Archive

Archive for the ‘Spring’ 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

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

Spring Boot REST API integration with Salesforce

December 26, 2017 3 comments

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

Drools 6 Decision Table with Spring MVC

June 8, 2015 Leave a comment

Drools is the Java Rules engine from Jboss. This article covers on how to use the Drools Decision Table using excel sheets with a Spring MVC project.

To start with, create a basic Spring MVC project using Spring STS. Add the following dependencies for drools on the pom file generated by the template in STS.


<dependency>
 <groupId>org.drools</groupId>
 <artifactId>drools-core</artifactId>
 <version>6.2.0.Final</version> 
 </dependency>
 <dependency>
 <groupId>org.drools</groupId>
 <artifactId>drools-compiler</artifactId>
 <version>6.2.0.Final</version> 
 </dependency>
 <dependency>
 <groupId>org.kie</groupId>
 <artifactId>kie-spring</artifactId>
 <version>6.2.0.Final</version> 
 </dependency>
 <dependency>
 <groupId>org.kie</groupId>
 <artifactId>kie-api</artifactId>
 <version>6.2.0.Final</version> 
 </dependency>
 <dependency>
 <groupId>org.kie</groupId>
 <artifactId>kie-internal</artifactId>
 <version>6.2.0.Final</version> 
 </dependency>

Create a spring-context.xml file in the following location /WEB-INF/spring with the following content


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:kie="http://drools.org/schema/kie-spring"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://drools.org/schema/kie-spring http://drools.org/schema/kie-spring.xsd">

<kie:kmodule id="kmodule1">
 <kie:kbase name="kbase1" packages="com.codesilo.wordpress.rules">
 <kie:ksession name="ksession1" type="stateless" />
 </kie:kbase>
 </kie:kmodule>

<beans:bean id="kiePostProcessor"
 class="org.kie.spring.KModuleBeanFactoryPostProcessor" />

</beans:beans>

The package here “com.codesilo.wordpress.rules” denotes the location where the decision tables are located. We will create that one we have created the POJO.

Add the /WEB-INF/spring/spring-context.xml on the contextConfigLocation in web.xml. The contextConfigLocation should now look like


<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/root-context.xml
 /WEB-INF/spring/root-context.xml</param-value>
 </context-param>

We create the POJO named as RouteAttribute in the following package com.wordpress.codesilo.model. This object will be used as the fact for the rules defined,


package com.wordpress.codesilo.model;

public class RouteAttribute {

private String country;
 private String state;
 private boolean newEntry;
 
 //Result
 private String ansOnRule;

public String getCountry() {
 return country;
 }

public void setCountry(String country) {
 this.country = country;
 }

public String getState() {
 return state;
 }

public void setState(String state) {
 this.state = state;
 }

public boolean isNewEntry() {
 return newEntry;
 }

public void setNewEntry(boolean newEntry) {
 this.newEntry = newEntry;
 }

public String getAnsOnRule() {
 return ansOnRule;
 }

public void setAnsOnRule(String ansOnRule) {
 this.ansOnRule = ansOnRule;
 }
 
}


Now we create the decision table (Rules.xls) on the following location com.codesilo.wordpress.rules

Rules

The file can also be downloaded from here.

As a last step, we change HomeController.java to fire the rules. This can be later moved to any controller/MVC flow. We inject the KieBase object by the following..

@Autowired
private KieBase kieBase;

Add the following in the default method on the HomeController class.


RouteAttribute routingComponent = new RouteAttribute();

routingComponent.setCountry("US");

StatelessKieSession statelessKieSession =  kbase.newStatelessKieSession();

statelessKieSession.execute(routingComponent);

Now, if we bring up the server, the default method is going to run and call the rules from above.

Spring MVC with Sitemesh 3

July 11, 2013 3 comments

In one of my earlier posts I showed some steps to create a project with Struts Tiles. This post mentions the steps to get a basic Spring MVC project running with Sitemesh 3. Sitemesh is a decorator framework. More information on Sitemesh 3 can be found here.

CREATING A BASIC SPRING MVC PROJECT

We will use the Spring Developer Toolsuite and Maven 3 for our project. Go to the toolsuite workspace and select File>New>Spring Template Project and choose Spring MVC Project from the list. Click yes on the download prompt. We will name the project as Sitemesh-SpringMVC and the package as com.wordpress.codesilo.

SETTING UP SITEMESH 3

Open the pom.xml of the Project and add the following dependency.

<dependency>
 <groupId>org.sitemesh</groupId>
 <artifactId>sitemesh</artifactId>
 <version>${sitemesh.version}</version>
</dependency>

Also add the following under properties

<sitemesh.version>3.0-alpha-2</sitemesh.version>

To the web.xml add the following

<filter>
 <filter-name>sitemesh</filter-name>
 <filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>sitemesh</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

Now create a sitemesh3.xml file in the web-inf folder of the project and add the decorator files mapping in the file like follows. We will create the decorator files next.

<sitemesh>
 <mapping path="/*" decorator="/WEB-INF/decorators/defaultDecorator.jsp"/>
 <mapping path="/user" decorator="/WEB-INF/decorators/userDecorator.jsp"/>
</sitemesh>

Create the decorators folder in your project and add the following  jsp files.

defaultDecorator.jsp

<html>
 <head>
 <title><sitemesh:write property='title'/></title>
 <sitemesh:write property='head'/>
 </head>

 <body>
 This is the default body in decorator:
 <sitemesh:write property='body'/>
 </body>
</html>

userDecorator.jsp

<html>
 <head>
 <title><sitemesh:write property='title'/></title>
 <sitemesh:write property='head'/>
 </head>

 <body>
 This is the decorator body in user:
 <sitemesh:write property='body'/>
 </body>
</html>

For the default decorator example we will use the home.jsp that was created as a part of the project template. For the user decorator, we will create a new view in the views folder. We will keep it very simple as follows.

user.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
 <title>User</title>
</head>
<body>
<h1>
 Hello User!
</h1>

<P> Welcome user ! </P>
</body>
</html>

We will also change the HomeController (created again as a part of the template) to add another method for the user request mapping. We will copy the method for the default request mapping and change it as follows. (Add the following code to the HomeConrtoller)

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String user(Locale locale, Model model) {
 logger.info("Welcome home! The client locale is {}.", locale);
 return "user";
}

Now, if we run the application and try the following urls we will see the different results. Notice the content added by the decorators.

http://localhost:8080/codesilo/

SitemeshImage1

http://localhost:8080/codesilo/user

SitemeshImage2

ADDING POST TO SITEMESH3

I read somewhere that Sitemesh 3 had a bug that did not allow it to use POST on the requests. I tried to give it a shot. We will add a field on the default view to accept a name. We will send that as a POST to the user method and display that on the user view.

Here is User.java class.

package com.wordpress.codesilo;

public class User {

private String name;

public String getName() {
 return name;
 }

public void setName(String name) {
 this.name = name;
 }

}

The HomeController now looks like this:

 @RequestMapping(value = "/", method = RequestMethod.GET)
 public ModelAndView home(Locale locale, Model model) {
 logger.info("Welcome home! The client locale is {}.", locale);

 Date date = new Date();
 DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

 String formattedDate = dateFormat.format(date);

 model.addAttribute("serverTime", formattedDate );

 return new ModelAndView("home", "command", new User());
 }

 @RequestMapping(value = "/user", method = RequestMethod.POST)
 public String user(Locale locale, @ModelAttribute("SpringWeb")User user, Model model) {
 logger.info("Welcome " + user.getName());
 model.addAttribute(user);
 return "user";
 }

We will change the home.jsp to

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page session="false" %>
<html>
<head>
 <title>Home</title>
</head>
<body>
<h1>
 Hello world!
</h1>

<P> The time on the server is ${serverTime}. </P>

<form:form method="POST" action="/codesilo/user">
 <form:input path="name" />
 <input type="submit" value="submit"/>
</form:form>

</body>
</html>

And, change user.jsp to

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
 <title>User</title>
</head>
<body>
<h1>
 Hello User!
</h1>

<P> Welcome ${user.name} ! </P>
</body>
</html>

Now if we call the urls we will see this..

http://localhost:8080/codesilo/

SitemeshImage3

Once we hit submit we will get the following

SitemeshImage4

It seems that the POST works too. Maybe it’s some specific case that I have not run into yet.

 

Hashing passwords in Spring Security

July 8, 2012 1 comment

Passwords should not be stored in clear text. It is a best practice to have a one way hash created before storing it. Spring Security provides a very easy way to accomplish this. Just add a passwordEncoder to the authentication-provider in the spring security configuration.
An easy way to this in Spring 3 and later is to have the following config. This uses a SHA-256 algorithm and the username is used to salt the hash.

<authentication-manager>
 <authentication-provider user-service-ref="customUserDetailsService">
 <password-encoder hash="sha-256">
 <salt-source user-property="username"/>
 </password-encoder>
 </authentication-provider>
 </authentication-manager>

In order to use hashed passwords, it becomes necessary that we store them hashed too. In order to this in the application, we can have the SignUp class hash the passwords before storing it in the datasource. (in our case MongoDB).
Here is an excerpt from my class …

@RequestMapping(value = "/signUp", method = RequestMethod.POST)
 public String home(Locale locale, Model model, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) {
 MongoOperations mongoOperation = (MongoOperations)mongoTemplate;
 User user = new User(username, passwordEncoder.encodePassword(password, username), firstName, lastName);
 user.setRole(2);

 logger.debug(user.toString());
 mongoOperation.save(user, "user");
 logger.debug("Adding the user to the database");
 model.addAttribute("user", user );
 return "signUpSuccessful";
 }

The following bean is used in the mongo-config.xml class to support the signUp process.

<bean id="passwordEncoder"
 class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
 <constructor-arg value="256"/>
</bean>

Spring security provides one iteration of the hash by default. In order to provide Key Stretching we can provide more iterations by using the following config instead.

<bean id="passwordEncoder"
 class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
 <constructor-arg value="256"/>
 <property name="iterations" value="1000"/>
 </bean>

The authentication-manager in the security config file can be used to reference the same bean so that the same number of iterations are performed at authentication.

<authentication-manager>
 <authentication-provider user-service-ref="customUserDetailsService">
 <password-encoder ref="passwordEncoder">
 <salt-source user-property="username"/>
 </password-encoder>
 </authentication-provider>
 </authentication-manager>

References:
Spring Source Doc

MongoDB Spring Data and Spring Security with custom UserDetailsService

July 8, 2012 12 comments

In a earlier write up we saw how we can setup basic spring security. In this one we will see how to make a custom UserDetailsService instead of using the credentials in the configuration file. We will use MongoDB as a datasource.

We will use the project from the Spring Security project we created earlier and add the MongoDB config details and user service to provide the capability. See my previous blog for setting up MongoDB Spring Data.

Add the following to the mongo-config.xml file in the location WEB-INF/mongo/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mongo="http://www.springframework.org/schema/data/mongo"
 xsi:schemaLocation="http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.1.xsd
 http://www.springframework.org/schema/data/mongo
 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017" />

 <bean id="mongoTemplate"
 class="org.springframework.data.mongodb.core.MongoTemplate">
 <constructor-arg ref="mongo" />
 <constructor-arg name="databaseName" value="codesilo" />

 </bean>

 <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
 <context:annotation-config />

</beans>

Add the Spring Data dependencies in the pom.xml file

<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>2.7.2</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
 <version>1.1.0.M1</version>
 </dependency>
 <dependency>
 <groupId>cglib</groupId>
 <artifactId>cglib</artifactId>
 <version>2.2</version>
 </dependency>

Add the mongo-config.xml file to the contextConfigLocation on web.xml. The context param will look like this

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/root-context.xml
 /WEB-INF/spring/security-app-context.xml
 /WEB-INF/mongo/mongo-config.xml
 </param-value>
 </context-param>

We will now create a CustomUserDetailsService class that implements UserDetailsService. We will add the implementation of loadUserByUsername method. The CustomUserDetailsService is as follows. The getUserDetail method queries to get the user object from MongoDB (it is assumed that the data is already there).

package com.wordpress.codesilo.model;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class CustomUserDetailsService implements UserDetailsService {

private MongoTemplate mongoTemplate;

 public UserDetails loadUserByUsername(String username)
 throws UsernameNotFoundException {
 User user = getUserDetail(username);
 System.out.println(username);
 org.springframework.security.core.userdetails.User userDetail = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),true,true,true,true,getAuthorities(user.getRole()));
 return userDetail;
 }

@Autowired
 public void setMongoTemplate(MongoTemplate mongoTemplate) {
 this.mongoTemplate = mongoTemplate;
 }

 public List<GrantedAuthority> getAuthorities(Integer role) {
 List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
 if (role.intValue() == 1) {
 authList.add(new SimpleGrantedAuthority("ROLE_USER"));
 authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
 } else if (role.intValue() == 2) {
 authList.add(new SimpleGrantedAuthority("ROLE_USER"));
 }
 return authList;
 }

 public User getUserDetail(String username){
 MongoOperations mongoOperation = (MongoOperations)mongoTemplate;
 User user = mongoOperation.findOne(
 new Query(Criteria.where("username").is(username)),
 User.class);
 System.out.println(user.toString());
 return user;
 }

}

We will also create a user POJO which is as follows.

package com.wordpress.codesilo.model;

public class User {

public String username;
 public String password;
 public String firstName;
 public String lastName;
 public String email;
 public int role;

public User() {
 }

public int getRole() {
 return role;
 }

public void setRole(int role) {
 this.role = role;
 }

public User(String username, String password, String firstName,
 String lastName) {
 this.username = username;
 this.password = password;
 this.firstName = firstName;
 this.lastName = lastName;
 }

public String getUsername() {
 return username;
 }

public void setUsername(String username) {
 this.username = username;
 }

public String getPassword() {
 return password;
 }

public void setPassword(String password) {
 this.password = password;
 }

public String getFirstName() {
 return firstName;
 }

public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

public String getLastName() {
 return lastName;
 }

public void setLastName(String lastName) {
 this.lastName = lastName;
 }

public String getEmail() {
 return email;
 }

public void setEmail(String email) {
 this.email = email;
 }

@Override
 public String toString(){
 return "First Name:" + this.firstName + " Last Name:" + this.lastName + " Username:" + this.username ;
 }

}

As a last step we will change the security-app-context.xml to have the customUserDetailsService bean and user-service-ref in the authentication provider.

<beans:bean id="customUserDetailsService" class="com.wordpress.codesilo.model.CustomUserDetailsService"/>

 <authentication-manager>
 <authentication-provider user-service-ref="customUserDetailsService"/>
 </authentication-manager>

Now when we try to login to the application it will use the MongoDB to get the credentials.

We can also use the Security Context to get the principal and display the username and roles on home.jsp.
Add this to the pom dependencies.

<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-taglibs</artifactId>
 <version>${org.springframework-version}</version>
 </dependency>

Add the following taglib to the home.jsp page

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

and the following content on the jsp page to display the data.

<sec:authorize access="isAuthenticated()">
 Username: <sec:authentication property="principal.username" />
 Role: <sec:authentication property="principal.authorities"/>
 </sec:authorize>

Setting up a project with Spring Data and MongoDB

July 2, 2012 4 comments

From springsource : “The goal of the Spring Data Document (or DATADOC) framework is to provide an extension to the Spring programming model that supports writing applications that use Document databases”.
This blog will cover on how to use Spring Data with MongoDB. We will start with creating a simple Spring MVC application. See my previous blog to see how to setup a basic Spring MVC app using STS.

We will first add the dependencies on the pom file of the project.

<!-- Spring Data Mongo Driver -->

 <dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>2.7.2</version>
 </dependency>

 <dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
 <version>1.1.0.M1</version>
 </dependency>
 <dependency>
 <groupId>cglib</groupId>
 <artifactId>cglib</artifactId>
 <version>2.2</version>
 </dependency>

We will also need to add the Spring Milestone repo to the pom

<repositories>
 <repository>
 <id>spring-milestone</id>
 <name>Spring Maven MILESTONE Repository</name>
 <url>http://maven.springframework.org/milestone</url>
 </repository>
</repositories>

CONFIGURING MONGO TEMPLATE USING SPRING XML
We will now create a mongo-config.xml in the WEB-INF directory of the project. Add this as the content of the xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mongo="http://www.springframework.org/schema/data/mongo"
 xsi:schemaLocation="http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.1.xsd
 http://www.springframework.org/schema/data/mongo
 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017" />

 <bean id="mongoTemplate"
 class="org.springframework.data.mongodb.core.MongoTemplate">
 <constructor-arg ref="mongo" />
 <constructor-arg name="databaseName" value="codesilo" />

 </bean>

 <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
 <context:annotation-config />

</beans>

Add this to the web.xml configLocation

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/root-context.xml
 /WEB-INF/mongo-config.xml
 </param-value>
 </context-param>

We will keep things simple. Create a user model and refactor the homeController class to use that model. The HomeController class will create a User object, insert it in the database, query and return the first result to the view.
The following is the model User class.

public class User {

 public String username;
 public String password;
 public String firstName;
 public String lastName;

 public User(){

 }

 public User(String username, String password, String firstName, String lastName){
 this.username = username;
 this.password = password;
 this.firstName = firstName;
 this.lastName = lastName;
 }

 public String getUsername() {
 return username;
 }
 public void setUsername(String username) {
 this.username = username;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
 public String getFirstName() {
 return firstName;
 }
 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
 public String getLastName() {
 return lastName;
 }
 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 @Override
 public String toString(){
 return "User [username=" + username + ", passowrd= ****" + ", firstName=" + firstName + "lastName" + lastName + "]";
 }
}

Change the HomeController class to look like the following

@Controller
public class HomeController {

 @Autowired
 private MongoTemplate mongoTemplate;

 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

 /**
 * Simply selects the home view to render by returning its name.
 */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home(Locale locale, Model model) {

 logger.info("Welcome home! the client locale is "+ locale.toString());

 MongoOperations mongoOperation = (MongoOperations)mongoTemplate;
 User user = new User("codesilo", "Password", "Code", "Silo");
 mongoOperation.save(user);
 List<User> users = mongoOperation.find(
 new Query(Criteria.where("username").is("codesilo")),
 User.class);

 model.addAttribute("user", users.get(0).toString());

 return "home";
 }

}

Change the body of home.jsp to the following

<body>
<h1>
 Hello world!
</h1>

<P> Getting user from MongoDB: ${user} </P>
</body>

Now when we go to the application, we will see the following

and when we use the mongo shell to query the database, we get..

> db.user.find();
{ "_id" : ObjectId("4fef96227e27ff2b7a81331f"), "_class" : "com.wordpress.codesilo.model.User", "username" : "codesilo", "password" : "Password", "firstName" :
"Code", "lastName" : "Silo" }

References:
MongoTemplate- SpringSource Documentation