Tuesday, November 3, 2015

Swagger Configuration with Java EE 7

Swagger can be very useful for defining restful APIs especially while working in a SOA based architecture.

Here is how I come up with swagger configuration with java EE 7.

You can check my github link :
https://github.com/anishmanandhar/java-ee-7-sample-project/tree/swagger-config

Here are the steps :
1.Add swagger dependency to your pom.xml :
   
  <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-jersey-jaxrs</artifactId>
<version>1.5.0</version>
   </dependency>

2. Now we need to create a custom Application class where we will define our basic swagger configurations.

@ApplicationPath("app")
public class AppConfig extends Application {

    public AppConfig() {
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.2");
        beanConfig.setSchemes(new String[]{"http"});
        beanConfig.setHost("localhost:8080");
        beanConfig.setBasePath("/java-ee-7-sample-project/app");
        beanConfig.setResourcePackage("org.akm.ems");
        beanConfig.setScan(true);
    }

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        resources.add(ApiListingResource.class);
        resources.add(SwaggerSerializers.class);
        addRestResourceClasses(resources);
        return resources;
    }

    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(EmployeeController.class);
        resources.add(CustomerController.class);
    }
}

So Here basically, we have defined host, base path, resource package to scan in the constructor  as well as override getClasses() method and added our custom classes to the set.

You can find sample Rest resource using swagger in the link
https://github.com/anishmanandhar/java-ee-7-sample-project/blob/swagger-config/src/main/java/org/akm/ems/controller/EmployeeController.java.

3.Now run the application and we can get a pretty json defining our rest apis in the url "http://localhost:8080/java-ee-7-sample-project/app/swagger.json".

3.We can use pretty UI provided by swagger found in https://github.com/swagger-api/swagger-ui.
We need to copy all the files and folders inside dist folder of swagger ui into our web app directory.

4.Next we need to do minor change in the index.html and need to link to our swagger url.
Something like this :

$(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://localhost:8080/java-ee-7-sample-project/app/swagger.json";
      }

5. We need to enable CORS to access the url. For this we can create a filter to allow CORS.

@WebFilter(filterName = "HTML5CorsFilter", urlPatterns = {"/app/*"})
public class CorsFilter implements javax.servlet.Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type");
        chain.doFilter(request, response);
    }

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

    @Override
    public void destroy() {
    }
}

6. We are ready to go and when we access index.html page we can see some thing like


Here is my github link for the whole project :
https://github.com/anishmanandhar/java-ee-7-sample-project/tree/swagger-config



Monday, November 2, 2015

MongoDB bulk upsert with java

I recently came up through the requirement for mongo db upsert with multiple documents in a single collection which should be transactional.

So I used BulkWriteOperation to achieve this requirement.

   1. Get the DBCollection

        private DBCollection getCollection() {
            MongoClient mongo;
            try {
                mongo = new MongoClient("localhost");
                DB db = mongo.getDB("test");
                return db.getCollection("employees");
            } catch (UnknownHostException e) {
                return null;
}
    }


2. Create Criteria to find the objects using Map:
     
     Map map = new HashMap();
      map.put("name", "anish");
      map.put("address", "kathmandu,nepal");
      map.put("phone", "9849243742");

3. Get DBObjects from the criteria, create WriteRequestBuilder

    DBCollection dbCollection = getCollection();
    DBObject dbObject = dbCollection.findOne(new BasicDBObject(map));
    BulkWriteRequestBuilder bulkWriteRequestBuilder = bulkWriteOperation.find(new         BasicDBObject(map));
    BulkUpdateRequestBuilder updateReqBuilder = bulkWriteRequestBuilder.upsert();