Friday, September 25, 2020

Consumer and Bi-consumer functional interface java

Functional Interface:

Functional interface is an interface that contains only one abstract method. A functional interface can have any number of default methods.
Consumer, Bi-consumer, Runnable are some example of functional interface. Annotation @FunctionalInterface is not mandatory however @FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method

Consumer :

@FunctionalInterface

public interface Consumer < T > {

    void accept(T t);

}

 public class ConsumerImpl {
public static void main(String args[]) {
List<String> strList = Arrays.asList("one","two","three");
strList.forEach(new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
});
}
}

OR Lambda format

java.lang.Iterable.forEach() method internally uses Consumer interface. 

public class ConsumerImpl {
public static void main(String args[]) {
List<String> strList = Arrays.asList("one","two","three");
strList.forEach(x->System.out.println(x));
}
}

Bi-Consumer : 

@FunctionalInterface

public interface BiConsumer<T, U>

Sample code:

public class BiConsumerImpl {

public static void main(String args[]) {

Map<Integer,String> map = new HashMap<>();

map.put(1, "one");

map.put(2,"two");

map.put(3,"three");

map.forEach(new BiConsumer<Integer, String>() {

@Override

public void accept(Integer arg0, String arg1) {

System.out.println(arg0 +"---"+arg1);

}

});

}

}

Labels: , ,

Thursday, September 24, 2020

Keystore and Truststore - SSL

Keystore (JKS):

In context of SSL / TLS, keystore is where server / or client store its certificate and private key This is required when you are going to authenticate yourself to remote connection.
There is a scenario where client want to access any service from server and the connection between is TLS 2 way. In that case when client makes a call to server, server respond with its certificate which client validates from CA truststore. In reply client also sends its certificate which server will identify using its truststore CAs.

Truststore:

Java comes with default trust store JRE / lib / security / cacerts.
Truststore store all CA's(certificate authorities) certificates. These CA will verify the certificate presented by server.





Labels: , , ,

kahaDB ActiveMQ

kahaDB is a file based persistence database. Message broker use this to store messages.
In a scenario where you want to schedule or delay the messages in activeMQ, Message broker use kahaDB to store the message before send to message que after predefined time interval.

Use case where we have used kahaDB to schedule activemq.

https://explainjava.blogspot.com/2020/08/schedule-or-delay-message-activemq.html


Labels: , ,

Sunday, September 20, 2020

Java 8 Stream (java.util.stream)

Java 8 Stream (java.util.stream)

Stream :

A stream is not a data structure; it takes input from underlying Collections, Arrays or any other objects. Stream work on underlying object and don’t change the original object. There are various intermediate operations on stream which returns a stream again. There is also terminal operation which terminates the process and collect the result.

In a nut shell stream is wrapper around underlying data which has multiple operation to allow process the bulk data operation easily.

Create stream;

    1.   We can create stream using collection.

          Stream strm =  listObject.stream();

    2.    Using array Object

           Stream strm = Stream.of(array);

    3.    Using any String or Integer value.

           Stream<Integer> strm =  Stream.of(1,3,4,6,4);

    4.    We can create empty stream

            Stream<String> emptyStream = Stream.empty();

    5.    Using Stream builder

            Stream builder= Stream.builder();

            Stream<String> strm =   builder.add("A").build();


Intermediate operations

Java 8 stream has intermediate operations which return itself a stream. Intermediate operations don't get executed until terminal operations called. All Intermediate operations are lazy.

1.    Stream filter( Predicate predicate)
      
        example:
        Stream strm = Stream.of(1,4,6,2,3);
        Stream strm2 = strm.filter(value -> value >4)
        long counter = strm2.count();

2.    map function :
        It returns a stream consisting of the results of replacing each element of the given stream with the         contents of a mapped stream.
        Suppose we have stream of Integer and we we want to convert each integer value multiply by 2.
        We can achieve this using map().
        
        List<Integer> list = Arrays.asList(5,3,6,7);   
        list.stream().map(num -> num * 2).forEach(System.out::println);

3.  flatmap :
        
        flatmap() is a combination of map & flat operation,  it applies function on element and flatterns             them.

        { {1,2}, {3,4}, {5,6} } -> flatMap -> {1,2,3,4,5,6}

Terminal operation

1.    collect :
        Return the result of intermediate operation.

        List<String> strm = Arrays.asList("one","two","three","four");
        List<String> data = strm.stream().filter(s -> s.startsWith("o")).collect(Collectors.toList());

2.    forEach :
        Iterate through the elements in the stream

        List<String> strm = Arrays.asList("one","two","three","four");
        strm.stream().filter(s -> s.startsWith("o")).forEach(s -> System.out.println(s));

3.    reduce :

Labels: , , , , , , , ,

Enabling cross origin requests for restful web services - spring boot

Enabling cross origin requests for restful web services - spring boot CORS

Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served


1.   Add following component class

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

 @Override
    public void destroy() {

    }

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT,OPTIONS,PATCH");
response.setHeader("Access-Control-Allow-Headers","Authorization,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
 response.setHeader("Access-Control-Allow-Credentials", "true");
 response.setHeader("Access-Control-Max-Age", "180");
 filterChain.doFilter(req, res);
}
}


2.    Add the following piece of code inside you WebSecurity Configuration class to                                  enable custom CorsFilter 

@Autowired
CorsFilter myCorsFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.addFilterBefore(myCorsFilter, SessionManagementFilter.class)
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}



Labels: , , , , ,

Tuesday, September 8, 2020

Call javascript function from java

 Call any function in JavaScript(JS) file from java code

1.    we need to import following inbuilt java classes

        import javax.script.Invocable;
        import javax.script.ScriptEngine;
        import javax.script.ScriptEngineManager;

2.   Code to call any function of javascript file.

        ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
      engine.eval(new InputStreamReader(this.getClass().getResourceAsStream("/Scripts/JavascriptFile.js")));         
       
 // put file JavascriptFile.js inside your project class path Scripts folder or anywhere you want

        Invocable inv = (Invocable) engine;
        ScriptObjectMirror obj = (ScriptObjectMirror) inv.invokeFunction("functionName",          parameterString);

Labels: ,

Find and delete duplicate records from a table - MySQL

 1.  MySQL - Find duplicate records

        SELECT  column_name,  COUNT(column_name) as 'Number of occurrences'  FROM   table_name

        GROUP BY column_name  HAVING COUNT(column_name) > 1;   

2.    MySQL - Delete duplicate records from a table

           delete t1 from table t1, table t2 where t1.column_name_duplicate=t2.column_name_duplicate AND             t1.id < t2.id;
            
Note :  table  - >  name of table
            column_name_duplicate  -> column name which has duplicate values
            id - > id column of table

Labels: , ,

Sunday, September 6, 2020

SOAP - setting service end point (target url) run time

Suppose you are the client and you are consuming SOAP service. There will be a possible scenario when you need to change / set  the SOAP server end point URL at run time when you are just to call the service.

We can achieve this using BindingProvider.ENDPOINT_ADDRESS_PROPERTY

We need to add the following code snippet just befor to call the SOAP service.

UserService_Service service = new UserService_Service();

UserService proxy = service.getUserService();

((BindingProvider)proxy).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "target-end-point-url");


Note : UserService is a stub service interface created by wsdl.

            UserService_Service is a stub service implementation class created by wsdl.

    

Labels: ,

Saturday, September 5, 2020

Spring boot load wsdl file from classpath

 If we are SOAP web service consumer and we have generated the stub from WSDL and want to maintain WSDL in our project or Spring boot jar class-path.

In this case we need to write the following piece of code to load WSDL from project / jar (Spring boot)  class-path.

Modify the URL object inside your service class of stub in  the following manner 

static {

        URL url = null;

        WebServiceException e = null;

        try {

            url = Thread.currentThread().getContextClassLoader().getResource("wsdl/test.wsdl");

        } catch ( Exception ex) {

            e = new WebServiceException(ex);

        }

Labels: