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();

}


Map to List Using Guava

Suppose, we have a list of Employee objects where we want to create a Map from the list with employee id as Key. You can do that with Java S...