Author Archive

Swagger 2 /Open API Specification on Spring Boot

January 24, 2018 Leave a comment

Swagger 2 ,or, Open API Specification is a definition used for REST APIs. ( We will in this blog see how to implement the Open API Specification on a Spring Boot application. The Open API spec allows us not only to provide human/machine readable mapping but allow us to use tools on it for creating other implementations (stubs for the services for example)

Here are some reasons how this can be helpful
1. Guiding principles for the API
2. Allows us to create the API from top-down or bottom-up approach
3. Can be easily understood by developers and non-developers
4. Machine readable as well – can be used for tooling and automation

In addition to above Google Cloud Platform Endpoints requires that the API implement this spec. We will see Endpoints in the next blog.

Before we get to the specifics of implementing the Open API spec on our application, we will create a simple Spring Boot Application (See the “Creating the Spring Boot Applicaton” section in this blog )

There are various libraries that implement the Open API specification. We will use SpringFox ( We will add the following dependencies on the pom.xml file



Next we add the config class for Open API in the main package.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class OpenAPIConfig {

    public Docket productApi(){
        return new Docket(DocumentationType.SWAGGER_2)

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My Open API Implementation")
                .description("Application for Open API implementation")

The package name and the PathSelectors can vary depending on the project. Also, the other values are configurable and will display on Swagger UI page.

Next we will implement a simple controller class in our Spring Boot application. Our controller class has a request mapping for /root and returns back a simple message.

package com.wordpress.codesilo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

public class MainController {

	@RequestMapping(value ="/root", response = MainMessage.class)
	public MainMessage getMessage(){
		return new MainMessage("This is the root controller !!");


The MainMessage is a simple POJO with a greeting attribute of type String.

We now will annotate the controllers and methods. Here is an example of annotating the class

@Api(tags={"Root Controller"}, value="Open API for testing", consumes="null")

Annotation of the method can be done in the following way

@ApiOperation(value = "Returns a message", response = MainMessage.class)
@ApiResponses(value = {
            @ApiResponse(code = 200, message = "Greeting is successfully sent"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")

Annotations are also added on the model class. After the annotations, the classes look as shown below.

package com.wordpress.codesilo.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value="Main Response", description="Sample model")
public class MainMessage {

	@ApiModelProperty(value = "Greeting/Message", required=true)
	private String greeting;

	public MainMessage(){

	public MainMessage(String greeting){
		this.greeting = greeting;
	public String getGreeting() {
		return greeting;

	public void setGreeting(String greeting) {
		this.greeting = greeting;
package com.wordpress.codesilo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wordpress.codesilo.model.MainMessage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(tags={"Root Controller"}, value="Open API for testing", consumes="null")
public class MainController {

	@ApiOperation(value = "Returns a message", response = MainMessage.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Greeting is successfully sent"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
	@RequestMapping(value="/",method = RequestMethod.GET)
	public MainMessage getMessage(){
		return new MainMessage("This is the root controller !!");

The last step is to add the @EnableSwagger2 annotation on the Application class.
Now, to view the Swagger UI go to the following url http://localhost:8080/swagger-ui.html#/ (assuming it deployed on your localhost), and to get the docs go to the url http://localhost:8080/v2/api-docs

Note: If you miss this annotation @EnableSwagger2 you get the following error..

Screen Shot 2018-01-23 at 6.26.20 PM


Creating a Spring Boot application on Google App Engine Standard

January 23, 2018 Leave a comment

In our last blog we saw how to create a simple application and deploy in Google App Engine Flex. In this write up we will see how to do the same but in the Google App Engine standard environment.
Last year the Standard App Engine was lagging behind specifically with the java runtime version that was supported but the recent updates have removed that issue. You can read more about the releases here

We will follow the steps from our previous blog up to the point where we add the appengine-maven-plugin. We do not use the app.yaml file in the App Engine standard. Instead we use the appengine-web.xml config file. The following steps need to be followed next.

1. Appengine-web.xml file
Create a new source folder : /src/main/webapp/WEB-INF. In this folder add a new file with the name appengine-web.xml. The following is the content of the file.

<?xml version="1.0" encoding="utf-8"?>
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.
<appengine-web-app xmlns="">

2. Change the packaging
Change the packaging in the pom file from jar to war


3. Add web.xml file
Add a web.xml file in the WEB-INF folder created aboove. The content of the file is as below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.1" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

4. Add a file in the same location with the following config for now

.level = WARNING
java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n

5. Change the main application class.
In our case the Application name is GoogleStandard and the SpringBootApplication class is called GoogleStandardApplication. We will extend the class to implement SpringBootServletInitializer. The class will look like the following

public class GoogleStandardApplication extends SpringBootServletInitializer{

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(GoogleStandardApplication.class);
	public static void main(String[] args) {, args);

Deploy the application using the following command

mvn appengine:deploy

If a new project was created for the deployment, make sure to use the following commands to use the new project and create the appengine instance.

gcloud config set project PROJECT-NAME
gcloud app create

Creating a Spring Boot application on Google App Engine Flex

January 22, 2018 Leave a comment

Google provides the infrastructure to build web applications on the cloud. There are different ways in which this can be done. App Engine provides a way where the scale up is provided automatically with other features. Within the App Engine offering there are 2 options – Flex and Standard. Flex App Engine allows us to use a Docker container for the application. In addition it is built on Compute Engine VM instances. Differences in Flex and Standard can be found here :

We will see how to build and deploy a simple Spring Boot application on a Google App Engine Flex environment.
The initial setup of the Google Cloud Platform project and the SDK can be found here. (

We will create a simple Spring Boot application as described in the “Creating the Spring Boot Application” section here (

After creating the project the billing needs to be enabled for the project –
For the free limits, the billing will not be enabled but it will need to be verified anyways

Once the Spring boot application is created we will add the appengine maven plugin to the pom file of the project. The latest version available currently is 1.3.2. It can be found here The following needs to be added under in the pom.xml file

<!-- -->

There is another plugin that is available with the group id But this is the older plugin available for the sdk. Additional information of the difference in the 2 plugins can be found here:

In the next step, create a folder under the “main” folder with the name “appengine”. We will create a file app.yaml in this folder with the following contents for now. Details on the app.yaml configuration can be found here

# [START appyaml]
runtime: java
env: flex
   jdk: openjdk8
  instances: 1
- url: /.*
  script: this field is required, but ignored
# [END appyaml]

In order to run the application locally, use the following command

mvn spring-boot:run

To deploy the application to the App Engine on Google Cloud use the following command

mvn appengine:deploy

Once the deployment is successful, you should be able to goto the cloud console at and see the services deployed on the app engine instance (you can see this on the app engine dashboard). In our configuration above, it is going to be a default service. Clicking on the service will take you to the root context of our deployed application.

Screen Shot 2018-01-22 at 1.56.24 PM

Screen Shot 2018-01-22 at 1.57.08 PM

GCloud SDK Setup for App Engine Java for Mac

January 18, 2018 Leave a comment

Google Cloud Platform ( is a cloud infrastructure solution from Google. In the next blog we will build and deploy a simple Spring Boot application on Google Flex App Engine. This writeup covers the setup of the gcloud sdk on Mac OS X for the purpose above.

First check if Python is installed in the OS using one of the following commands

python -V
python --version


Download the Google Cloud SDK from this location for your OS .In my case I downloaded the 64bit version for Mac: google-cloud-sdk-157.0.0-darwin-x86_64.tar.gz

Extract the files and then run the command ./ in the directory created. This will install the sdk.
Once installed the output will show the components installed and give some commands that can be run to update the components.

│                                                  Components                                                 │
│     Status    │                         Name                         │            ID            │    Size   │
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │  96.7 MiB │
│ Not Installed │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.0 MiB │
│ Not Installed │ Cloud Bigtable Emulator                              │ bigtable                 │   3.3 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  15.4 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  21.0 MiB │
│ Not Installed │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.3 MiB │
│ Not Installed │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Not Installed │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 132.2 MiB │
│ Not Installed │ gcloud app PHP Extensions (Mac OS X)                 │ app-engine-php-darwin    │  21.9 MiB │
│ Not Installed │ gcloud app Python Extensions                         │ app-engine-python        │   6.4 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  14.8 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   6.1 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   2.9 MiB │
│ Installed     │ Default set of gcloud commands                       │ gcloud                   │           │

Based on the input provided by you, the bash_profile will be updated and the PATH will be set for gcloud.
Once this is done run the following command

gcloud init

This will prompt you to login to your account. This along with some more input will provide the initial setup for the components. Once done the process will also give an option to use an existing project on Google Cloud, or , create a new one. Select a new project and proceed.

In order to develop a Java application on Google App Engine we require the app engine components. We will install those components now by running the following command.

gcloud components install app-engine-java

This should complete the setup for the sdk. The rest of the information/steps is optional.

Eclipse Plugin for Development
I tried to use the Eclipse plugin but was outdated at the time and works only for the standard App Engine (not for the Flex app engine). Have been using the command line for the push since then.

Misc Commands
Here are some other commands that might be useful in future development.

Used to set a Project for the SDK

gcloud config set project PROJECT_NAME 

List of configuration parameters that have been set(includes account, usage reporting flag and project name)

gcloud config list

List of authorized accounts and the one being used actively

gcloud auth list

Used to update the components in the sdk that was installed.

gcloud components update


Multiple versions of Java on Mac OS X

January 18, 2018 Leave a comment

I was working on the Google Cloud platform a couple of months back when Java 8 was not supported on the Standard App Engine. However, the Flex engine had Java 8 support (currently even the standard has support for it). When trying out Standard Vs Flex, I had to find something to switch between the Java versions. Jenv came to the rescue (

The following steps show how to work with jenv on Mac OS X. (Java 8 was already installed on my OS.)

Use Homebrew to install some packages. Brew is the command for Homebrew ( and Homebrew is the package manager for Mac.

Update Homebrew and install Cask if it is not installed already(Cask is an extension of brew for graphical applications)

brew update && brew cask 

Update the repositories in brew to use caskroom/versions

brew tap caskroom/versions

Install Java7 from Caskroom versions

brew cask install java7

Use brew to install jenv

brew install jenv

The following command gives the list of versions of Java installed. The one with the * is the one being used globally

jenv versions 

To install a new version, first we need to make the versions dir

mkdir /Users/codesilo/.jenv/versions

Then add the Java (installed by cask earlier) to the versions of jenv by using the following command

jenv add /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/
jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/

Use the following command to set the selected install as the global jenv version to be used

jenv global oracle64-

The versions command will give the following result now

$ jenv versions
* oracle64- (set by /Users/codesilo/.jenv/version)

You can also configure directory level version (local version) or shell instance version by using the following commands

$ jenv local oracle64-
$ jenv shell oracle64-


Categories: Java, Shell Tags: , , , , , , ,

Salesforce REST API Composite Services

January 17, 2018 Leave a comment

Salesforce has a feature on the REST API called as the Composite Resources. This allows us to build API requests by combining more than one request. Shown below are some  examples of them with Postman ( Documentation of Composite Resources can be found here (

The first step is to get the authorization token.

Endpoint :
Method Type : POST

The body should have form data which has the following : grant_type, username, password, client_id, client_secret. client_id and client_secret are taken from the App created in Salesforce for the integration. See details in the “Setting up Salesforce Connected App” section on this blog post here :
Username and Password should be the username and password of the account being used for the API access. Security Token, if enabled, should be concatenated to the password above. API access should be provided to the Profile of this account.
The grant_type is “password”. It is the word password without the quotes and not the actual password of the user account.

Screen Shot 2018-01-17 at 12.53.33 PM
On making the call, we should get the access_token in the response. This access_token is now used in all subsequent calls below. The instance_url from the response is used to create the endpoint in the requests below.

For all calls below we will have the following 2 headers

Authorization : Bearer **accesss_token HERE**
Content-Type : application/json

Note: For the authorization header the value has to be “Bearer” without the quotes followed by a space and the access_token

1. Composite API Call:

Endpoint: https://INSTANCE_URL_HERE/services/data/v41.0/composite/
Method Type: POST

Sample Body:

    "allOrNone" : true,
    "compositeRequest" : [{
        "method" : "GET",
        "url" : "/services/data/v38.0/query?q=select id from Account where id='0014600000KPgY8'",
        "referenceId" : "AccountIden"
        "method" : "GET",
        "url" : "/services/data/v38.0/query?q=select name from Account where id = '@{AccountIden.records[0].Id}'",
        "referenceId" : "TestDataQuery"

Screen Shot 2018-01-17 at 1.01.38 PM

2. Batch API call:

Endpoint: https://INSTANCE_URL_HERE/services/data/v40.0/composite/batch/
Method Type: POST

Sample Body:

    "batchRequests" : [{
        "method" : "GET",
        "url" : "/services/data/v38.0/query?q=select id from Account where id='0014600000KPgY8'"
        "method" : "GET",
        "url" : "/services/data/v38.0/query?q=select id, name from SalesforceTestData__c where id = 'a0E46000003icvo'"

Screen Shot 2018-01-17 at 1.02.50 PM

3. SObject Tree API call:
Endpoint: services/data/v40.0/composite/tree/Account
Method Type: POST

Sample Body:

"records" :[{
    "attributes" : {"type" : "Account", "referenceId" : "ref1"},
    "name" : "SampleAccount",
    "phone" : "1234567890",
    "website" : "",
    "numberOfEmployees" : "100",
    "industry" : "Banking",
    "Contacts" : {
      "records" : [{
         "attributes" : {"type" : "Contact", "referenceId" : "ref2"},
         "lastname" : "Smith",
         "title" : "President",
         "email" : ""
         "attributes" : {"type" : "Contact", "referenceId" : "ref3"},
         "lastname" : "Evans",
         "title" : "Vice President",
         "email" : ""
    "attributes" : {"type" : "Account", "referenceId" : "ref4"},
    "name" : "SampleAccount2",
    "phone" : "1234567890",
    "website" : "",
    "numberOfEmployees" : "100",
    "industry" : "Banking"

Note: In this example we are adding Contacts tp an account and adding another account without a Contact (Reference:

4. SObject Collections:
This is similar to the Tree API call however it does not take child records in the request. This can be used to execute requests on several records at once. It can also be used to retrieve the data (which is different in comparison to tree)
Examples are described well here: