06 November 2016

Easy Way to Create wrapper for Java Project

Most of the articles I have written for android related development issues. I thought need to write something new for java and spring related article.when I was in university when we running project what wed did was always run the project using IDE. But after joining to industry we know that we have to write executable file to run project in different environments. Let's say customer server may be windows, linux or mac .Then we have to create executable file which run in all platforms. If the project is simple what we can do is create executable jar and give to customer.

 But if the project contents configuration files this approach is not good.  Then we have to use better way to bundle executable files. So in this tutorial I will show you to how to create wrapper for java project but make sure you have to use maven.

First you have to add following property to pom.xml

1
2
3
<properties>
    <wrapper.location>${project.build.directory}/generated-resources/appassembler/jsw/#wrapper-name</wrapper.location>
</properties>

Then need to add following plugins to pom.xml and make sure change the main class and wrapper name.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-resources</id>
                <phase>process-classes</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/conf</outputDirectory>
                    <resources>
                        <resource>
                            <directory>${project.basedir}/src/main/resources</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
            <excludes>
                <exclude>**/*.yml</exclude>
                <exclude>**/*.txt</exclude>
            </excludes>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>appassembler-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
            <execution>
                <id>generate-jsw-scripts</id>
                <phase>package</phase>
                <goals>
                    <goal>generate-daemons</goal>
                </goals>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationDirectory>conf</configurationDirectory>
                    <daemons>
                        <daemon>
                            <id>#wrapper-name</id>
                            <wrapperMainClass>org.tanukisoftware.wrapper.WrapperSimpleApp</wrapperMainClass>
                            <mainClass>#Main-class</mainClass>
                            <commandLineArguments>
                                <commandLineArgument>start</commandLineArgument>
                            </commandLineArguments>
                            <platforms>
                                <platform>jsw</platform>
                            </platforms>
                            <generatorConfigurations>
                                <generatorConfiguration>
                                    <generator>jsw</generator>
                                    <configuration>
                                        <property>
                                            <name>wrapper.java.additional.1</name>
                                            <value>-Xloggc:logs/gclog</value>
                                        </property>
                                        <property>
                                            <name>wrapper.java.additional.2</name>
                                            <value>-XX:MaxDirectMemorySize=256M</value>
                                        </property>
                                        <property>
                                            <name>configuration.directory.in.classpath.first</name>
                                            <value>conf</value>
                                        </property>
                                        <property>
                                            <name>set.default.REPO_DIR</name>
                                            <value>lib</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile</name>
                                            <value>logs/wrapper.log</value>
                                        </property>
                                    </configuration>
                                    <includes>
                                        <include>linux-x86-32</include>
                                        <include>linux-x86-64</include>
                                    </includes>
                                </generatorConfiguration>
                            </generatorConfigurations>
                        </daemon>
                    </daemons>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.6</version>
        <executions>
            <execution>
                <id>make-log-dir</id>
                <phase>package</phase>
                <configuration>
                    <tasks>
                        <mkdir dir="${wrapper.location}/logs" />
                        <copy todir="${wrapper.location}/conf">
                            <fileset dir="target/conf" />
                        </copy>
                        <chmod dir="${wrapper.location}/bin" includes="**/*" perm="0755" />
                    </tasks>
                </configuration>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
            <descriptor>src/assembly/dep.xml</descriptor>
            <finalName>#app-name</finalName>
        </configuration>
        <executions>
            <execution>
                <id>create-archive</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>




And final Step is need to add assembly file to your project. Create assembly folder inside src folder and put the following dep.xml file in to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>bin</id>
<formats>
    <format>zip</format>
</formats>
<fileSets>
    <fileSet>
        <directory>${wrapper.location}</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
</fileSets>
</assembly>

And now you can see the wrapper-name.zip file in target folder. after extracting it inside the bin folder four executable files are there and bat file for windows and wrapper for linux . All the dependency jar files are under lib folder. and configurations in conf folder. Now in this way we can easily handle projects. Hope now you will learn something from my tutorial.

Android Dynamically Change Style colors

In this Tutorial I will discuss How to Change Android Style theme colors. Last few days I had to I have searched how to change android theme style color dynamically but android doesn't support to change theme colors dynamically. (Note :You can changed android pre-defined theme styles dynamically not the dynamic generated themes)

If we using Theme.AppCompat.Light.DarkActionBar then these are the main properties in layout.



If You want to change theme what you did was change the primary color and primaryDark color. And this code helps you to dynamically change the theme (above mention colors) colors.

This is for change primary Dark color.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static void setStatusBarColor(String color) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = currentActivity.getWindow();
        int statusBarColor = Color.parseColor(color);

        if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }
        window.setStatusBarColor(statusBarColor);
    }
}




This is for change primary color


1
2
getSupportActionBar().setBackgroundDrawable(
        new ColorDrawable(Color.parseColor("#AA3939")));



I hope this article help you to resolve your problem.
Thanks

07 August 2016

Android Realm Db Tutorial

These Days I have worked with android realm db project. So After done the project I thought It is better to write post about Realm db with android.

What Is Realm ??


Realm Db is No SQL framework which support android, ios to persistence data in mobile devices. When I start develop application with android there were few frameworks which support persistence. I worked with sqlite but the problem is It is hard to understand and write data and retrieve data.  But Realm db is the best android persistence framework I have ever seen. The main advantage is there is no sql syntax or queries . It is easy to understand  and implement.


This Diagram shows the simplicity of Realm db.



Configuration for android realm project

Add the following dependency to main project.


1
classpath "io.realm:realm-gradle-plugin:1.1.0"

Add the following dependency to sub project build.gradle file.
   
   Add the following line top of the build gradle file.

1
apply plugin: 'realm-android'

How to use Realm

Realm can be used any insert,update,delete operations in database. But unlikely sqlite realm gives easy way to handle data base operations . In here I will not show all the things in realm because realm documentation is better than my blog. So first we need realm object because realm object is a main concept in realm.

Let's say I need to add sales merchants to sales merchant table . First I create merchant object like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class SalesMerchant extends RealmObject {

    @PrimaryKey    private String id;

    private String name;

    private String address;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
Let's insert first data to realm db. First I will add the db 
configuration class to my project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import android.content.Context;

import io.realm.Realm;
import io.realm.RealmConfiguration;


public class DBConfiguration {

    private static String REALM_NAME = "sajith-blog.realm";

    public Realm getRealm(Context context) {
        Realm myOtherRealm = Realm.getInstance(
                new RealmConfiguration.Builder(context)
                        .name(REALM_NAME)
                        .build()
        );
        return myOtherRealm;
    }

}
Then Final stage write factory class to add data to database.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import domain.db.SalesMerchant;
import io.realm.Realm;


public class MerchantFactory {
    private Realm realm;

    public MerchantFactory(Realm realm) {
        this.realm = realm;
    }

    public void insertMerchant(final SalesMerchant salesMerchant) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override            public void execute(Realm bgRealm) {
                SalesMerchant addProduct = bgRealm.createObject(SalesMerchant.class);
                addProduct.setName(salesMerchant.getName());
                addProduct.setId(salesMerchant.getId());
                addProduct.setAddress(salesMerchant.getAddress());
            }
        });
    }

}
And that is it now you can see your data stored in database.
It is easy to handle transactions in realm db.
This tutorial is simple introduction of realm db. I just want to show how easy to use realm  and next tutorial i hope to go deep how to handle relationships in realm objects , Handle in different threads ,how to automatically populate db change in UI thread and other advanced techniques .


30 May 2016

Swagger with Dropwizard

In this post I will discuss how to integrate swagger in to dropwizard project.If you new to dropwizard this will help you to understand what is the dropwizard. So swagger is api documentation tool . For get basic knowledge swagger this will helps. But today I will integrate swagger in to dropwizard.

First you need to add this dependency to your project.

1
2
3
4
5
<dependency>
    <groupId>com.smoketurner</groupId>
    <artifactId>dropwizard-swagger</artifactId>
    <version>0.9.2-3</version>
</dependency>

And next thing is using annotation you have to document  resource class. This is the example of how to use swagger anotation.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Path("/studentManagement/api/")
@Api(value = "Student Management API", description = "Student Management API")
public interface StudentManagement {
    @GET
    @PermitAll
    @Path("/getAllStudent")
    @ApiOperation(value = "Get All Students")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "Error Occurred 
                                                     while getting data"),
            @ApiResponse(code = 404, message = "Student not found"),
            @ApiResponse(code = 405, message = "Validation exception") })
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Response getAllStudents();

    @GET
    @PermitAll
    @Path("/getStudent")
    @ApiOperation(value = "Get Students by Name")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "Error Occurred 
                                                     while getting data"),
            @ApiResponse(code = 404, message = "Student not found"),
            @ApiResponse(code = 405, message = "Validation exception") })
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Response getStudent(@QueryParam("name") String name,
                                 @QueryParam("age") int age);
}

And next step is you need add this swagger configuration to your dropwizard configuration class.


1
2
@JsonProperty("swagger")
    public SwaggerBundleConfiguration swaggerBundleConfiguration

And next step is in your dropwizard application you need to add swagger configuration bundle.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Override
    public void initialize(Bootstrap bootstrap) {
        bootstrap.addBundle(new SwaggerBundle() {
            @Override
            protected SwaggerBundleConfiguration 
                  getSwaggerBundleConfiguration(StudentManagementServerConfiguration configuration) {
                return configuration.swaggerBundleConfiguration;
            }
        });
    }
Last step is need to add your resource class package to yaml configuration file.


1
swagger:   resourcePackage: dev.innova.student.api




And that is all for this blog post.If you have any issue please
comment here.Thanks

29 March 2016

Introduction to Json Web Token




JSON web tokens are specifically for pass data between two parties securly.It is a industry standard protocol format.[https://tools.ietf.org/html/rfc7519]. In this tutorial i am mainly going to talk about how JWT is useful for client to server communication.Let’s assume you have http client and you need to communicate to rest server.So basically there are different ways to secure your connection.


  1. HTTPS
  2. User name password based authentication
  3. Pass custom secure   element using http header.

We all know that HTTPS is the secure way to communicate via HTTP protocol. But it is costly.So token based authentication gives the best security for your API design.


Usage Of JWT


JWT use for token based authentication.Token based authentication helps to authenticate server and client stateless. So No need to store client data in server side(Like sessions).

So Let’s see how JWT work in API.First when client login using username and password Then server validate the credentials and generate sign token and sent to client.Then client store token and every request send token with header.Then server verify the token and validate request.

Structure of JWT


Jason web token is this type.
aaaaa.bbbbbb.cccc So It have three parts.

Header
Payload
Signature

Header contains algorithm and type of token.

Payload is simply data you want to exchange two parties. These data type called as clams. There are two type of clams (Public and Private).
Ex:-
iss (issuer)
exp (expiration time)
sub (subject)
aud (audience)

Signature is the most advance part in web token. signature made using using this structure. Algorithem(base64urlencode(header) +"."base64urlencode(payload)+ secret)

Implementation Of JWT

There are lot of libraries available for creating and validate JSON web tokens.In this tutorial I have used this library.


1
2
3
4
5
<dependency>
    <groupid>org.bitbucket.b_c</groupid>
    <artifactid>jose4j</artifactid>
    <version>0.4.4</version>
</dependency>

Create JASON web token.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public String generateToken(String userName) {
        String jwt = null;
        try {
            JwtClaims claims = new JwtClaims();
            claims.setIssuer(userName);
            claims.setExpirationTimeMinutesInTheFuture(expiryTimeInMinutes);
            claims.setGeneratedJwtId();
            claims.setIssuedAtToNow();
            claims.setNotBeforeMinutesInThePast(beforeTimeTest);
            claims.setSubject(subject);


            JsonWebSignature jws = new JsonWebSignature();
            jws.setPayload(claims.toJson());
            jws.setKey(rsaJsonWebKey.getPrivateKey());
            jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
            jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

            jwt = jws.getCompactSerialization();
            logger.info("Token Created {}", jwt);

        } catch (JoseException e) {
            logger.error("Creating Token Failed {}", e);
        } catch (Exception ex) {
            logger.error("Error occurred while Creating Token {}", ex);
        }
        return jwt;
    }
Most important thing is creating token we can set expiration time so when authentication token from server side if token is expired then it helps to easily authenticate token.As example when user first login to system we create token send and then sequentially request by request client append that token to header and send to server.

Validating Web Token


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public boolean validateToken(String token) {
        boolean state;
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime()
                .setAllowedClockSkewInSeconds(30)
                .setRequireSubject()
                .setRequireExpirationTime()
                .setVerificationKey(rsaJsonWebKey.getKey())
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
            long expiredDateTime = jwtClaims.getExpirationTime().getValueInMillis();
            Date date = new Date(expiredDateTime);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.info("Token Expired Date : " + simpleDateFormat.format(date));
            state = true;
        } catch (InvalidJwtException e) {
            state = false;
            logger.debug("Error Occurred while validating JWT {}", e);
        } catch (MalformedClaimException e) {
            state = false;
        }
        return state;
    }

Above method validate Web Token if token expired it will throw exception. Hope you got some understand what is JSON web token and usage of web tokens.If you have any question feel free to comment in here.Thanks.