Monday, November 28, 2022

Running a continuos job using Reactor

In this section we will try to execute a job at a certain interval, using Spring Reactor framework. The job should be defined in the subscribe method.

Maven Dependency:

<dependency>

    <groupId>io.projectreactor</groupId>

    <artifactId>reactor-core</artifactId>

    <version>3.4.24</version>

</dependency> 

Code Snippet:

Running a job at a certain interval (10 sec) forever.

Mono.just("SD").delaySubscription(Duration.ofSeconds(10)).repeat(()->true).subscribe(a->System.out.println(a));

Wednesday, September 14, 2022

Installing Kotlin on Eclipse

Recently I have faced problem to install Kotlin Plugin for Eclipse IDE. As per the StackOverflow post  the plugin has been removed. The nelwy forked linked that can be used to install Kotlin in Eclipse is

https://github.com/bvfalcon/kotlin-eclipse-2022


Sunday, April 17, 2022

AWS Translate using AWS JS SDK

 In this post, I will discuss how to use AWS Javascript SDK V3 for AWS Translate.

Prerequisite: Node.js should be pre-installed

Steps:

  • Create a folder e.g. AWSTranslateApp
  • From command prompt navigate to folder "AWSTranslateApp"
  • Type npm init
  • This will create Node project
  • Install AWS JS SDK by typing "npm install @aws-sdk/client-translate" under folder "AWSTranslateApp"
  • Now open the "AWSTranslateApp" folder in VS Code
  • Create a file translateExample.js

Below is the code snippet for translateExample.js

const { TranslateClient, TranslateTextCommand } = require("@aws-sdk/client-translate");

 async function getTranslatedData(){

  const client = new TranslateClient({ region: "<region_name>", 

  credentials: {

    accessKeyId: '<access_key>', 

    secretAccessKey: '<secret_key>'

  } 

});

  const params = {

    SourceLanguageCode: "en",

    TargetLanguageCode: "es",

    Text: "Hello, world"

  };

      const command = new TranslateTextCommand(params);

      const data = await client.send(command);   

      const jsonData =await data.TranslatedText;

      console.log(jsonData);

  }

 getTranslatedData();


  • Replace the region, access key, secret key with the actual values. In my case the region was 'us-east-1'.
  • Once done, you can now run the program using below command from command prompt

        node translateExample

References:

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-translate/index.html



Saturday, April 9, 2022

AWS Service Call from Java SDK

 Here in this post I will discuss how to use AWS Translate Service from Java Code.

Steps:

1. Add the below dependency in pom.xml

<dependency>

    <groupId>com.amazonaws</groupId>

    <artifactId>aws-java-sdk-translate</artifactId>

    <version>1.12.194</version>

</dependency>

2. Add below imports in Java File

import com.amazonaws.auth.AWSStaticCredentialsProvider;

import com.amazonaws.auth.BasicAWSCredentials;

import com.amazonaws.regions.Regions;

import com.amazonaws.services.translate.AmazonTranslate;

import com.amazonaws.services.translate.AmazonTranslateClient;

import com.amazonaws.services.translate.model.TranslateTextRequest;

import com.amazonaws.services.translate.model.TranslateTextResult;

3. Below is the code snippet; provide the accessKey & secretKey to access the service

BasicAWSCredentials credentials = new BasicAWSCredentials("<access_key>",
"<secret_key>");
AmazonTranslate translate = AmazonTranslateClient.builder()
.withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();
TranslateTextRequest request = new TranslateTextRequest().withText("Hello, world").withSourceLanguageCode("en")
.withTargetLanguageCode("es");
TranslateTextResult result = translate.translateText(request);
System.out.println(result.getTranslatedText());

AWS Service Call from Postman

Many of the times you need to use AWS services via Postman for testing.

I am using Amazon Translate Service, below are the configuration made to call the service:

In Postman choose the Post method for call

Service URL: https://translate.us-east-1.amazonaws.com/

In "Authorization" tab choose "Type" "AWS Signature"

Provide AccessKey, SecretKey, AWS Region, Service Name

The region I am using is "us-east-1" , Service Name will be "translate"

Then Move to "Headers" tab & add the following Headers

Content-Type: application/x-amz-json-1.1

X-Amz-Target: AWSShineFrontendService_20170701.TranslateText

N.B. X-Amz-Date will be generated by Postman automatically

Under "Body", select "raw", and added the following sample body:

{
    "SourceLanguageCode": "en",
    "TargetLanguageCode": "es",
    "Text": "Hello, world"
}

Now hit the Send button & check the result.

Clicking on the "Code" in Postman you can also get the cod for Java/Node JS and many other languages.

Helpful Links:

https://stackoverflow.com/questions/59128739/how-to-use-aws-translate-translatetext-api-via-postman

https://docs.aws.amazon.com/translate/latest/dg/API_Reference.html

Wednesday, March 30, 2022

Maven Repository configuration in pom.xml

Many a times you might face to downlod maven dependency in Jenkins due to netwok issue. In that case, Maen repository needs to be configured in pom.xml.

Below is the snippet you can use to configure maven repo.

<project>

..................

    <repositories>

<repository>

<id>central</id>

<name>Central Repository</name>

<url>https://repo.maven.apache.org/maven2</url>

<layout>default</layout>

<snapshots>

<enabled>false</enabled>

</snapshots>

</repository>

</repositories>


<pluginRepositories>

<pluginRepository>

<id>central</id>

<name>Central Repository</name>

<url>https://repo.maven.apache.org/maven2</url>

<layout>default</layout>

<snapshots>

<enabled>false</enabled>

</snapshots>

<releases>

<updatePolicy>never</updatePolicy>

</releases>

</pluginRepository>

</pluginRepositories>

    

</project>

Thursday, March 10, 2022

Calling external services using RestTemplate

 Though today's date, microservice with  Spring boot is a very popular architecture; but along with new architectural apps we need to maintain legacy apps also.

In legacy apps, we will often found external http calls. In my case, most of the times I found the legacy code is using Apache commons httpclient or plain java http calls.

One of the common mistake is, after making the call we often leave the http connection open instead of closing. This causes probelm when the called service is down & in those cases the calling apps will have memory issue.

To solve this, we can  use Spring RestTemplate instead of  other http clients. The main reason is, the code is tiny & crisp ; also the closing of connection is also handled by Spring.

Steps:

1. Add below maven dependency:


        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-web</artifactId>

            <version>3.0.6.RELEASE</version>

        </dependency>

2. Below is a sample code: Assumption is Code is sending JSON request & receiving JSON response


public static String callRestService(String serviceUrl, String strRQ) {

SimpleClientHttpRequestFactory clientHttpRequestFactory= new SimpleClientHttpRequestFactory();

//Connect timeout in milisec.

clientHttpRequestFactory.setConnectTimeout(1000);


//Read timeout in milisec

clientHttpRequestFactory.setReadTimeout(1000);

RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(strRQ, headers);

ResponseEntity<String> response=restTemplate.exchange(serviceUrl, HttpMethod.POST, entity, String.class);

return response.getBody();

}


Convert Java Project from Log4j 1 to Log4j2

Many times while working on old Java projects we find Log4j 1.x is used. But as the Log4j2 is the new one; hence to upgrade to Log4j2 we nee...