Thursday, October 8, 2015

How to implement Hibernate Bean Validations with Jersey2

When to use??

When we need to validate the properties of a bean class (eg:max length, not null , etc) we can simple use Hibernate Bean Validations


Implementation


Bean Class

import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;

public class UserDTO {
  @NotNull
  private int userId;
  @Size(min = 1, max=50)
  private String userName;

  public int getUseId() {
    return this.userId;
  }

  public void setUseId(int userId) {
    this.userId = userId;
  }

  public String getUseName() {
    return this. userName;
  }

  public void setUserName(String userName) {
    this.userId = userName;
  }
}


Service Class


import javax.validation.Valid;

public Response createUser(@Valid UserDTO userDTO) {
  //validate UserDTO bean
  validateBean(userDTO);

  //Rest of the logic goes here
}

@Valid - This annotation used to specify that we need to validate this bean.

Validation Engine Call

Annotation is not just enough and below code needs to be executed to call to hibernate Validation engine.

public void validateBean(Object object) throws ValidationException {
  if (object == null) {
    throw new ValidationException("Payload cannot be null");
  }
  //contains internal error message
  StringBuilder internalErrMsg = null;
  //validate request payload
  Set<ConstraintViolation<Object>> constraintViolations =
  validator.validate(object);
  //check if there are bean validation violations
  if (CollectionUtils.isNotEmpty(constraintViolations)) {
    internalErrMsg = new StringBuilder();
    //check through each property in the bean class for validation violation
    for (ConstraintViolation<Object> violation : constraintViolations) {
      //Appending property name and violated validation
      internalErrMsg.append(violation.getPropertyPath().toString()).append(" ").append(
        violation.getMessage()).append("; ");
    }
    throw new ValidationException(internalErrMsg.toString());
  }
}




Jersey2 Request Filters

What and Why?

Jersey filter is an interceptor class (mediator) we use to filter the requests before hitting out the end point.
(Caller)  --> Filter  --> (End point)

Eg:
We can check the Authorization functionality here.
Lets assume we have an end point which returns user permission details.
So if we need to filter only the requests come through a particular client, we can add a filter and allow only the valid requests.

Implementation


import javax.ws.rs.container.ContainerRequestFilter;

public class AuthorizationFilter implements ContainerRequestFilter { 
    @Override public void filter(ContainerRequestContext request) throws IOException {
        
            if (!isAuthorized()) {
               // Throw Exception here
            }
        }
    }

    private Boolean isAuthorized() {
        boolean isAuthorized = true;

        //implement the logic here.
        return isAuthorized;
    }
}

Saturday, May 30, 2015

WSO2 Application Manager (AppM)

WSO2 Application Manager (AppM)


What and Why?

WSO2 App Manager (AppM) is a solution to provide controlled access to several applications for many users in an organisation. In other words WSO2 AppM handles as a proxy between your web apps and the user and enables you to maintained a controlled and monitored environment.


Technical Aspects:

WSO2 App Manager is created on top of the Carbon platform, where it extends registry assets and provides the capability to add web applications. All the functionality can be extended with extension points provided by WSO2 App Manager. It is developed mainly using three technologies namely, SAML2 SSO, XACML policy definition and OAuth secured API invocations.  It is bundled with a set of features for app creation, publication, lifecycle management, versioning, monetization, governance, security etc. using proven WSO2 products such as, WSO2 Enterprise Store, WSO2 Enterprise Service Bus, WSO2 Identity Server, and WSO2 Governance Registry. In addition, it is also powered by the WSO2 Business Activity Monitor, and is immediately ready for massively scalable deployments.
WSO2 App Manager is a fully open sourced product and released under Apache Software License Version 2.0, one of the most business-friendly licenses available tod ay.


Mobile Support:

WSO2 App Manager supports publishing iOS, Android, Hybrid and Web apps with app versioning and lifecycle management. The storefront enables directly downloading mobile apps with the support for self-subscription and app rating. WSO2 App Manager is easily configurable with WSO2 device management solutions or any third-party device management solutions for device management purposes.


How to start?

You can download the AppM binary from here.

  • Unzip the binary
  • go to [binary] > bin 
  • wso2server.sh (linux/mac) , wso2server.bat (windows)

WSO2 AppM Components

 




Tuesday, May 26, 2015

Database interaction WSO2 ESB

Database interaction WSO2 ESB

Lets say we have a requirement of getting the data (eg: may be configuration information) from database and store the same in a cache. This should be a onetime activity where we don’t want to interact with the database for every request. The newly created cache should be accessed for any further request in order to get the configuration information instead of from the database.

In this post I'm trying to explain you what are the options available and how to achieve the above requirement.

There are 2 options available to cater this requirement
  1. Cache Mediator
  2. Custom Mediator

Cache Mediator

Refer : https://docs.wso2.com/display/ESB481/Cache+Mediator
You can retrieve the values from database using a DB Lookup Mediator and cache the result.
And when the next request comes, it should only execute the dblookup mediator when the cache is empty.
But please note that using a DB lookup mediator you can retrieve only one data row from the database.


Custom Mediator 

Refer : https://docs.wso2.com/display/ESB470/Sample+380%3A+Writing+your+own+Custom+Mediation+in+Java
You can write a custom mediator to implement this requirement. Here you do not need a DB lookup mediator. And what this custom mediator would do is, it should have a cache and when a requests comes, if the cache it empty it should retrieve the data from the database directly. else it should use the cached values and update the messageContext properties. please refer the sample.


//Please note that this is only a sample code for you to get a basic idea

package org.example.mediator;

import org.apache.synapse.MessageContext;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.AbstractMediator;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.cache.Cache;

import javax.xml.namespace.QName;

public class MyMediator extends AbstractMediator {

    private static final Log log = LogFactory.getLog(MyMediator.class);

    public MyMediator(){}

    public boolean mediate(MessageContext mc) {
      if( getDBValueCache().get(“dbValueCache”) == null){
//retrieve values from db
//update cache
}
//set values as MessageContext properties
return true;
    }

    private Cache getDBValueCache() {
return Caching.getCacheManager(“dbValueCache".getCache(“dbValueCache”);
    );
}




If you need to further improve the code and to load the values when synapse initializes, you can implement the ManagedLifecycle interface in your class mediator and implement the init() method to load the required data.

import org.apache.synapse.ManagedLifecycle;
public class MyMediator implements Mediator, ManagedLifecycle {
public void init(SynapseEnvironment synapseEnvironment)
public void destroy() {
}
// mediation logic here
@Override
{ // perform initialization here }
@Override
}

If you are using this in multiple places, there will be multiple instances of the class mediator created for each declaration of the class mediator in synapse configurations. Hence there will be multiple copies of the cache as well. If you need to eliminate having multiple copies, you can make the cache/map static.


Saturday, February 28, 2015

How to optimize SQL Queries??

How to optimize SQL Queries??

Here I'm sharing some of valuable tips to optimize SQL queries to gain high performance

  • In a SELECT statement use the column names you need to select instead of using (*)
  • When ever possible, use LEFT JOINs instead of INNER JOINs as when you are using a INNER JOIN the DBMS runs through indexes of both tables and when you are using a LEFT JOIN it runs through the indexes of one table and search for matching record in the other table.
  • Avoid using NOT operators. It is much faster to search for an exact match (positive operator) such as using the LIKE, IN, EXIST or = symbol operator instead of a negative operator such as NOT LIKE, NOT IN, NOT EXIST or != symbol. Using a negative operator will cause the search to find every single row to identify that they are ALL not belong or exist within the table. On the other hand, using a positive operator just stop immediately once the result has been found.
  • Use EXITS instead of COUNT to check if a record is exists.
  • Avoid using IN clause. EXISTS is another option or you can use JOINs
Eg:
SELECT id,
       name,
       address,
       birthday
FROM student_master
WHERE id IN
    (SELECT id
     FROM good_student)

Doing this is very expensive because SQL query will evaluate the outer query first before proceed with the inner query. Instead we can use this instead.


SELECT good.id,
       all.name,
       all.address,
       all.birthday
FROM good_student good
LEFT JOIN student_master ALL ON ALL.id = good.id

  • Use UNION ALL instead of OR as this will utilize indexes
  • Avoid using HAVING clause. HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes. 
Eg:
SELECT name,
       count(name)
FROM student_master
WHERE name != 'marry'
  AND name != 'john'
GROUP BY name;

Instead of:
SELECT name,
       count(name)
FROM student_master
GROUP BY name
HAVING name!= 'marry'
AND name!= 'john';

  • When joining tables always use filtered subsets. Please refer below examples to see the explanation.

CITY
CITY_ID CITY_NAME 
1 Paris
2 Sydney
3 Madrid
4 Colombo
5 Auckland
6 Mumbai
7 Venice


FAVOURITE_CITY
SEQ_ID CITY_ID HAVE_VISITED
1 1 FALSE
2 3 TRUE
3 4TRUE

I need to get all the cities I have visited??
Option 1:
SELECT C.CITY_ID,
       C.CITY_NAME
FROM CITY C
INNER JOIN FAVOURITE_CITY FC ON C. CITY_ID=FC. CITY_ID
WHERE FC.HAVE_VISITED='TRUE'
Here we are using a INNER JOIN so the indexes of both tables will be scanned and even though the result is correct its a costly operation.

Option 2 (Best):
SELECT C.CITY_ID,
       C. CITY_NAME
FROM FAVOURITE_CITY FC
LEFT JOIN CITY C ON C. CITY_ID=FC. CITY_ID
WHERE FC.HAVE_VISITED='TRUE'

Here we are retrieving only the favourite cities (small subset) and joining master table to get the relevant master information. This is the way to do it. 


I need to get my favorite cities which I have visited but the Name should begin with 'C'
Option 1: 
SELECT C.CITY_ID,
       C.CITY_NAME
FROM FAVOURITE_CITY FC
LEFT JOIN CITY C ON C. CITY_ID=FC. CITY_ID
WHERE FC. HAVE_VISITED =TRUE' AND C.CITY LIKE 'C%'

This query works fine. But when joining the two tables we can increase the performance by minimizing the data subset

Option 2 (Best):
SELECT C.CITY_ID,
       C.CITY_NAME
FROM FAVOURITE_CITY FC
LEFT JOIN CITY C ON C. CITY_ID=FC. CITY_ID
AND C.CITY LIKE 'C%'
WHERE FC. HAVE_VISITED

Here we get only a filtered subset of data in CITY table. So rather than using this (CITY LIKE 'C%') condition in WHERE clause it will be more useful to use when joining the tables.



Saturday, January 3, 2015

Introduction to Json

Introduction to Json


What Json Object looks like?

eg: {"apple","cherry","grapes"}


What Json Array looks like?

eg: {"fruits":[{"apple","grapes"},{"cherry","banana"},{"pineapple","orange"}],"vegetable":[{"carrot","leeks"},{pumpkin,tomato}]}


What Json String looks like? 

eg: '{"apple","cherry","grapes"}'


Using JSON with Different Platforms

Since JSON is so popular, there are parsers (tools and libraries that decode one programming language so that another can understand it) and generators (tools and libraries that do the opposite; encode one programming language into another) available for most programming languages.I'll highlight a few...

For .NET:

#using System.Json; 
decoded = JsonValue.Parse(jsonString);  //may be a JsonPrimitive, JsonArray, or JsonObject, depending on the JSON passed


For JavaScript (including HTML 5 apps):

You could just pass the JSON string to eval() in JavaScript, but this is a terrible security risk. Most modern browsers support a function JSON.parse(), which will parse a JSON string into JavaScript objects, and JSON.stringify(), which will turn a JavaScript object or array into a JSON string.

For Java (example):

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}