Archive

Archive for the ‘Java’ Category

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. (https://swagger.io/specification/). 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 https://codesilo.wordpress.com/2017/12/26/spring-boot-rest-api-integration-with-salesforce/ )

There are various libraries that implement the Open API specification. We will use SpringFox (http://springfox.github.io/springfox/). We will add the following dependencies on the pom.xml file

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
    <scope>compile</scope>
</dependency>

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.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class OpenAPIConfig {

    @Bean
    public Docket productApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select().apis(RequestHandlerSelectors.basePackage("com.wordpress.codesilo"))
                .paths(PathSelectors.ant("/root/*"))
                .build();
    }

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

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;

@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;

@RestController
@RequestMapping("/root")
@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

Advertisements

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 https://cloud.google.com/appengine/docs/standard/java/release-notes

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
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <threadsafe>true</threadsafe>
    <runtime>java8</runtime>
</appengine-web-app>

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

<packaging>war</packaging>

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="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
</web-app>

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

.level = WARNING
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
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

@SpringBootApplication
public class GoogleStandardApplication extends SpringBootServletInitializer{

	@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(GoogleStandardApplication.class);
    }
	
	public static void main(String[] args) {
		SpringApplication.run(GoogleStandardApplication.class, 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 : https://cloud.google.com/appengine/docs/the-appengine-environments

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. (https://codesilo.wordpress.com/2018/01/18/gcloud-sdk-setup-for-app-engine-java-for-mac/)

We will create a simple Spring Boot application as described in the “Creating the Spring Boot Application” section here (https://codesilo.wordpress.com/2017/12/26/spring-boot-rest-api-integration-with-salesforce/)

After creating the project the billing needs to be enabled for the project –
https://console.developers.google.com/billing
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 https://mvnrepository.com/artifact/com.google.cloud.tools/appengine-maven-plugin/1.3.2. The following needs to be added under in the pom.xml file

<!-- https://mvnrepository.com/artifact/com.google.cloud.tools/appengine-maven-plugin -->
<plugin>
    <groupId>com.google.cloud.tools</groupId>
    <artifactId>appengine-maven-plugin</artifactId>
    <version>1.3.2</version>
</plugin>

There is another plugin that is available with the group id com.google.appengine. But this is the older plugin available for the sdk. Additional information of the difference in the 2 plugins can be found here: https://stackoverflow.com/questions/40627278/which-app-engine-maven-plugin-to-use

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 https://cloud.google.com/appengine/docs/flexible/java/configuring-your-app-with-app-yaml

# [START appyaml]
runtime: java
env: flex
runtime_config:
   jdk: openjdk8
manual_scaling:
  instances: 1
handlers:
- 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 https://console.cloud.google.com/ 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 (https://cloud.google.com/) 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 https://cloud.google.com/sdk/ .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 ./install.sh 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

Reference: https://cloud.google.com/sdk/

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 (http://www.jenv.be/)

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 (https://brew.sh/) 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-1.7.0.80

The versions command will give the following result now

$ jenv versions
  system
  1.7
  1.7.0.80
  1.8
  1.8.0.101
* oracle64-1.7.0.80 (set by /Users/codesilo/.jenv/version)
  oracle64-1.8.0.101

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

$ jenv local oracle64-1.7.0.80
$ jenv shell oracle64-1.7.0.80

 

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

Spring Boot REST API integration with Salesforce

December 26, 2017 1 comment

This blog covers ways to integrate with Salesforce using REST API.
We will use Spring Boot to authenticate (get access_token and instance_url from Salesforce). Although this can be done using a plain Java Application, we will assume that a real world use case requires a web application to call the services.

The Spring Boot application we create will have have a service exposed through a plain HTTP GET call. The application will call the authentication on Salesforce and use the response from the authentication to make a call to get some data from an Object in Salesforce. In an actual implementation the authentication can be cached and need not be called each time before making an API call to Salesforce. The cache can be refreshed more frequently than the timeout on the session, or, it can be refreshed after the authentication failure exception because of the timeout.

1. Creating the Spring Boot Application

The easiest way to create a starter project is to use Spring STS (https://spring.io/tools). You could also follow the steps here if you don’t want to use STS and want to use some other IDE. (https://spring.io/guides/gs/spring-boot/)

To create the Project in STS, run the install of STS and create a new workspace for yourself. Click on File | New | Spring Starter Project
In the new Window, provide the name of the Project (for this example we give the name SalesforceRESTAPI), group name (com.wordpress.codesilo.salesforce), Artifcat (keep it as is – should have autofilled the name of the Project above), package (com.wordpress.codesilo.salesforce). These can be changed according to your namespace.

Screen Shot 2017-12-22 at 3.53.54 PM

In the next step select “Web” from the dependencies and proceed to create the project. To start the instance, right click on the project and to to Run As | Spring Boot App. This should start the server and you should be able to see the progress in the console. On the browser, go to http://localhost:8080 and you should be presented with a page with a “Whitelabel Error Page” header

Screen Shot 2017-12-22 at 6.08.34 PM

So far, we have created a default Spring Boot Application with “Web” added as a dependency (spring-boot-starter-web dependency). The next step is to add a simple Controller and a class to call the Salesforce API. But before we do that, we will create an object and create an “App” on a Salesforce instance that we want to connect to.

2. Setting up Salesforce Connected App

We will use a new Salesforce Developer Edition Org. Sign up for on here (https://developer.salesforce.com/signup)
Once logged in, go to the Classic mode in Salesforce and then to Setup | Create | Apps

Click “New” on Connected Apps and fill the form in the next page. Add the Connected App Name, API Name and email as required. We don’t need these fields for the integration however. Click on “Enable OAuth Settings” and add the following as the Callback Url “http://localhost&#8221;. For selected OAuth Scopes, choose Full Access for now. Change these settings as required later. Save the changes – it should take a few minutes for this to take effect.
In order to create Connected App in Salesforce Lightning see here https://help.salesforce.com/articleView?id=connected_app_create.htm&type=5

You should now be able to get the following information from the Connected App created – Consumer Key, Consumer Secret. If you don’t have a Security Token for your account yet (had you created the Developer Edition instance earlier), go to, “My Profile” and in the Quick Find look for “Reset Security Token”. This should send you a security token to your email. Note: If the “Login IP” ranges for your Profile has been set appropriately, you might not require the security token.

3. Create the Controller on Spring Boot App

We will create a new Class for the controller in the following package. com.wordpress.codesilo.salesforce.controller. The class will take a simple GET request and return the text “home” in the body.

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

@RestController
public class SalesforceAPIController {

@RequestMapping("/home")
public String getSalesforceObject(){
return "home";
}

}

4. Create the class to make the API call to Salesforce

Create the model class to store the response from the authentication on Salesforce

package com.wordpress.codesilo.salesforce.model;

public class AuthenticationResponse {

private String access_token;
private String instance_url;
private String token_type;
private String issued_at;

public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getInstance_url() {
return instance_url;
}
public void setInstance_url(String instance_url) {
this.instance_url = instance_url;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public String getIssued_at() {
return issued_at;
}
public void setIssued_at(String issued_at) {
this.issued_at = issued_at;
}

@Override
public String toString() {
return "AuthenticationResponse [access_token=" + access_token + ", instance_url=" + instance_url
+ ", token_type=" + token_type + ", issued_at=" + issued_at + "]";
}
}

We now create a class (SalesforceAPIService) to make the REST API calls to Salesforce. We first have to make a call to authenticate with Salesforce. (Replace the parameters marked between ** below with appropriate values of your instance/Org)

public AuthenticationResponse login(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();

params.add("username", ** USERNAME HERE **);
params.add("password", ** CONCATENATION OF PASSWORD AND SECURITY TOKEN HERE ** );
params.add("client_secret", ** CONSUMER SECRET FROM CONNECTED APP HERE ** );
params.add("client_id", ** CONSUMER KEY FROM CONNECTED APP HERE **);
params.add("grant_type","password");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity response = restTemplate.postForEntity("https://login.salesforce.com/services/oauth2/token", request, AuthenticationResponse.class);
return response.getBody();;
}

The response from the call above has the token and the instance url that we use in the next call to get the data from an Object.

In the next API call, we will query the Account object to get the Id and Name from the object. We will assume that we will get a specific object by querying based on an Id. Use an Id from your Developer Edition to query and get a result. The response is going to be in json in the following format. Here is the sample:

{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v22.0/sobjects/Account/001f4000005WEvpAAG"
},
"Id": "001f4000005WEvpAAG",
"Name": "Burlington Textiles Corp of America"
}
]
}

We need to create the Java Objects to store the response. In order to create the POJO, we can use http://www.jsonschema2pojo.org/

The following classes are to be created for the POJOs

public class AccountResponse {

private int totalSize;
private boolean done;
private List records;

public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public List getRecords() {
return records;
}
public void setRecords(List records) {
this.records = records;
}

}
public class Attribute{
private String type;
private String url;

public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

public class Account {
@JsonProperty("attributes")
private Attribute attributes;
@JsonProperty("Id")
private String id;
@JsonProperty("Name")
private String name;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("attributes")
public Attribute getAttributes() {
return attributes;
}

@JsonProperty("attributes")
public void setAttributes(Attribute attributes) {
this.attributes = attributes;
}

@JsonProperty("Id")
public String getId() {
return id;
}

@JsonProperty("Id")
public void setId(String id) {
this.id = id;
}

@JsonProperty("Name")
public String getName() {
return name;
}

@JsonProperty("Name")
public void setName(String name) {
this.name = name;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

In the class we use to call the API to Salesforce add the following method to get the data from the Account Object.

public AccountResponse getAccountData(String accessToken, String instanceUrl){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + accessToken);
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity salesforceTestData = restTemplate.exchange(instanceUrl+ "/services/data/v22.0/query?q=select Id, Name from Account where Id = '001f4000005WEvp'", HttpMethod.GET, request, AccountResponse.class);
log.info(salesforceTestData.getBody().getRecords().get(0).getName());
return salesforceTestData.getBody();
}

The accessToken and instanceUrl parameters are the values from the AuthenticationResponse above.

5. Remap the Controller class to call the service

We will mark the SalesforceAPIService class with the @Component annotation so that it is available for autowiring in the controller.
We now call the SalesforceAPIService from the controller and pass the response to the service on Spring.

@RequestMapping("/account")
public AccountResponse getSalesforceAccount(){
AuthenticationResponse authenticationResponse = salesforceAPIService.login();
AccountResponse accountResponse = salesforceAPIService.getAccountData(authenticationResponse.getAccess_token(), authenticationResponse.getInstance_url());
return accountResponse;
}

Once we start the server and call go the following url (GET request) http://localhost:8080/account , we get the response from the service call to Salesforce.

Screen Shot 2017-12-25 at 10.45.50 PM.png