Friday, May 18, 2018

Testing A Java Bean For Code Coverage in SonarQube



Here is a generic way of testing a java bean to provide 100% code coverage on sonarqube.
Remember, if beans are trivial, please use this approach, otherwise write proper test cases.


Complete Source code is here -
https://gist.github.com/deodeveloper/405bfbaf8ad94a37304dbfe8949f5757



Sample Source code -

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanTester {

public static <T>  void testBean(Class<T>... beanClasses) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
    for (Class<T> beanClass : beanClasses) {
      T bean = beanClass.newInstance();
      Field[] declaredFields = beanClass.getDeclaredFields();
      for (Field f : declaredFields) {
        PropertyUtils.getProperty(bean, f.getName());
        Class<?> fieldType = f.getType();
        PropertyUtils.setProperty(bean, f.getName(),
            !fieldType.isPrimitive() ? fieldType.newInstance() :
                defaultValue(fieldType));
      }
    }
  }

  public static <T> T defaultValue(Class<T> type) {
    if (type == boolean.class) {
      return (T) Boolean.FALSE;
    } else if (type == char.class) {
      return (T) Character.valueOf('\0');
    } else if (type == byte.class) {
      return (T) Byte.valueOf((byte) 0);
    } else if (type == short.class) {
      return (T) Short.valueOf((short) 0);
    } else if (type == int.class) {
      return (T) Integer.valueOf(0);
    } else if (type == long.class) {
      return (T) Long.valueOf(0L);
    } else if (type == float.class) {
      return (T) Float.valueOf(0f);
    } else if (type == double.class) {
      return (T) Double.valueOf(0d);
    } else {
      return null;
    }
  }

}

usage example - testBean(Person.class)
dependencies used:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>




Sunday, March 11, 2018

Vertx Programming Style : Your Reactive Web Companion REST API Explained


Vertx provides a lot of options to program in a light weight environment, like node.js . However, It could be little confusing for new users to choose which method to adopt for creating REST API.

There are different models to adopt while programming in vertx. They are explained below with easy to understand diagrams.

P.S - The heart of vertx programming is a reference to vertx object which could be obtained statically or as an inherited member with a verticle that extends the AbstractVerticle class. Now you know where to get the vertx object. Let's dive further.

Different Models of programming in vertx falls into the following categories as below, I am adding some funny names to each model :) :-

  1. FaceToFace Approach
  2. Matchmaker Approach
  3. Matching Coach Approach


Model 1 - FaceToFace Approach:

As shown in the diagram, in this model client sends the events in forms of http requests which are buffered to server verticle via a Router. A router could be obtained by using Router.router(vertx)

Now we can configure the router to handle http requests. Careful, router handlers are synchronous call. To run blocking calls or any async operations, please use executeBlocking or adopt Model#2

Model #2 - Matchmaker Approach:
As the name suggests, you can't talk to the other person directly, you will have to go through the dating match maker which is the event bus. This is model is useful when you have a lot of micro services running on different machines or you want to modularize your code in a single machine. A message has header, body, address and by calling message.reply(Object), the receiver verticle can send response back to the sender.





Model 3: Matching Coach Approach:

Here The matchmaker becomes a coach too who will help you how to connect other verticle. It helps by code generation to bind service with event bus so that it would be easier to call service methods.

The main idea is a service name Service (java interface) and corresponding implementation Service Implementation to be exposed as a REST API. But it can't be that straight forward in vertx as in spring web or other frameworks. For Service interface to be exposed, you need to create a AsyncService interface and it's implementation which will mimic Service methods but the signatures will be little different.

Example: In Service interface, you have a method as below:
public User getUser(final String verificationToken) {...}

In async service interface, the same looks like, 
void getUser(String verificationToken, Handler<AsyncResult<User>> resultHandler)

Here we adding an extra argument to the method in form of a vertx Handler that returns an AsyncResult which makes it possible for non-blocking call. Also the return type is void. The result could obtained from the client side using the resultHandler callback.



Please leave your comments below.

Happy Coding!

Thursday, October 19, 2017

URLify in java 8 style functional flavor


 Write a method to replace all spaces in a string with '%20'


Instead of using str.replaceAll("\\s", "%20"), here is a function. This exercise is to help learning.



public String URLifyJava8(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.flatMap(c -> Character.isWhitespace(c)
? "%20".chars().mapToObj(ch -> (char) ch) : Stream.of(c))
.collect(Collector
.of(StringBuilder::new, StringBuilder::append,
(r1, r2) -> {
r1.append(r2);
return r1;
},
StringBuilder::toString, Collector.Characteristics.CONCURRENT));
}

Thursday, June 6, 2013

JQuery XML find method problem - Webkit and chrome fix




If you have xml element tag like this <gml:featureMember>, then jQuery(xml).find("gml\\:featureMember").each(function(){}); will not work across all the browsers, it works in IE and firefox.


To fix it, use as below

$(xml).find("gml\\:featureMember,featureMember").each(function() {
// Do stuff
});
 
 

This works across all the browser.
 

Friday, January 25, 2013

Accept Self signed certificate in JAVA


Accept Self signed certificate in JAVA.

Have you ever faced problem with SSLHandshakeException ?

This is because you are trying to use a website which uses an non-standard https certificate which are not registered on JRE. If you want a self signed certificate web request to be accepted, here is the code.


import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLTest {

    public static void main(String [] args) throws Exception {
        // configure the SSLContext with a TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL("https://mms.nw.ru");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        System.out.println(conn.getResponseCode());
        conn.disconnect();
    }

    private static class DefaultTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}

Friday, January 4, 2013

Convert EPGS to WGS84 using open layer


This is useful when you want to convert your EPSG to google or bing map co-ordinate.


var projWGS84 = new OpenLayers.Projection("EPSG:4326");

var proj900913 = new OpenLayers.Projection("EPSG:102711");

var orinialPoint =  new OpenLayers.LonLat(609638.467487335, 691427.100266891);

 var newPoint = orinialPoint.transform(proj900913, projWGS84);


var projWGS84 = new OpenLayers.Projection("EPSG:4326");

var proj900913 = new OpenLayers.Projection("EPSG:102711");

var orinialPoint =  new OpenLayers.LonLat(609638.467487335, 691427.100266891);

 var newPoint = orinialPoint.transform(proj900913, projWGS84);
var projWGS84 = new OpenLayers.Projection("EPSG:4326");

var proj900913 = new OpenLayers.Projection("EPSG:102711");

var orinialPoint =  new OpenLayers.LonLat(609638.467487335, 691427.100266891);

 var newPoint = orinialPoint.transform(proj900913, projWGS84);

var projWGS84 = new OpenLayers.Projection("EPSG:4326");

var proj900913 = new OpenLayers.Projection("EPSG:102711");

var orinialPoint =  new OpenLayers.LonLat(609638.467487335, 691427.100266891);

 var newPoint = orinialPoint.transform(proj900913, projWGS84);

var projWGS84 = new OpenLayers.Projection("EPSG:4326");

var proj900913 = new OpenLayers.Projection("EPSG:102711");

var orinialPoint =  new OpenLayers.LonLat(609638.467487335, 691427.100266891);

 var newPoint = orinialPoint.transform(proj900913, projWGS84);

Now you can use this newPoint on your preferred map.

Wednesday, November 21, 2012

Google Guice Quick Reference



Google Guice Quick Reference

 bold marked words in code are derived from guice library

Google Guice Cheat Sheet
Basic @Inject
  1. Service Consumer Class
 
@Inject

  RealBillingService(CreditCardProcessor processor,TransactionLog transactionLog) {
this.processor = processor;

    this.transactionLog= transactionLog;

  }
 
  1. Guice Configuration Class
 
public class BillingModule extends AbstractModule {

  @Override 

  protected void configure() {


// Class binding
       bind(TransactionLog.class).to(DatabaseTransactionLog.class).in(Singleton.class);
bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
 
//or instance binding
bind(CreditCardProcessor.class).toInstance(new PaypalCreditCardProcessor());
 
  }

}
  1. Client Class
 
    Injector injector = Guice.createInjector(new BillingModule());



    /*

     * Now that we've got the injector, we can build objects.

     */

    RealBillingService billingService= injector.getInstance(RealBillingService.class);
 
Extention @Inject
1.Linked Binding – Link DatabaseTransactionLog to subclass MySqlDatabaseTransactionLog. You can chain this linking. Injector will return instance of MySqlDatabaseTransactionLog
public class BillingModule extends AbstractModule {

  @Override 

  protected void configure() {

    bind(TransactionLog.class).to(DatabaseTransactionLog.class);

    bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);

  }

}
2.Binding Annotation
Ø  2a . @Named
  @Inject

  public RealBillingService(@Named("PayPal") CreditCardProcessor processor)
- Guice Configuration
    bind(CreditCardProcessor.class)

        .annotatedWith(Names.named("PayPal"))

        .to(PayPalCreditCardProcessor.class);

Ø  2b.Custom Annotation @PayPal
a.Client Guice Configuration
import com.google.inject.BindingAnnotation;

import java.lang.annotation.Target;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import static java.lang.annotation.ElementType.PARAMETER;

import static java.lang.annotation.ElementType.FIELD;

import static java.lang.annotation.ElementType.METHOD;



@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)

public @interface PayPal {}
b.Service Consumer
  @Inject

  public RealBillingService(@PayPal CreditCardProcessor processor)
c. Client
    bind(CreditCardProcessor.class)

        .annotatedWith(PayPal.class)

        .to(PayPalCreditCardProcessor.class);

Ø  2c.@Provides –create an object with some code instade of single line toInstance method
Guice Configuration
public class BillingModule extends AbstractModule {



 // Add any subannotation if required like @PayPal

  @Provides

  TransactionLog provideTransactionLog() {

    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();

    transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");

    transactionLog.setThreadPoolSize(30);

    return transactionLog;

  }

}
Ø  2d.Provider Binding – Alternative to @Provides by moving instance production logic to a separate class
a.Guice Configuration
public class BillingModule extends AbstractModule {

  @Override

  protected void configure() {

    bind(TransactionLog.class)

        .toProvider(DatabaseTransactionLogProvider.class);

  }



b.Provider as instance creation class
public interface Provider<T> {

  T get();

}
 
public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {

 



  public TransactionLog get() {

    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();

    transactionLog.setConnection(connection);

    return transactionLog;

  }

}

Ø  2e. @ImplementedBy and @ProvidedBy – Provides default implementation, can be overriden by the bind() method in guice configuration module.
@ImplementedBy(PayPalCreditCardProcessor.class)

public interface CreditCardProcessor{…}
Equivalient to
bind(CreditCardProcessor.class).to(PayPalCreditCardProcessor.class);

@ProvidedBy(DatabaseTransactionLogProvider.class)

public interface TransactionLog {…}
Equivalent to
    bind(TransactionLog.class).toProvider(DatabaseTransactionLogProvider.class);

Ø  2f. Inject into an existing instance – (for objects that are already instatiated not by guice)useful in servlets or instances that you can’t instantiate or already instatiated by container
    Injector injector = Guice.createInjector(...);

    

    CreditCardProcessor creditCardProcessor = new PayPalCreditCardProcessor();

    injector.injectMembers(creditCardProcessor);




Injecting by Providers (alternative to direct @Inject)
Usability Criteria - Whenever you need to scope mixing (like accessing a request scoped object in session scope or singleton scope) or get instances on demand (lazy loading) or inject more than one instances per type.
Below instead of injecting directly CreditcardProcessor, we use Provider< CreditcardProcessor > and its get() method call provides an instance when required. You can call the get() method to provide as many instances you like and wherever you need inside the code
public class RealBillingService implements BillingService {

  private final Provider<CreditCardProcessor> processorProvider;

  private final Provider<TransactionLog> transactionLogProvider;



  @Inject

  public RealBillingService(Provider<CreditCardProcessor> processorProvider,

      Provider<TransactionLog> transactionLogProvider) {

    this.processorProvider = processorProvider;

    this.transactionLogProvider = transactionLogProvider;

  }



  public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {

    CreditCardProcessor processor = processorProvider.get();

    TransactionLog transactionLog = transactionLogProvider.get();



    /* use the processor and transaction log here */

  }

}

Guice configuration
 
public class BillingModule extends AbstractModule {

  @Override 

  protected void configure() {


// Class binding
       bind(TransactionLog.class).to(DatabaseTransactionLog.class).in(Singleton.class);
bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
 
//or instance binding
bind(CreditCardProcessor.class).toInstance(new PaypalCreditCardProcessor());
 
  }

}

AOP with GUICE
Two concepts – Matcher and MethodInterceptors
Matchers matches classes to apply pointcuts (cross cutting concerns), MethodInterceptors implement the cross cutting concern.

Example in steps – stop pizza orders on weekends
1.create an annotation or use builtin @Named annotation
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)

@interface NotOnWeekends {}
2.Annotate the method where you want to introduce pointcut
public class RealBillingService implements BillingService {



  @NotOnWeekends

  public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {

    ...

  }
3.Implement MethodInterceptors
public class WeekendBlocker implements MethodInterceptor {

  public Object invoke(MethodInvocation invocation) throws Throwable {

    Calendar today = new GregorianCalendar();

    if (today.getDisplayName(DAY_OF_WEEK, LONG, ENGLISH).startsWith("S")) {

      throw new IllegalStateException(

          invocation.getMethod().getName() + " not allowed on weekends!");

    }

    return invocation.proceed();

  }

}

4.Wire or configure all
public class NotOnWeekendsModule extends AbstractModule {

  protected void configure() {

    bindInterceptor(Matchers.only(RealBillingService.class), Matchers.annotatedWith(NotOnWeekends.class), 

        new WeekendBlocker());

  }

}

You can use Matchers.any() or Matchers.subclassesof(BillingService.class)
or if you want the interceptor to be injected with some objects
public class NotOnWeekendsModule extends AbstractModule {

  protected void configure() {

    WeekendBlocker weekendBlocker = new WeekendBlocker();

    requestInjection(weekendBlocker);

    bindInterceptor(Matchers.any(), Matchers.annotatedWith(NotOnWeekends.class), 

       weekendBlocker);

  }

}




Bootstrap for Injecting in http servlets –
Bootstrap guice servlet –
1.
 
<listener>

  <listener-class>com.example.MyGuiceServletConfig</listener-class>

</listener>
2.
public class MyGuiceServletConfig extends GuiceServletContextListener {



  @Override

  protected Injector getInjector() {

    return Guice.createInjector(new ServletModule());

  }

}
or You can subclass ServletModule class like above
   Guice.createInjector(..., new ServletModule() {



     @Override

     protected void configureServlets() {
filter("/*").through(MyFilter.class);

       serve("*.html").with(MyServlet.class);

     }

   }

3.
  <filter>

    <filter-name>guiceFilter</filter-name>

    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>

  </filter>



  <filter-mapping>

    <filter-name>guiceFilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

  1. Injecting inside servlet if ServletModdule class is installed as above
@Singleton

public class MyServlet extends HttpServlet {
@Inject private Injector injector;
...
}

Or Inside servlet init() method, use the bootstrap class
    public void init(ServletConfig config) throws ServletException {
      super.init(config);
      ServletContext servletContext = config.getServletContext();
      Injector injector =
          (Injector) servletContext.getAttribute(Injector.class.getName());
      injector.injectMembers(this);
    }



You can inject ServletContext. You can inject Request parameters by,
@Inject @RequestParameters Map<String, String[]> params;
 
 



GUICE with JERSEY REST Service
Setup –
Step 1 – Use maven dependency  jersey-guice with google guice as shown below.
              <!-- Google Guice -->
              <dependency>
                     <groupId>com.google.inject</groupId>
                     <artifactId>guice</artifactId>
                     <version>3.0</version>
              </dependency>

              <!-- Jersey Guice Module -->
              <dependency>
                     <groupId>com.sun.jersey.contribs</groupId>
                     <artifactId>jersey-guice</artifactId>
                     <version>1.15</version>
              </dependency>


Step 2 - Follow the same setup as web application, but Instead of creating injector from ServletModule class, use JerseyServletModule and use jersey GuiceContainer class to bind to request that will be server by Jersey as REST resources as shown below.

   Guice.createInjector(..., new JerseyServletModule() {



     @Override

     protected void configureServlets() {
filter("/*").through(MyFilter.class);

       serve("*.html").with(MyServlet.class);
serve("/rest/*").with(GuiceContainer.class);


     }

   }

That’s it, then you are read to inject guice dependency to REST services by jersey framework.
JSP injection - look here
http://turbomanage.wordpress.com/2009/12/11/how-to-inject-guice-objects-in-a-jsp/