Showing posts with the label Java

Secure Spring Boot REST API using Basic Authentication

This is the third post of my Spring Boot Blog post series. In the very first post, I talked about my experience with creating RESTFul Services using Spring Boot. Then I have expanded the sample to integrate with Swagger documentation. In this post, I am going to expand above sample with security aspect.

What is API Security

API Security is a wide area with many different definitions, meanings, and solutions. The main key terms in API security are Authorization, Authentication, Encryption, Federation, and Delegation. However, I am not going to talk about each of them here.

What is Authentication

Authentication is used to reliably determine the identity of an end user and give access to the resources based on the correctly identified user.

What is Basic Authentication

Basic Authentication is the simplest way to enforce access controling to resources. Here, the HTTP user agent provides the username and the password when making a request. The string containing the username and password separ…

Integrating Swagger with Spring Boot REST API

In the last post, I talked about my experience with creating RESTFul Services using Spring Boot. When creating a REST API, proper documentation is a mandatory part of it.

What is Swagger?

Swagger(Swagger 2) is a specification for describing and documenting a REST API. It specifies the format of the REST web services including URL, Resources, methods, etc. Swagger will generate documentation from the application code and handle the rendering part as well.

In this post, I am going to integrate Swagger 2 documentation into a Spring Boot based REST web service. So I am going to use Springfox implementation to generate the swagger documentation. If you want to know how to run/build Spring Boot project, please refer my previous post.

Springfox provides two dependencies to generate API Doc and Swagger UI. If you are not expecting to integrate Swagger UI into your API level, no need to add  Swagger UI dependency.


Building a RESTFul Service using Spring Boot

Everyone is talking about Microservices such as WSO2 Microservice Framework, Spring Boot, etc. Since I haven't worked on any Spring related project since a very long time, I thought to implement a simple RESTFul service using Spring Boot.

So I started with Spring documentation. It is straightforward.  You can create the structure of your project using "Spring Initializr". This is an online tool where you can add all the desired dependencies to your project POM file. Since I am a big fan of Maven, I am generating a maven project.

In the Spring Initializr UI, you can choose the Language, Spring Boot Version, Project Group ID, artifact name, etc. Please refer below screenshot for information I have provided while generating the project.

When clicking on "Generate Project", it will download zipped maven project into your computer. Unzip it and import into an IDE. The initial project structure is like below.

In my HelloWorld REST service implementation, it accepts u…

Java 8 lambda expression for list/array conversion

1). Convert List to List ( List of Strings to List of Integers)

List<Integer>  integerList =; 

// the longer full lambda version:  List<Integer>  integerList  = -> Integer.parseInt(s)).collect(Collectors.toList());

2). Convert List to int[](List of Strings to int array)
int[] intArray =;

3). Convert String[] to List ( String array to List of Integers)
List<Integer>  integerList = Stream.of(array).map(Integer::parseInt).collect(Collectors.toList());

4). Convert String[] to int[] (String array to int array)
int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
5). Convert String[] to List (String array to Double List)
List<Double> doubleList = Stream.of(stringArray).map(Double::parseDouble).collect(Collectors.toList());
6). Convert int[] to String[] (int array to String array)

WSO2 Governance Registry Lifecycle transition inputs

WSO2 Governance Registry (WSO2 G-Reg) is a fully open source product for governing SOA deployments, which provides many extension points to ensure your business policies. With G-Reg 5.0.0 release, we have introduced revolutionary UIs for enterprise asset management and discovery. 
The Lifecycle of an asset is one of the critical requirements of enterprise asset management and Lifecycle management is focused on various state changes in a given artifact through different phases. If you want to read more about this, please go through my article on "Governance Framework Extension Points."
So here I am going to talk about, one of the feature enhancements which we added for G-Reg 5.3.0. With G-Reg 5.3.0, we have introduced lifecycle transition input for G-Reg publisher. With lifecycle transition inputs, you will be able to parse custom inputs from a user who is doing lifecycle operation. 
As an example, you have integrated wso2 governance registry with API Management product using…

Java - String intern() Method

String Intern method returns an individual representation for the given String object. When the intern() method get invoked on a String object, it will look up the other interned strings, and if a String object exists in the memory with the same content, it will return the existing reference. Otherwise, it will return a new reference.

Example usage of String intern:

Think about a web application with a caching layer. If cache got missed, it would go to the Database. When the application is running with the high level of concurrency, we should not send all the request to the database. Such a situation we can check whether, multiple calls coming to the same reference by checking String intern.


String name1 = "Value";
String name2 = "Value";
String name3 = new String("Value");
String name4 = new String("Value").intern();

if ( name1 == name2 ){
    System.out.println("name1 and name2 are same");
if ( name1 == name3 ){

Maven Compiler Plugin

The Maven Compiler Plugin is used to compile the java source code of your project. The default compiler is javac and is used to compile Java sources. By modifying pom.xml file, you can customize the default behavior of Maven Compiler Plugin. 

Using Maven Compiler Plugin, you can compile the source code of a certain project to a different version of JVM than what you are currently using. EX: compile using JDK 1.8 and target JVM is 1.7. Default source setting is JDK 1.5, and the default target setting is JDK 1.5

Example configuration is as below:

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins…

Java7: Strings in Switch Statements

Switch statements with String is long waiting enhancement which is requested 1995(Decade before I have joined to IT industry).

This String switch statement uses the equal operation to compare the String object in expression and label. Therefore String switch statement is case sensitive. Also according to the Java documentation, this switch statement is more efficient than if-else statements("Java compiler generates generally more efficient bytecode from switch statements").

public void stringSwitchStatement(String value) { switch (value) { case "Chandana": System.out.println("Input is Chandana"); break; case "OtherValue": case "OtherValue2": System.out.println("Other inputs : " + value); break; case "Test": System.out.println("Input is Test"); break; default: throw new IllegalArgumentException("Invalid input value : " + value); } }

Java7 : Multiple Catch Block with example

With JAVA SE 7, Multi-catch exceptions handling has been introduced and it is a convinent way for exception handling, since we can catch multiple exceptions using one catch block.

In the "Multi-catch" block each exception should be separated by pipe (|) charatcter and that will make code is more readable.

Read more : Working with Java SE 7 

Ex: public class SampleClass { public static void main(String[] args) { try { // Your code } catch (ParseException | IOException exception) { // inside the multie catch block } } }

Configure External Solr server with Governance Registry

In WSO2 Governance Registry 5.0.0, we have upgraded Apache Solr version into 5.2 release. With that you can connect WSO2 Governance Registry into an external Solr server or Solr cluster. External Solr integration provides features to gain comprehensive Administration Interfaces, High scalability and Fault Tolerance, Easy Monitoring and many more Solr capabilities.

Let me explain how you can connect WSO2 Governance Registry server with an external Apache Solr server.

1). First, you have to download Apache Solr 5.x.x from the below location.
Please note that we have only verified with Solr 5.2.0 and 5.2.1 versions only.

2). Then unzip Solr Zip file. Once unzipped, it's content will look like the below.

The bin folder contains the scripts to start and stop the server. Before starting the Solr server, you have to make sure JAVA_HOME variable is set properly. Apache Solr is shipped with an inbuilt Jetty server.

3). …

Writing a Create API Executor for API.RXT

One of the use cases of the WSO2 Governance Registry is storing metadata information of different artifacts. In an Organization, there can be different metadata of different artifacts such their REST APIs, SOAP Services etc. In such a scenario you can use API and Service RXT which are available in the WSO2 Governance Registry to store metadata information.

With the use of API metadata which is stored in the WSO2 Governance Registry, you can publish APIs into WSO2 API Manager without accessing the web interface of the API Manager. This API creation is handled through lifecycle executor of the WSO2 Governance Registry. Once lifecycle state of the api publisher is reached, the executor will invoke Publisher REST API of the WSO2 API Manager and create the API. "Integrating with WSO2 API Manager" documentation explains about how to create an API using SOAP service meta data information.

If you want to create an API using the REST API metadata information available in the WSO2…

Maven excludes all transitive dependencies

"Transitive dependencies are a new feature in Maven 2.0. This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically."

I had a problem, where some dependencies were available in the run time, but they weren't available in the public nexus repositories. For an example, Hibernate depends on the Sun JTA API JAR and it is not available in the central Maven repository because it cannot be freely redistributed. So when building the project, it was trying to download transitive dependencies and got failed.

So I looked  a way to ignore all the transitive dependencies, and found that we can ignore all the associated dependencies of a given dependency. There we can exclude all transitive dependencies without specifying groupId and artifactId of the dependencies. So need to use astric(*) character as groupid and artifactid of the dependency.
<dependency> <groupId>sample.ProjectA</grou…

Host name verification failed for

Are you getting a " Host name verification failed for host" exception as below while trying to connect with a different host? 

TID: [0] [AM] [2014-08-28 14:41:51,936] ERROR {org.apache.synapse.transport.passthru.TargetHandler} - I/O error: Host name verification failed for host : {org.apache.synapse.transport.passthru.TargetHandler} Host name verification failed for host : at org.apache.synapse.transport.http.conn.ClientSSLSetupHandler.verify(
at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(
at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(
at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(
at org.apache.http.i…

Build Maven Multi Module Project and Run using one Command

When we have maven multi module project, there will be dependency between sub project. Therefor if you need to build all projects need tp navigate to parent directory and run the mvn clean install command.

If we have web based multi module project, currently most people doing is go to parent directory and build the all projects using mvn install or mvn clean install command, after that navigate to web project and start web container.

Ex: Projects are P1(parent project), Core and Web. When we building project go to P1 and build the all subprojects, after that go to web project and start jetty server using mvn jetty:run

But that approach wasting you time little bit and when we doing same thing all the time it will become boring  task to do(build parent and go to child folder and run the server)

For avoid this issue I am going to show how to run web project with out navigate to child project.

following command will help you to run specific project without moving to sub project folder.


Change Jetty Server Running Port

Jetty is one one of the best development server which I have ever used. It is easy to work with jetty server and its light weight

Here I am going to show how to change jetty server running port.  Jetty server default running port is 8080.

Port with Maven: 

 Command line:          For starting jetty server we are using mvn jetty:run command. We can change the port jetty server running by passing run time argument to it.

mvn -Djetty.port=80 jetty:run

 Using pom.xml
                By changing jetty plugin system properties as below, you can change the jetty running port.
<plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <configuration> <stopPort>9966</stopPort> <stopKey>foo</stopKey> <systemProperties> <systemproperty> <name>jetty.port</name> <value>80</value> </systemproperty> </systemP…

Maven add jar without install

I have some problem with adding external jar in to maven project without install it. If I install JAR file other people who working on same project, have to install same JAR. them I want to avoid that issue.

First need to place jar file inside lib folder. After that using following POM entry we can use it as dependency.

<dependency> <groupId>com.chandana</groupId> <artifactId>example</artifactId> <version>0.1</version> <scope>system</scope> <systemPath>${basedir}/lib/example.0.1.jar</systemPath> </dependency>

Ex: <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.5.0</version> <scope>system</scope> <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath> </dependency>
 Here very important option is <scope>system</scope>. It's say dependency provide with system, no need …

Maven commands and hint

svn checkout without subfolders

svn co --depth immediates URL
maven without internet(Without downloading)

mvn -o install
mvn --offline install

Force the check of the latest dependency jars
mvn -U install
mvn --update-snapshots install

*** -U option to update your snapshots

Skip the tests

mvn install -DskipTests

also use the maven.test.skip property to skip compiling the tests

mvn install -Dmaven.test.skip=true

Remote Debug

mvnDebug test
mvnDebug install

To avoid OutOfMemoryError

To avoid OutOfMemoryError when running maven, set environment variable MAVEN_OPTS as below

MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=256m

If you have issue with Maven does not find JUnit test cases to run:
By default Maven runs tests class which names start with Test or end with Test or TestCase.Do not messed up the naming convention

Introduction to OSGi - 2 (OSGi Services)

There are so many OSGi tutorials, blogs, and samples. I am going to add another OSGi sample/tutorial with my OSGi leanings. Here is my previous article regarding OSGi(Introduction to OSGi).

An OSGi Service is a java object instance which is registered with OSGi framework with set of attributes. Services can be accessed via service registry(performed via the class BundleContext). BundleActivator is to be invoked on start and stop. When BundleActivator call start method we are going to register our service. After that any bundle can access that service.

Service Bundle:

In service bundle you need to export your service and need to register it via service registry. When we are exporting service we export interface package only. As usual that is to hide the implementation from the other bundles.

I have created a sample OSGi project called HelloServcie

Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: HelloService Bundle-SymbolicName: com.chandana.hello.HelloSer…

How to Ignore Files or Directories in Subversion

We are facing a common problem when trying to commit some changes to the SVN. That is each time we have to ignore some JAR files, because those JAR files are user run time specific and if they are committed, it would not work on other local runtimes.

Here is a pretty simple solution for this problem. We can tell subversion to ignore directories or specific files as follows.

Ignore directories or specific files.
   svn propedit svn:ignore ./some_path
It will ignore all files in the specified directory. Here only wildcard indication is supported, and regular expressions are not supported.

Example wildcard supprt:
 svn propedit svn:ignore *
Example ingnore class files with wildcard:
  svn propedit svn:ignore *.class

If you are using Eclipse SubEclispe plugin,

Right Click file or folder --> Team --> Then click on svn:ignore

How to debug using Maven Jetty

Debugging is a better approach to find out bugs in our programs. Here is a way to debug a maven project, and I am going to run my web application in the Jetty server.

First you need to add the following environmental variables on your Windows/Linux environment.

MAVEN_OPTS = -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=y Now go to your maven web project location through command line and start the jetter server -> mvn jetty:run

Now in eclipse debug configuration, add a remote Java application instance on port 4000. Then Add some debug points to your codes  and start the remote app instance on debug mode. You can see the steps from following screen shots.

In this manner you can debug your java web apps and find out the bugs. With this way you can debug your java web app.

if you are using maven latest version( Maven 2.0.8 or later)

run the
mvnDebug command instead of
mvn and attach a debugger on port 8000.

Love to hear from yo…