Monday, 27 March 2023

Thursday, 23 March 2023

Completable feature

 https://www.callicoder.com/java-8-completablefuture-tutorial/

spring batch example

 steps for create spring batch application

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
public class MyFirstJob implements Tasklet {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("MyTaskOne start..");
List<Integer> mylist= Arrays.asList(1,2,3,4,5,6,6,67,7,7,7,7);
for(Integer number :mylist){
System.out.println("-------------"+number);
}

// ... your code

System.out.println("MyTaskOne done..");
return RepeatStatus.FINISHED;
}
}
 
public class MySecondJob implements Tasklet {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
List<String>mylist= Arrays.asList("pawan","ravi","mynme");
for(String name: mylist){
System.out.println("name---"+name);
}
return RepeatStatus.FINISHED;
}
}
 

@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobs;

@Autowired
private StepBuilderFactory steps;

@Bean
public Step stepOne() {
return steps.get("stepOne")
.tasklet(new MyFirstJob())
.build();
}

@Bean
public Step stepTwo() {
return steps.get("stepTwo")
.tasklet(new MySecondJob())
.build();
}

@Bean
public Job demoJob() {
return jobs.get("demoJob").incrementer(new RunIdIncrementer())
.start(stepOne())
.next(stepTwo())
.build();
}

}
 
 
 

@Configuration
public class AvoidMetadataConfiguration extends DefaultBatchConfigurer {
@Override
protected JobRepository createJobRepository() throws Exception {
MapJobRepositoryFactoryBean factoryBean = new MapJobRepositoryFactoryBean();
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
}
 
@Component
public class SpringJobSchedular {
@Autowired
JobLauncher jobLauncher;

@Autowired
Job job;

@Scheduled(cron = "* 0/1 * * * ?")
public void perform() throws Exception
{
System.out.println("------------------myjob in ----------------------");
JobParameters params = new JobParametersBuilder()
.addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();

jobLauncher.run(job, params);
System.out.println("------------------myjob in ----------------------");
}
}
 
 
 

Creating docker image from fresh

1. Create docker file

 Dockerfile

FROM openjdk

COPY ./target/myservice-0.0.1-SNAPSHOT.jar /usr/app/

WORKDIR /usr/app

RUN sh -c 'touch myservice-0.0.1-SNAPSHOT.jar'

EXPOSE 8089

ENV spring.profiles.active="local"


 2.Create image from docker file

 sudo docker build -t mylocalapp:1.0 .

mylocalapp is image name 

1.0 is tag 

 3.Create container from image 

sudo docker run -d -p 9090:80 --name pawancontainer mylocalapp:1.0

 

pawancontainer is container name

mylocalapp:1.0 is image name and 1.0 is tag name

4.sudo docker ps -a

list of all container

 

Docker image tutorial

 https://devopscube.com/what-is-docker/

Monday, 20 March 2023

Create a docker image

 https://devopscube.com/build-docker-image/

 

FROM ubuntu:18.04 LABEL maintainer="contact@devopscube.com" RUN apt-get -y update && apt-get -y install nginx COPY files/default /etc/nginx/sites-available/default COPY files/index.html /usr/share/nginx/html/index.html EXPOSE 80 CMD ["/usr/sbin/nginx", "-g", "daemon off;"]

Sunday, 19 March 2023

elastic search setup and query

 https://reflectoring.io/spring-boot-elasticsearch

 

docker run -p 9200:9200 \
  -e "discovery.type=single-node" \
  docker.elastic.co/elasticsearch/elasticsearch:7.10.0
sudo docker ps -a
list docker images 
sudo docker images ls
sudo start estic-container-id
 
curl --location --request PUT 'http://localhost:9200/messages/_doc/1' \
--header 'Content-Type: application/json' \
--data '{
"message": "Pawan is blue today"
}'
 
 
curl --location 'http://localhost:9200/_all/_search' \
--header 'Content-Type: application/json' \
--data '{
"query":{
"query_string":{
"query":"pawan"
}
}
}'
 

 https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html

 

Documentation for elastic search

 

Elastic search code implementation 

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Builder;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Builder
@Configuration
public class ElasticSearchConfig {

@Bean
public RestClient getRestClient() {

Header[] defaultHeaders = new Header[]{new BasicHeader("Content-type", "application/json"),new BasicHeader("X-Elastic-Product", "Elasticsearch")};
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).setDefaultHeaders(defaultHeaders).build();
return restClient;
    }

@Bean
public ElasticsearchTransport getElasticsearchTransport() {
return new RestClientTransport(
getRestClient(), new JacksonJsonpMapper());
}

@Bean
public ElasticsearchClient getElasticsearchClient() {
ElasticsearchClient client = new ElasticsearchClient(getElasticsearchTransport());
return client;
}
}

 

mport co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Repository
public class ElasticSearchQuery {
@Autowired
private ElasticsearchClient elasticsearchClient;

private final String indexName = "messages";


public String createOrUpdateDocument(Product product) throws IOException {

IndexResponse response = elasticsearchClient.index(i -> i
.index(indexName)
.id(product.getId())
.document(product)
);
if (response.result().name().equals("Created")) {
return new StringBuilder("Document has been successfully created.").toString();
} else if (response.result().name().equals("Updated")) {
return new StringBuilder("Document has been successfully updated.").toString();
}
return new StringBuilder("Error while performing the operation.").toString();
}

public Product getDocumentById(String productId) throws IOException {
Product product = null;
GetResponse<Product> response = elasticsearchClient.get(g -> g
.index(indexName)
.id(productId),
Product.class
);

if (response.found()) {
product = response.source();
System.out.println("Product name " + product.getName());
} else {
System.out.println("Product not found");
}

return product;
}

public String deleteDocumentById(String productId) throws IOException {

DeleteRequest request = DeleteRequest.of(d -> d.index(indexName).id(productId));

DeleteResponse deleteResponse = elasticsearchClient.delete(request);
if (Objects.nonNull(deleteResponse.result()) && !deleteResponse.result().name().equals("NotFound")) {
return new StringBuilder("Product with id " + deleteResponse.id() + " has been deleted.").toString();
}
System.out.println("Product not found");
return new StringBuilder("Product with id " + deleteResponse.id() + " does not exist.").toString();

}

public List<Product> searchAllDocuments() throws IOException {
SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
List<Hit> hits = searchResponse.hits().hits();
List<Product> products = new ArrayList<>();
for (Hit object : hits) {

System.out.print(((Product) object.source()));
products.add((Product) object.source());

}
return products;
}
}

 

Dependency required

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>8.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.6.2</version>
</dependency>
Header[] defaultHeaders = new Header[]{new BasicHeader("Content-type", "application/json"),new BasicHeader("X-Elastic-Product", "Elasticsearch")};
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).setDefaultHeaders(defaultHeaders).build();
return restClient;

 

Thursday, 16 March 2023

Spring AOP for logging

 @Aspect

@Component
public class LogMyMethodAspect {
private static final Logger logger = LoggerFactory.getLogger(LogMyMethodAspect.class);
@Around("@annotation(LogMyMethod)")
public void logMyMethod(ProceedingJoinPoint joinPointpawan) throws Throwable {
System.out.println("-----------------pawan----------------");
logger.info("service_identifier={},event={},game_session_id={},company_id={},player_id={},game_id={},action={},reason={},status={},data={}",
"CDS",
joinPointpawan.getSignature().getName(),
"",
"",
"",
"",
"refusing to start downstream processing",
"gameSessionID already processed",
"failed",
Arrays.stream(joinPointpawan.getArgs()).findFirst()
);
logger.info("service_identifier={},event={},game_session_id={},company_id={},player_id={},game_id={},action={},reason={},status={},data={}",
"CDS",
"submitEndGameDetails",
"",
"",
"",
"",
"refusing to start downstream processing",
"gameSessionID already processed",
"completed",
Arrays.stream(joinPointpawan.getArgs()).findFirst()
);
joinPointpawan.proceed();
}

@Pointcut(value = "execution(* com.huddle.gameservice.service.impl.GameProfileServiceImpl.*(..))")
private void logDisplay()
{
System.out.println("---------------controller method called--------------------");
}

@Around("execution(* com.huddle.gameservice.service.impl.GameProfileServiceImpl.*(..))")
public void
logBefore(ProceedingJoinPoint joinPointpawan)
{

System.out.println(
".............I WILL EXECUTE BEFORE EACH AND EVERY METHOD.............");
logger.info("service_identifier={},event={},game_session_id={},company_id={},player_id={},game_id={},action={},reason={},status={},data={}",
(Object) "CDS",
joinPointpawan.getSignature().getName(),
"",
"",
"",
"",
"refusing to start downstream processing",
"gameSessionID already processed",
"failed",
Arrays.stream(joinPointpawan.getArgs()).collect(Collectors.toList()).toString()
);
}

@Around(value ="execution(* com.huddle.gameservice.controller.GameProfileController.*(..))")
public Object logBeforeController(ProceedingJoinPoint joinPointpawan) throws Throwable {
System.out.println(".............Logging controller request.............");
logger.info("service_identifier={},event={},game_session_id={},company_id={},player_id={},game_id={},action={},reason={},status={},data={}",
(Object) "CDS",
joinPointpawan.getSignature().getName(),
"",
"",
"",
"",
"refusing to start downstream processing",
"gameSessionID already processed",
"failed",
Arrays.stream(joinPointpawan.getArgs()).collect(Collectors.toList()).toString()
);
return joinPointpawan.proceed();
}

Tuesday, 14 March 2023

Create own annotation in springboot

 https://fullstackdeveloper.guru/2021/06/15/how-to-create-a-custom-annotation-in-spring-boot/

 

 

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogMyMethodAnnotation {

}

 

@Aspect
@Component
public class LogMyMethodAnnotationAspect {

@Around("@annotation(LogMyMethodAnnotation)")
public void logMyController(ProceedingJoinPoint joinPoint){
System.out.println("pawankumar--------");
System.out.println("joinPoint"+joinPoint.getArgs().toString());
}
}

 

@LogMyMethodAnnotation
@RequestMapping(method = RequestMethod.GET, value = "game/get_game_profile_data")

 

 

Friday, 10 March 2023

how to install docker in linux

 

1. Open the terminal on Ubuntu.

2. Remove any Docker files that are running in the system, using the following command:

$ sudo apt-get remove docker docker-engine docker.io

After entering the above command, you will need to enter the password of the root and press enter.

3. Check if the system is up-to-date using the following command:

$ sudo apt-get update

4. Install Docker using the following command:

$ sudo apt install docker.io

You’ll then get a prompt asking you to choose between y/n - choose y

Learn Concepts - Basics to Advanced!

Caltech Program in DevOpsEXPLORE PROGRAM
Learn Concepts - Basics to Advanced!

5. Install all the dependency packages using the following command:

$ sudo snap install docker

6. Before testing Docker, check the version installed using the following command:

$ docker --version

7. Pull an image from the Docker hub using the following command:

$ sudo docker run hello-world

Here, hello-world is the docker image present on the Docker hub.

8. Check if the docker image has been pulled and is present in your system using the following command:

$ sudo docker images

9. To display all the containers pulled, use the following command:

$ sudo docker ps -a

10. To check for containers in a running state, use the following command:

$ sudo docker ps

Monday, 6 March 2023

Redis Stream

 1.Create:-  XADD mystream * mydata '{"name":"pawan"}'

 2.Read:-  XREAD COUNT 100 STREAMS mystream  0

3.Lenth:- XLEN mystream

4.List data with rang:- XRANGE mystream - +
 

 

 

Sunday, 5 March 2023

Rest client

 https://howtodoinjava.com/spring-webflux/webclient-get-post-example/

https://www.baeldung.com/java-reactor-flux-vs-mono


https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/