Why Is Swagger JSON Better Than Swagger Java Client?

The Swagger Java-Based Client Using Java Annotations on the Controller layer

Pros and Cons

  • It’s the old way of creating web-based REST API documents through the Swagger Java library.
  • It’s easy for Java developers to code.
  • All API description of endpoints will be added in the Java annotations parameters.
  • Swagger API dependency has to be added to the Maven configuration file POM.xml.
  • It creates overhead on the performance because of extra processing time for creating Swagger GUI files (CSS, HTML, JS etc). Also, parsing the annotation logic on the controller classes creates overhead on the performance, as well. It makes the build a little heavy to deploy on microservices, where build size should be smaller.
  • The code looks dirty because the extra code has to be added to the Spring MVC Controller classes through the Spring annotations. Sometimes, if the description of the API contract is too long, then it makes code unreadable and maintainable.
  • Any change in an API contract requires Java to build changes and re-deployment, even if it’s only simple text changes, like API definition text.
  • The biggest challenge is to share with the clients/QA/BA teams before the actual development and to make frequent amendments. The service consumers may change their requirements frequently. Then, it’s very difficult to make these changes in code and create the Swagger GUI HTML pages by redeploying and sharing the updated Swagger dashboard on the actual deployed dev/QA env.

2. Swagger JSON File Can be Written Separately and Provide Browser-Based GUI

Pros and Cons

  • In this latest approach, all of the above challenges with Java-based client solution have been solved.
  • The developer initially creates a JSON file, shares, and agrees with the service consumer and stakeholders. They will get signed off after many amendments —no code change and re-deployment are required.
  • The code will be cleaner, readable, and maintainable.
  • There is no extra overhead for file creation and processing, performance is better, and the code is more lightweight for microservices, etc.
  • There is no code dependency for any API contract changes.
  • Swagger JSON file resides in the project binaries (inside src/main/resources/swagger_api_doc.json). We can deploy Swagger on one server and can switch to an environment like this.


You can copy and paste swagger_api_doc.json JSON file content on https://editor.swagger.io/. It will help you modify content and create an HTML page like the following.  Swagger GUI will provide the web-based interface like Postman.


10 Challenges of Microservices and Solutions – Tips & Tricks

I am cloud API developer and architect and currently working on Google’s GCP based microservices for a large retail client of USA.

Transitioning/implementing to microservices creates significant challenges for organizations. I have identified these challenges and solution based on my real exposure of microservices on PROD.

I am writing this white paper in June 2018. At this time, Microservices architecture is not matured enough to address completely all the existing challenges, however open source communities and IT product companies are trying to address all these open issues. All new researches on this topics are based on the finding solutions to the new challenges.

These are the major 10 challenges of microservices architecture and proposed solutions-

1. Data Synchronization – We have event sourcing architecture to address this issue using the async messaging platform. Saga design pattern can address this challenge.
2. Security – API Gateway can solve these challenges. Kong is very popular open source which is being used by many companies on the production system. The custom solution can also be developed for API security using JWT token, Spring Security, and Netflix Zuul/ Zuul2. There are enterprise solutions are also available like Apigee, Okta ( 2 step authentication). Openshift for public cloud security for its top features of RedHat Linux Kernal based security and namespace-based app to app security.
3. Versioning – It will be taken care by API registry and discovery APIs using dynamic Swagger API, which can be updated dynamically and shared with the consumers on the server.
4. Discovery – It will be addressed by API discovery tools like Kubernetes, OpenShift. It can also be done using Netflix Eureka at the code level. However, doing with the orchestration layer will be better and that can be managed by these tools rather doing and maintaining thru code and configuration.

5. Data Staleness – The database should be always updated to give recent data, API will fetch data from the recent and updated database. A timestamp entry can also be added with each record in the database to check and verify the recent data. Caching can be used and customized with an acceptable eviction policy based on the business requirement.
6. Debugging and Logging – There are multiple solutions- Externalised logging can be used by pushing log messages to an async messaging platform like Kafka, Google PubSub etc. A correlation ID can be provided by the client in the header to REST APIs to track the relevant logs across all the pods/docker containers. Also, local debugging can be done individually of each microservice using IDE or checking the logs.
7. Testing– This issue can be addressed using unit testing by mocking REST APIs, Mocking integrated/dependent APIs which are not available for testing using WireMock, BDD Cucumber integration testing, performance testing using Jmeter and any good profiling tool like Jprofiler, DynaTrace, YourToolKit, VisualVM etc.
8. Monitoring – Monitoring can be done using Open source tools Prometheus in the combination of Grafana by creating Gauge and matrices, Kubernetes/OpensShift, Influx DB, Apigee, the combination of Graphana and Graphite.
9. DevOps Support – Microservices deployment and support related challenges can be addressed using state on the art DevOps tools GCP Kubernetes, OpenShift with Jenkin.
10. Fault Tolerance – Netflix Hystrix can be used to break the circuit if there is no response from the API for the given SLA/ETA.

Logback is not writing specific log file Solution

Logback is not writing specific log file Solution
Logback Configuration:
<property name="DEV_HOME" value="/root/apps/logs" />
<appender name="FILE-AUDIT"     class="ch.qos.logback.core.rolling.RollingFileAppender">
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <!-- or whenever the file size reaches the max -->

Issue is related to conflict between log4j and Logback, when we migrate from old log4j to Logback. You need to exclude lo4j dependencies from existing dependencies by running this command:

$ mvn dependency:tree

= >Add these jars only for logging using SLF4j and Logback




Posted detail issue on StackOverflow:


Apache Common Pool – Object pool example

Advantage of using object pool is to improve performance of the application by saving time to create new object from other source for the same purpose. Object pool creates once and reuse for other subsequent operations on the same object. You can customize other configuration settings. Please visit this URL for more info: http://commons.apache.org/proper/commons-pool/api-1.6/index.html

Step:1 Add this Maven jar dependency in your POM.xml


Step:2 Create Factory  Class

import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.springframework.stereotype.Component;

 * @author Rajiv Srivastava
 * Object pool factory
//Extend BasePoolableObjectFactory class.
public class ObjectPoolFactory extends BasePoolableObjectFactory<ConnClient> {

 // for makeObject we'll simply return a new object e.g: connection object
 public ConnClient makeObject() throws Exception {

 InputStream stream = null;
 // Create object code here for the first time. e.g: Create connection object from other integrated system component
 ConnClient connClient= new connClient();
 return connClient;

Step:3 Create Object Pool class and usage

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.springframework.stereotype.Component;

 * @author Rajiv Srivastava

public class ObjectPoolConnection {

    private ObjectPool<ConnClient> pool;

	ConnClient obj = null;

	public ConnClient getConnClient(){

		PoolableObjectFactory<ConnClient> factory = new ObjectPoolFactory();
	    pool = new GenericObjectPool<ConnClient>(factory);

	        try {
	                try {
	                		obj = (ConnClient)pool.borrowObject();
	                } catch (Exception e) {
	                	logger.error("failed to borrow object from Connection pool"+e.getMessage());
	                } finally {
	                    if (obj != null) {
	                        try {
							} catch (Exception e) {
			                	logger.error("failed to return object from Connection"+e.getMessage());
	        } finally {
	            try {
				} catch (Exception e) {
                	logger.error("failed to return pool"+e.getMessage());
	    	return obj;

Cassandra DataStax – Developer Guide with Spring Data Cassandra

We will discus Cassandra implementation :

Important Points:

Download and Installation:

  1. Tarball Installation

  1. DataStax DB
    • You need to register yourself with DataStax for download.
    • DataStax Enterprise – http://www.datastax.com/download#dl-enterprise.
    • Create These folders and changed permission:
    • sudo chmod 777 /var/log/cassandra
      sudo mkdir -p /var/lib/cassandra/data
      sudo chmod 777 /var/lib/cassandra/data
      sudo mkdir -p /var/lib/cassandra/commitlog
      sudo chmod 777 /var/lib/cassandra/commitlog
      sudo mkdir -p /var/lib/cassandra/saved_caches
      sudo chmod 777 /var/lib/cassandra/saved_caches
    • How to run Cassandra: Go to DataStax Cassndra installed folder on Mac/Linux/Unix env:                                                                                          
                                                                                                                                                                        cd /Users/<userName>/dse-4.5.2/bin</pre>
      <pre>sudo ./dse cassandra -f
      //This above command Cassandra DB on your local system. Hit enter to quit from ruining server in background and start CQL query console.
      sudo ./cqlsh
  • Create Schema:
    CREATE SCHEMA event_owner WITH replication = {‘class’: ‘SimpleStrategy’, ‘replication_factor’ : 1 };
    1. Schema(Keyspace) name: event_owner
    2. Table name: event_audit
    Table creation syntax:Please find the revised data model and details below.Note: I have used expanded names for easier understanding which can be shortened later on.
    CREATE TABLE  event_owner.event_audit (
    ctg    text,
    month       timestamp,
    ctgid      text,
    ver     timeuuid,
    userid      text,
    action      text,
    content     text,
    PRIMARY KEY ((category,month),cat_id,version)
    ) WITH CLUSTERING ORDER BY (cat_id ASC, version DESC);
    Sample Data
  • category | month                    | cat_id | version                              | action | content      | userid
    CC | 2014-01-01 05:30:00+0530 |   8000 | b3fc48e0-5608-11e4-aacd-e700f669bcfc |  DRAFT | json content | 155045940
    CC | 2014-01-01 05:30:00+0530 |   9000 | a4747460-5608-11e4-aacd-e700f669bcfc |  DRAFT | json content | 155045940

    • category
      • Commitcode / Part Association/ EventTag [CC / PA / ET]
    • month
      • 12 AM timestamp of first day of the month the change is made
    • cat_id 
      • Unique id for a particular category [Say inc axe of commit code it is cc_id say 9000]
    • version 
      • it is the unique id that indicates the version number. 
      • You can populate it using now() function. 
      • It has an embedded timestamp that can be used to know the timestamp. Use dateOf() function to get the timestamp value.
    • userid
      • id of the user who made the change
    • action 
    • content 
      • actual json content after the change [full json]

  • Sample Query to access the data
    cqlsh:cdb> select * from audit where category=’CC’ and month=’2014-01-01 05:30:00+0530′ and cat_id=’9000′;
    category | month                    | cat_id | version                              | action | content      | userid
    CC | 2014-01-01 05:30:00+0530 |   9000 | a4747460-5608-11e4-aacd-e700f669bcfc |  DRAFT | json content | 155045940
  • SQL Like Commands: You can use same standard SQL DDL/DML commands/syntax for Cassandra query, like-
    • Drop table 
    • Update
    • Delete
    • Truncate
    • Select query

    2. DataStax OpsCenter- 


    3. DataStax DevCenter

        Installation: DataStax DevCenter is a visual CQL query tool for Cassandra and DataStax Enterprise.

        How to start OpsCenter GUI: http://www.datastax.com/documentation/getting_started/doc/getting_started/gettingStartedInstallOpscTar_t.html

2. Package Installation:

DataStax All-in-One Installer

How to run DataStax?

  • Cassandra:
    • Go to your /Users//dse via Terminal and execute the following command:
      • sudo ./bin/dse cassandra -f (This will start the cassandra)
  • Opscenter and DataStax-Agent:
    • Go to /Users//dse in new Tab and execute command : 
      • sudo ./opscenter/bin/opscenter -f (This will start the opscenter)
    • Go to /Users//dse in new Tab and execute command :
      • sudo ./datastax-agent/bin/datastax-agent -f (This will start the datastax-agent)

Using DataStax:

  • Now you can see the Opscenter in Browser in following address:
    • localhost:8888/
  • Here You can able to see the your Cassandra cluster visually, (Kind of monitoring tool for cassandra)


Integrate Cassandra with Spring Data Cassandra :

  1. /**
     * Created by: Rajiv Srivastava
    @ComponentScan(basePackages = {com.cassandraproject.dao,com.cassandraproject.utils})
    @EnableCassandraRepositories(basePackages ={com.cassandraproject.repository})
    public class AuditCoreContextConfig extends AbstractCassandraConfiguration {
     protected String getKeyspaceName() {
     return event_owner; //Schema or Keyspace name
     protected String getContactPoints() {
     return localhost;//IP address of server/local machine. Host of a clusters can be separated with comma (,) like host1,host2. Also minimum two host should be added, so that second Cassandra server will be connected if first is down.
     protected int getPort() {
     return 9042; //Cassandra DB port

2. Data Modelling

 a. Primary/Clustered/Partioned key

 * Created by: Rajiv Srivastava

/* Keyspac/Schema- event_owner
 * CREATE TABLE event_owner.event_audit (
 ctg text,
 month timestamp,
 ctgid text,
 ver timeuuid,
 userid text,
 action text,
 content text,
 PRIMARY KEY ((ctg,month),ctgid,ver)


public class EventAuditKey implements Serializable {

private static final long serialVersionUID = 1L;

@PrimaryKeyColumn(name = ctg, ordinal = 0, type = PrimaryKeyType.PARTITIONED)
 private String category;

 @PrimaryKeyColumn(name = month, ordinal = 1, type = PrimaryKeyType.PARTITIONED)
 private Date month;

 @PrimaryKeyColumn(name = ctgid, ordinal = 2, type = PrimaryKeyType.CLUSTERED, ordering =Ordering.ASCENDING)
 private String categoryId;

 @PrimaryKeyColumn(name = ver, ordinal = 3, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
 private UUID version;

 3. Repository

 * Created by: Rajiv Srivastava*/
public interface AuditRepository extends CrudRepository <EventAudit, EventAuditKey> {

	@Query(select * from event_owner.event_audit)
	public List<EventAudit&amp> eventAudit();

4. CRUD Operation using JPA/CrudRepository – DAO Layer

 * Created by: Rajiv Srivastava*/
public class EventDaoImpl implements EventAuditDao {

 public AuditRepository auditRepository;

 public void save(EventAudit entity) {


 public void save(Collection<EventAudit> entities) {

 public EventAudit find(EventAuditKey eventAuditKey) {
 throw new IllegalArgumentException(It doesn't has all required instance variable set);
 return auditRepository.findOne(eventAuditKey);

 public List<EventAudit> getAll() {

 Iterable<EventAudit> iterable=auditRepository.findAll();
 if(null != iterable.iterator()){
 return Lists.newArrayList(iterable.iterator());
 return new ArrayList<>();

 public List<EventAudit> getListEventAuditMonthCategoryWise(Date date, String Category) {
 // TODO Auto-generated method stub
 return null;

Apache Cassandra: 

  * Getting started: http://wiki.apache.org/cassandra/GettingStarted

  * Join us in #cassandra on irc.freenode.net and ask questions

  * Subscribe to the Users mailing list by sending a mail to


  * Planet Cassandra aggregates Cassandra articles and news:


For more on what commands are supported by CQL, see

https://github.com/apache/cassandra/blob/trunk/doc/cql3/CQL.textile.  A

reasonable way to think of it is as, “SQL minus joins and subqueries.”

MongoDB + Java + Maven Sample Application

Prerequisite: Download and Install MongoDB (http://docs.mongodb.org/manual/installation/) on your local machine and run two instances in two separate terminal/command prompt. This sample app is developed on Mac OS/Linux env.

1. Start MongoDB server using : ./mongod

2. Start MongoDB client : ./mongo

Add MongoDB Jar dependency in your project:



Sample MONGODB CRUD code:

package com.db;
import java.util.List;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoConnectionManager {
	static DBCursor cursor;

	public static void main(String[] args) {

		System.out.println("Connecting with MongoDB......");
		//DB connection after ver 2.10.0
		MongoClient mongoconn = new MongoClient("localhost",27017 );
		//Get database
		DB db = mongoconn.getDB( "test" );
		System.out.println("Database Name: "+db.getName());

		//Display all databases
		List<String> dbs = mongoconn.getDatabaseNames();
		for(String mydb : dbs){

		//If MongoDB is installed on Secure mode
		//boolean auth = db.authenticate("username", "password".toCharArray());

		//Get Collection/tables names
		Set<String> colls = db.getCollectionNames();

		for (String s : colls) {

		//Get Collection

		DBCollection coll = db.getCollection("mynames");
		coll.createIndex(new BasicDBObject("email", 1));  // create index on "i", ascending

		System.out.printf("Collection Names:"+db.getCollectionNames());

		//Drop collections

		//Insert new records/documents
		BasicDBObject doc1 = new BasicDBObject();

		//Insert values into document/record
        doc1.put("name", "Rajiv");
        doc1.put("email", "rajivmca2004@yahoo.com");

     // Insert values in Collection

        BasicDBObject doc2 = new BasicDBObject();

		//Insert values into document/record
        doc2.put("name", "Mohit");
        doc2.put("email", "mohit@yahoo.com");

       // Insert values in Collection

        //Fecth only first doc

        DBObject mydoc= coll.findOne();
        System.out.println("Only First Doc :"+mydoc);

        //Insert and fetch Multiple doc

        for (int i = 0; i < 10; i++) {
			coll.insert(new BasicDBObject().append("count", i));

        //Total documents
       cursor= coll.find();


        //Getting A Single Document with A Query
        BasicDBObject query= new BasicDBObject();
        cursor= coll.find(query);
        System.out.print("Getting A Single Document with A Query: \n");

        //Iterate over database results

        //Conditional Queries, documents where i > 50. We could also get a range, say 20 < i <= 30 :
        query = new BasicDBObject();
        query.put("count", new BasicDBObject("$gt", 1).append("$lte", 30));  // i.e.   20 < i <= 30

        cursor = coll.find(query);

        while(cursor.hasNext()) {
            System.out.println("Comparison =>"+cursor.next());
        System.out.println("Total documents: "+coll.getCount());

		} catch (Exception e) {