Thursday, November 22, 2018

Spring Boot (Microservice) - Inter service call

Generally, inter service call more common, when we develop a microservice application. So in this artical, I'm going to explain, how to use RestTemplate to call another service.

We have eurekaServer, zuulServer, clientServer, serverServer. Initially, we need to register our all servers with the eurekaServer.
zuulServer register as proxyService
clientServer register as oneService
serverServer register as twoService

twoService has a end-point as below:
http method: PUT
url: /api/person/{personId}/bank

this end-point is going to update the bank information in particulate person and we need to pass the bank details in the body. As below, you can call above end-point in twoService from oneService.

    @Autowired 
    private final RestTemplate restTemplate;
    @Autowired 
    private final EurekaClient eurekaClient;
   .....
   .....
    public CustomResponseMessageDTO method() {
     ....
        String endPoint = "/api/person/{personId}/bank"
        HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object);
        Map<String, String> param = new HashMap<>();
param.put("personId", "person_id_should_pass");
        Application application = eurekaClient.getApplication(twoService);
        InstanceInfo instanceInfo = application.getInstances().get(0);
        String url = "http://" + instanceInfo.getIPAddr() + ":" + instanceInfo.getPort() + endPoint;
        ResponseEntity<CustomResponseMessageDTO> exchange = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, CustomResponseMessageDTO.class, param);
        return exchange.getBody(); // this return the CustomResponseMessageDTO object.
    }
....
As above, you can pass the message body using HttpEntity and url paramerter using HashMap.

If you need to pass the header you can add the header to the HttpEntity as below
HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object, HttpHeaders_object);

Enjoy..!!!

Spring Boot - Read yml file

When developing a Spring Boot application, we are using yml (properties) file to store the data. Due to this without we don't want to re-build the source code after change the property values.

Even thought this a very basic thing, in this article, I'm going to explain the way we can get the data from yml file.

For this explanation, I'm going to take application.yml file and we have a property as below
company:
  name: Company ABC

Then we can get this value in java code as below
public class TestApplication {
...
@Value("${company.name}")
        private String companyName;
...
}

This value will cast to the variable type.

Enjoy.....!!!

Thursday, June 21, 2018

No 'Access-Control-Allow-Origin' header is present on the requested resource.

In this blog I'm try to explain the way we can solve above issue from the "SpringBoot" side.

I faced the below issue with calling my service through the React.
Failed to load http://xx.xx.xx.xx:8080/api/yy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.xx.xx.xx:3000' is therefore not allowed access.

Default, it didn't set the "Access-Control-Allow-Origin" header. So, you can solve this as below.

1. Create a filter as below
 
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter extends GenericFilterBean implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        //httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        //httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        //httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
        //httpResponse.setHeader("Access-Control-Max-Age", "3600");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

Add if you need add more headers you can add as above.

2. In the main application you have to set the @Bean as below
@SpringBootApplication
@EnableMongoRepositories(basePackages= {"com.home"})
@EntityScan(basePackages = {"com.home"})
@EnableEurekaClient
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
        registrationBean.setName("CORS Filter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}


After this, when you execute the service you can see the 'Access-Control-Allow-Origin' in the header.

Enjoy...!!!

Friday, March 2, 2018

The way we can use 'intellij community edition' to debug tomcat application:

 Environment configurations use for this explanation:

        #  apache-tomcat-7.0.85
        #  IntelliJ IDEA 2017.3.2 (Community Edition)

Steps:

1. Build the project and put the war file into the webapps folder(<tomcat_home>/webapps/).

2. Intellij IDEA
    a) Run -> Edit Configurations
    b) Press the green + and select 'Remote'
    c) Give a proper name (Ex: debug-demo)
    d) Set the host and port(not the tomcat running port number. better to keep the default 5005)
    f) Select the 'Search sources using module's classpath (better to select root)
    g) Copy the 'Command line arguments for running remove JVM'
    Ex: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

3. Tomcat
    a) Open the 'setclasspath.sh'
    b) Set the above copied 'Command line arguments for running remove JVM' value to the  'JAVA_OPTS'. To do that, paste the below line at the end of the file:
JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
    c) Start the tomcat
        Ex: sh startup.sh

4. Intellij IDEA
    a) Select the 'debug-demo' according to our example
    b) Press 'Debug' icon (Shift+9)

Then you can see the connected message in the console as below:
Connected to the target VM, address: 'localhost:5005', transport: 'socket'

Enjoy...!!!

Friday, January 26, 2018

How to connect MySql 5.x using Hibernate 5

In this post, I'll discuss below points

  • How to create 'SessionFactory' and 'Session'
  • How to choose  'dialect'
Create 'SessionFactory' and 'Session'

Hibernate 5 comes with major changes and they change the way we can building 'SessionFactory'

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

....

StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
SessionFactory sf = metadata.getSessionFactoryBuilder().build();
Session session = sf.openSession()

...
Select 'dialect'.

In hibernate 5, we can below below dialects when connecting to the MySQL


  • org.hibernate.dialect.MySQL5Dialect
  • org.hibernate.dialect.MySQL55Dialect
  • org.hibernate.dialect.MySQL57Dialect

Note: org.hibernate.dialect.MySQLDialect is for MySQL 4.x or earlier.

Enjoy...!!