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...!!

Sunday, December 10, 2017

Spring - Execute a init method when initializing bean and destroying bean.

There are couple of ways to achieve this requirement.

First methodology
You can simply implements below interfaces in the bean

  • InitializingBean
  • DisposableBean
Then you have to override below methods respectively above interfaces. 

  • afterPropertiesSet()
  • destroy()
Note: You have to use registerShutdownHook (link) to see the effect of the destroy method.

Second methodology
In this scenario, I would like to introduce the way we can execute the custom method when initializing and destroying beans.

Initially, you have to implement custom methods for init and destroy as below
    public void myInit() {
        System.out.println("This is the custom init method");
    }
....
    public void myDestroy() {
        System.out.println("This is the custom destroy method");
    }

In the bean configuration file you have to tell to the Spring what are the init and destroy methods as below.
<beans>
    <bean id="student" class="com.home.model.Student" init-method="myInit" destroy-method="myDestroy">
        .....
    </bean>
.....
.....
</beans>

Enjoy...!!!


Tuesday, December 5, 2017

Spring - How to destroy beans when application shutdown? (registerShutdownHook)

If someone needs to destroy the beans when shutdown then application, what you need to do is:
  • Create a 'AbstractApplicationContext'
  • call the 'registerShutdownHook'
Find the below code for your reference

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();

Once this "registerShutdownHook()" method executes, it destroy the beans when down the application.


Enjoy..!!

Sunday, September 24, 2017

Lambda (Java 8) - Transfer one type of object to another type of object

We will assume that we have list of Students to convert into list of Persions.

public class Student {
    private String name;
    private String school;
    private int age;

    public Student(String name, String school, int age) {
        this.name = name;
        this.school = school;
        this.age = age;
    }

    // getters/setters should come here

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", school='" + school + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Person {
    private String fullName;
    private int age;

    public Person(String fullName, int age) {
        this.fullName = fullName;
        this.age = age;
    }

    //getters/setters should come here

    @Override
    public String toString() {
        return "Person{" +
                "fullName='" + fullName + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

In this article, I'm going to use functional interface call Funcation to achieve this.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class StudentApplication {
    public static void main(String[] args) {
        Function<Student, Person> functionStuToPer = student -> new Person(student.getName(), student.getAge());

        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        List<Person> persons = convertStudentListToPerson(students, functionStuToPer);
        persons.forEach(System.out::println);

    }

    private static List<Person> convertStudentListToPerson(List<Student> students, Function<Student, Person> functions) {
        List<Person> persons = new ArrayList<>();
        for (Student student: students) {
            persons.add(functions.apply(student));
        }
        return persons;
    }
}


Enjoy...!!

Lambda (Java 8) - How to sort and filter array

In this article, I'm going to explain about the way we can sort and filter an array using lambda expressions.

TASK 1

We will assume that, we have a list of students as follows:
 List<Student> students = Arrays.asList(
         new Student("Tharanga", "UOC", 22),
         new Student("Ruwan", "UOM", 24),
         new Student("Ruvini", "UOK", 20),
         new Student("Randika", "TOUC", 25),
         new Student("Amara", "UOR", 23)
);

In this scenario, we will assume that we have to sort the students by name:

Initially, how we cater this without lambda expression:
Collections.sort(students, new Comparator<Student>() {
       @Override
       public int compare(Student o1, Student o2) {
           return o1.getName().compareTo(o2.getName());
       }
});

Now will cater this requirement with lambda expressions.
 Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

Note: Since 'Comparator' interface is a functional interface we can sort the object list as above.

TASK 2

In here, we will assume that we need to filter the students, name starting with 'R'

Without lambda expression we can achieve this as below.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StudentApplication {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

        printConditionally(students, new Condition() {
            @Override
            public boolean test(Student student) {
                return student.getName().startsWith("R");
            }
        });

    }

    private static void printConditionally(List<Student> students, Condition condition) {
        for (Student student: students) {
            if(condition.test(student)) {
                System.out.println(student);
            }
        }
    }
}

interface Condition {
    boolean test(Student student);
} 

How we achieve this using lambda expression.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

public class StudentApplication {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Tharanga", "UOC", 22),
                new Student("Ruwan", "UOM", 24),
                new Student("Ruvini", "UOK", 20),
                new Student("Randika", "TOUC", 25),
                new Student("Amara", "UOR", 23)
        );

        Collections.sort(students, (o1, o2) -> o1.getName().compareTo(o2.getName()));

        printConditionally(students, student -> student.getName().startsWith("R"));

    }

    private static void printConditionally(List<Student> students, Predicate<Student> predicate) {
        for (Student student: students) {
            if(predicate.test(student)) {
                System.out.println(student);
            }
        }
    }
}

Note: Java 8, OFTB support many functional interfaces such as "Predicate". You can find more on here.

Note: Find more information about funcational interfaces here.