Thursday 3 November 2022

SpringBoot

SpringBoot

  • SpringBoot Application : 

    • Pros & Cons : 

  • SpringBoot Application creation using spring.io : 

  • SpringBoot Application Annotations : 

                    @SpringBootApplication : 
                            @SpringBootConfiguration
                            @EnableAutoConfiguration
                            @ComponentScan
                        
  • SpringBoot Application RestApi representation : 

  • SpringBoot Application RestApi with SpringJpa with CRUD operations :

  • Create

  • Insert

  • Update

  • Delete

  • SpringBoot Application RestApi with JPA Repository with Relationships : 

  • One to many

  • Many to one 

  • Many to many

  • One to one



Spring boot Interview Based Questions

Annotations

@SpringBootApplication : will take care of everything

@SpringBootConfiguration : will take about the configurations

@EnableAutoConfiguration : it configures the classpath beans

@ComponentScan : will scan all the classes 

ex : adding mongo dependency in the pom but beans no need to specify, enable auto configuration will take care.


SpringBoot Console Application : 

    


Diff between SpringBootConfiguration vs EnableAutoConfiguration


@Sterotype :

@Service :

@Controller :

@Componet :


@ResponseBody :

@ResponseEntity :


@Lazy :

IOC vs Dependency Injection :

    Earlier we are provind the dependency injection in xml but after spring boot comes its easy to inject the bean using @Autowired.


Diff mvc and spring boot ::
                Springboot                                            SpringMVC
    ==> embeded server                                        ==> need to configure the server
    ==> embeded db                                                ==> need to configure the db
    ==> faster development                                     ==> takes time to develop
    ==> avoid boilerplate code                                

SpringProfiling : using Profile we can instantiate the bean to the particular env.

For dev env we can instantiate the few beans for production we can instantiation using spring profiling.


Retry mechanism : 

@EnableRetry is used to retry the springboot application. It will retry the calls when exception occurs.

@Retryable(value=RuntimeException.class)


What is the starter dependency of the Spring boot module : web starter, Test starter , Data JPA starter.

How can you configure the RestTemplate in Spring not springBoot : 
        ==> ApplicationContext ctx = new AnnotationConfigApplicationContext(RestTemplate.class)
                RestTemplate rs = ctx.getBean(RestTemplate.class);

How can you secure your api in Spring not SpringBoot(SpringWebFilter)
        @EnableWebSecurity and overrride the configure(HttpSecurity http) method

When the beans will destroy in SpringBoot : 

When the beans will initialize : By Starting the springboot tomcat server or applicaiton starting time.

Bean Life Cycle :    
            ==> ContainerStarted --> Bean instantiated --> Dependcies injected --> Init() -> destroy()
    
Spring Actuator Apis : 
            ==> Health check purpose 
            ==>  /health
            ==> / beans
            ==> /caches
            ==> /configProps
            ==> /env
What is thymeleaf?
   
Spring cloud config server : 

GraphQL : Graphql is a query language to retrive the data from servers. Its a alternative to SOAP and REST and GRPC. 
The main steps of creating a GraphQL Java server are:
  1. Defining a GraphQL Schema.
  2. Deciding on how the actual data for a query is fetched
GraphQL offers a solution to both of these problems. It allows the client to specify exactly what data it desires, including from navigating child resources in a single request, and allows for multiple queries in a single request.
It also works in a much more RPC manner, using named queries and mutations, instead of a standard mandatory set of actions. This works to put the control where it belongs, with the API developer specifying what's possible, and the API consumer specifying what's desired.

2 Piller of GraphQL : 
  1. GraphQL Schema
  2. GraphQL Query Language

Thursday 27 October 2022

Email Sending Configuration


Email Configuration


Step 1 : Need Spring Email Dependency 
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Step 2 : Required Email properties 
Properties props = new Properties ();
props.put ("mail.smtp.auth", Boolean.TRUE);
props.put ("mail.smtp.starttls.enable", Boolean.TRUE);
props.put ("mail.smtp.host", "smtp-mail.outlook.com"); // gmail : smtp-mail.gmail.com
props.put ("mail.smtp.port", "587");

Step 3 : Use below code to send email using springboot application 
try
{
Session session = Session.getInstance(
props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("user-email", "user-password");
}
})
;
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("user-email", false));

msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse("user-mails"));

msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("user-email"));
msg.setSubject("Email Configuration");
msg.setSentDate(new Date());

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("MESSAGE_BODY",
MediaType.TEXT_HTML_VALUE);

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(file);
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
}
catch (Exception exe)
{
log.error ("error @ Email sending {} ", exe);
}

Tuesday 11 February 2020

Linux Commands

To Kill the Running ports

  • netstat -ano | findstr :8080
  • taskkill /PID 25864 /F


Run SpringBoot : mvn spring-boot:run

Wednesday 19 June 2019

Kubernetes Commands

Enter into the Deployment machine :
==> ssh -A core@<ipaddress> -i <name>.pem

Enter into api deployment machine
==> ssh core@<ipaddress>

To deploy the helm use below command
==> helm upgrade --recreate-pods <project-name>  <project-name> -f  <project-name>/values.yaml

To know the ip
==> helm status  <project-name>

To Find any command
==> Ctrl + r

To Install the helm in machine :
==> helm install  <project-name> -n  <project-name> -f  <project-name>/values.yaml


To Check the logs :
==>  kubectl logs -f <pod-name>

To check the latest 500 Logs :
==>  kubectl logs --tail 500 -f pod name

To find the names or folders :
==>  ls |grep <pod-name>

To get the pod name :
==> kubectl get pods | grep saas

To enter into the pod tomcat:
==> kubectl exec -it <pod-name> sh
==> kubectl exec -it <pod-name> bash

To Delete the pods
=============
To find the perticular logs in POD
==> kubectl logs -f <pod-name> | grep "any logger message "

To Delete/Stop the Pod :
==> helm del --purge  <project-name>

To Copy the logs from the remote pod machine
==> kubectl cp <pod-name>:usr/local/tomcat/logs .




## Helm
helm create saas-api                                                                    - Create helm folder structure 
helm lint saas-api                                                                        - Verify Yaml file from template
helm install saas-api --dry-run --debug        - Perform dry run which will replace value from values.yaml file to template yaml file

helm status saas-api                                                                    - Check the status of component
helm list                                                                                      - Get the list of deployed component

helm install saas-api -n seas-api -f saas-api/value.yaml             - Install component basically it will create new pods. Here first folder name is “Release name” second name is component folder name

helm upgrade --recreate-pods saas-api seas-api -f saas-api/values.yaml       - First give release name then folder name
helm upgrade --recreate-pods saas-api saas-api -f saas-api/values.yaml -f saas-api/values-harman-dev.yaml                                                                               - To replace values other than default

## K8S - Basic Commands:
kubectl get pods                                                                            - List all the pods
kubectl get pods |grep mess                                                          - This will list device message component pods
kubectl describe pods <pod-name>                                              - Shows the description of pods like which image is runnung stuff like that
kubectl get svc                                                                              - List all the service names
kubectl get svc|grep mess                                                             - Shows the service name with ip
kubectl apply -f <yaml file name>                                               - Start component
kubectl exec <pod-name> -it sh                                                   - Get into pod container
kubectl describe services device-message-api-int-svc              - Describes the given service

## Internal Service Name:
kubectl exec -it busybox -- nslookup 10.233.7.69
kubectl get svc -o wide | grep vault


## Log:
kubectl logs -f <pod-name>                                                            - Show component logs
kubectl logs --tail 10 -f <pod-name>                                              - Show component logs last 10 lines
kubectl logs --since 5m -f <pod-name>                                          - Show component logs since 5 mins


Run Command in Pods:
kubectl exec my-pod -- ls /


Delete:
kubectl delete pods <pod-name>
kubectl delete configmaps <configmap-name>


Mongo:
~~~~~~
kubectl exec -it mongo-qr-mjrcz bash
mongo --port 27017 admin -u admin -p 5D0c72dz4bxl

Postgres:
~~~~~~~~~
kubectl exec postgres-0 -it bash psql -U postgres

## Connect To Postgres in Kubernetes Env
kubectl exec postgres-0 -it bash psql -U postgres

See ELB:
kubectl get svc|grep comp
kubectl describe services vehicle-compatibility-api-ext-svc


Note: saas-api is the component name in this list.


Thursday 23 May 2019

GIT Commands


Step 1: Clone the project into local folder :
$ git clone <reviewbd url>
Step 2: Copy the project folder into the Local Folder
Step 3: To check the status use below command :
$ git status
Step 4: Add the Project Folder into repository.
$ git add <ProjectName>/
Step 5: Commit the Project/Files
$ git commit -m "initial commit for git and review"
Step 6: To check the repositories use below command
$ git remote -v
Step 7: To add the project into Remote location
$ git remote add origin git@<remoteServerip>:user1/user-project.git
Step 8: To Push the code
git push origin master
(OR)
git push origin HEAD:refs/for/master
Step 9: At any point you can view the history of your changes using
$ git log
Step 10: Create a new Branch
$ git branch <branch-name>
Step 11: To Check-out the branch
$ git checkout <branch-name>
Step 12: To Merge the code into master
$ git merge <branch-name>
Step 13: To Pull the code
$ git pull /home/lputta/ProjectName master
ex : git pull origin HEAD:refs/for/master
Step 14: To Tag the code
$ git tag v1.0 <Commit_Id>
Step 15: To check the difference
$ git diff
Step 16: To checkout files
$ git checkout <file-name-with-full-path>
ex : git checkout src/deploy/kubernetes/test.yaml
Step 17 : To reset the code changes
$ git reset --hard <change-Id>
ex : git reset --hard adsfadsf3434343da123dsfda11
Step 18 : To reset all the code changes
$ git reset .
ex : git reset . 
Step 19 : To Resolve the Merge Conflicts
i) git pull ==> if you get Merge Conflicts in your files.
ii) Take a back up of your files.
iii) Use git stash command to stash your changes
$ git stash
iv) Now again do pull you will get latest code.
$ git pull
v) Use pop command for merge with your changes in latest code.
$ git stash pop
vi) You will see some conflicts in your fles, please merge your changes in your workspace and commit your changes.

BitBucket Migration from GIT :

Process of Bitbucket migration

1. create repo “service-name” under https://bitbucket.elife.com/projects/lks

2. git clone ssh://lputta@reviewbd.harman.com:29440/services/service-name temp-dir

3. cd temp-dir

4. git remote set-url origin ssh://git@bitbucket.elife.com:7999/lks/service-name.git

5. git push -u origin --all 

6. git push origin —tags (Move all tags into the bitbucket)

Moving the sub-folder from Gerrit to bitbucket.
https://docs.github.com/en/get-started/using-git/splitting-a-subfolder-out-into-a-new-repository
https://ao.ms/how-to-split-a-subdirectory-to-a-new-git-repository-and-keep-the-history/

        1. git clone ssh://lokesh@reviewbd.elife.com:29440/service-name

        2. cd service-name

        3. git checkout master

        4. git filter-branch --prune-empty --subdirectory-filter service-name master

        5. create repo “service-name” under https://bitbucket.elife.com/projects/plk

        6. git remote set-url origin ssh://git@bitbucket.elife.com:7999/plk/service-name.git

        7. git push -u origin --all

        8. git push origin --tags


Wednesday 29 August 2018

Lombok Plugin

Lombok Plugin implementation (To Avoid Setters and Getters in Pojo's and Entitties)

Step 1: Add lombok latest dependency in pom.xml.

<dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
          <version>1.18.2</version> 
         <scope>provided</scope> 
</dependency>

Step 2: Add or copy lombok jar in sts or eclipse(Where the location of Eclipse or STS installation).

Step 3: Open command prompt and move to eclipse location and type below command.
java -jar lombok-1.18.2.jar

Step 4: After above step it will open a small UI like below 

Step 5: Click on install and specify the installation location of sts or eclipse.

Step 6: Remove all setters and getters in Entity and Pojo's and add @Data annotation in that.

Step 7: Update the Maven update once.



Tuesday 20 February 2018

Internal Collection working

HashMap Internal Working

HashMap always works based on Hashing. Because which helps to faster search.
HashMap having put(Object k, Value v) and get(Object k) methods.
Will see How HashMap works Internally by using these 2 methods.

Bucket : Bucket is one element in HashMap Array. Nodes can store into the bucket. 2 or more nodes are same in each bucket then it will store by using linked list as like below.

Key k = "king"
Value v = "100"
put(Key k, Value v) 
{
       hash(k) ->1021467
       index = hash & (n-1) -> 3
}

Based on key will find the HashValue
Based on HashValue will find the IndexValue.
HashValue & key & value will sit. @ indexValue,
If it same Index it will store in next node of Linked List.(Because in linked list always last node is null).


get(Object key)
{
hash(key) -> 1021467
index = hash & (n - 1) ->3
}

Based on Key value it will find the HashValue.
Based on Hashvalue it will find the Index.
Based on Index value it will return the value of that key.

If Index  value is same for different key then it will take the Hash Code and compares and return the value.

Ex : Key = "King" then Hashvalue = 1021467 so it return index = 3. Based on index and hashvalue it return the value = 100.
If Key = "Queen" then HashValue = 1024241 so it return index = 3. Both index are same so now it take the Hash value and compare in another node of the linked list. If both Hash values are same then it will return the value= 90.

ArrayList Internal Working



LinkedList Internal Working


SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...