Wednesday, 19 March 2014

Java Custom ArrayList

This blog explains how internally a ArrayList stores data. To simplify the actual ArrayList implementation I have created a custom ArrayList class with minimum methods to add and get the elements. The ArrayList here uses generics and can also be instantiated without the generic parameter as allowed for java.util.ArrayList class.

Hashing + Symmetric Key Encryption

This post explains the concept of Hashing and how to use the generated hash key to generate a symmetric key which can be used to encrypt and decrypt data.

This kind of security is generally used in banks.

Hashing is a one way process unlike encryption. A encrypted data can be decrypted using the key by which the data was encrypted, but a hashed data can not be converted into its original data using the key or mostly called as salt.

Friday, 14 March 2014

Jquery to iterate XML POST response and populate table

<order>
<product>
<product_no>111</product_no>
<product_name>Camera</product_name>
<product_date>12-01-2013</product_date>
</product>
<product>
<product_no>1121</product_no>
<product_name>Mobile</product_name>
<product_date>14-01-2013</product_date>
</product>
<product>
<product_no>121</product_no>
<product_name>Bat</product_name>
<product_date>12-06-2013</product_date>
</product>
</order>
$.ajax({
 type : "POST",
 headers : {
 "Content-Type" : "application/xml"
 },
 url : 'rest/getorder',
 dataType : "xml",
 data : ''
  + $('#username').val() + ''
  + $('#password').val() + '',
 success : function(response) {  
   $(response).find('product').each(function() {
   $('#tbody').append(
    $('').append(
     $('').text(
      $(this).find('product_no').text()
     ),
     $('').text(
      $(this).find('product_name').text()
     ),
     $('').text(
      $(this).find('product_date').text()
     )
    )
   );
  
  });

  },
 error : function(response) {
  alert('error:' + response);
 }
 });
 
 <table cellpadding="5" cellspacing="5"
  style="border: 1px solid #ccc; background: #F1F6F6">
  <thead>
   <tr>
    <th>Product No</th>
    <th>Product Name</th>
    <th>Date</th>
   </tr>
  </thead>
  <tbody id="tbody"></tbody>
 </table>

Get the source code from here

Spring Rest MVC + JSP + Jquery


Spring MVC + REST + JSP + Jquery
This post explains how a application can be made with a combination of Spring  Rest MVC + JSP Jquery.

Below is the pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nihilent.rest</groupId>
  <artifactId>rest-web-app</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>rest-web-app</name>
  <url>http://maven.apache.org</url>
  <build>
  <finalName>rest-web-app</finalName>
 </build>
  <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.version>3.2.2.RELEASE</spring.version>
  <java.version>1.6</java.version>
  <servlet-api.version>2.5.0</servlet-api.version>
 </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.1.1</version>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.16</version>
  </dependency>
  <!-- JSTL -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.1.2</version>
  </dependency>

  <dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
  </dependency>

  <!-- for compile only, your container should have this -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.8</version>
  </dependency>
  </dependencies>
</project>

Below is the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- * This software is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 
 OR CONDITIONS OF ANY KIND. -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5">
 <display-name>Order Web Service</display-name>

 <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>/WEB-INF/classes/log4j.xml</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>rest</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>rest</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Spring context file rest-servlet.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:p="http://www.springframework.org/schema/p"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:oxm="http://www.springframework.org/schema/oxm"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
  default-autowire="byName">
 
 <context:component-scan base-package="com.nihilent.*" />
 <mvc:annotation-driven />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>

XML request message which will be needed to create XSD

<login>
<username>admin</username>
<password>admin</password>
</login>
<response>
<message>login successful</message>
</response>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="response">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="message"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

The Message XSD that can be created from any online tool from a XML

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="login">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="username"/>
        <xs:element type="xs:string" name="password"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Pojo created from the XSD. The POJO can be created by using the xjc command of JDK

package com.nihilent.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "username",
    "password"
})
@XmlRootElement(name = "login")
public class Login {

    @XmlElement(required = true)
    protected String username;
    @XmlElement(required = true)
    protected String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String value) {
        this.username = value;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String value) {
        this.password = value;
    }

}

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "message"
})
@XmlRootElement(name = "response")
public class Response {

    @XmlElement(required = true)
    protected String message;

   
    public String getMessage() {
        return message;
    }

    
    public void setMessage(String value) {
        this.message = value;
    }

}

Controller class RestController.java

package com.nihilent.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nihilent.model.Login;
import com.nihilent.model.Response;

@Controller

public class RestController {
 
 @RequestMapping(value = "/login", method = RequestMethod.POST, headers = "Accept=application/xml")
 public @ResponseBody
 Response login(@RequestBody Login login) {
  Response response = new Response();
  if(login.getUsername().equals("admin") && login.getPassword().equals("admin")){
   response.setMessage("login successful");
  }else{
   response.setMessage("login invalid");
  }
  
  return response;
 }
}


index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-ui.min.js"></script>
<script type="text/javascript" src="scripts/jquery.js"></script>

<link rel="stylesheet" href="styles/jquery-ui.css" type="text/css" />
</head>
<script>
 $(document).ready(function() {

 });
 function submitfun() {

  $.ajax({
   type : "POST",
   headers : {
    "Content-Type" : "application/xml"
   },
   url : 'rest/login',
   dataType : "xml",
   data : '<?xml version="1.0" encoding="UTF-8"?><login><username>'
     + $('#username').val() + '</username><password>'
     + $('#password').val() + '</password></login>',
   success : function(response) {

    $(response).find('message').each(function() {
     $('#response').html($(this).text());
    });

   },
   error : function(response) {
    alert('error:' + response);
   }
  });
 }
</script>
<body>

 <h1 align="center">Spring 3.0 MVC Rest + Jquery + JSP</h1>
 <table cellpadding="5" cellspacing="5" align="center"
  style="vertical-align: middle; border: 1px solid #ccc; background: #F1F6F6">
  <tr>
   <td>Username</td>
   <td><input id="username" type="text"></input></td>
  </tr>
  <tr>
   <td>Password</td>
   <td><input id="password" type="password"></input></td>
  </tr>
  <tr>
   <td align="center" colspan="2"><input type="button"
    value="Login" onclick="submitfun();" /></td>
  </tr>

 </table>

 <div align="center" id="response"></div>
</html>

The final structure of the project should be like :
Get the source code from here


The same rest service can also be tested using Google chrome app - Advanced Rest Client.
To know how see this blog
The rest service can also be tested using a HTTP client API from Apache which simulates the HTTP request. To see how it can be implemented, refer this blog

For Web Service Introduction click here

Below are some posts that explain how to implement and test SOAP/REST Webservices

Host
SOAP REST
JAX-WS JAX-RS
Spring-ws Spring-MVC-REST
Client
SOAP REST
JAX-WS(wsimport) Google REST APP
SOAP UI Apache REST

Wednesday, 12 March 2014

What is java this() and super()


A call to super() is the first statement inserted by default in all the constructors of all the classes. A class which does not have a super class, actually has a super class called Object. A call to super() means calling the default constructor of the super class. This is necessary because before initializing a class the super class should be initialized. A user can also call a parametric constructor from a constructor eg: super(1). Note here super(1) should be the first statement in the constructor.

The this() call is a call to a constructor of the same class. This also should be the first  statement in the constructor. If this statement occurs in a constructor then the call to super() is omitted.

Tuesday, 11 March 2014

Java static block

The static block in java is very similar to init block. The difference is instead of getting called before the constructor the static block gets called when the class is loaded in JVM. So when a instance of a class is created a static block gets called, then the init block and then the constructor. The static block's syntax is similar to init block with a difference that a term static needs to be places before the opening curly braces.
A class can have multiple static blocks and their execution will depend upon the order in which they are placed. Please note that just like static methods you can not initialize a instance variable in a static block.

Java init block

Init block is a code of block that gets executed before the constructor of a class gets called. It is denoted by open and closed curly braces without any name.
Their could be multiple init blocks inside a class. Their execution depends upon the order in which they are written. Init block are generally used when a common code needs to be invoked for every constructor, so instead of writing the same code in every constructor we can write the code in a common init block. below examples shows when and how init block gets called in inheritance.

Symmetric and Asymmetric key Encryption with Key tool

This post explains the concept of combining symmetric key and asymmetric key encryption with the use of key tool. For example which does this without the keytool refer here

Symmetric + Asymmetric + Signature

This type of security is more strong and secure then asymmetric key encryption. We have already seen how we can combine symmetric and asymmetric key encryption here. In this post we add more security by adding the concept of Digital Signature. In Symmetric + Asymmetric key we encrypt the symmetric key with the public key of a asymmetric key to make the symmetric key an message more secure, but still the authenticity of the sender of the encrypted symmetric key is not verified. This can be achieved by using Digital signature. To understand Digital signature first refer this post .

Java Digital Singnature


Digital Signatures are used to authenticate the sender sending the message. Digital signature are also based on Asymmetric key Encryption mentioned here. Here the sender signs the message by its private key and any receiver can verify the signature who has the public key. An analogy for digital signatures is the sealing of an envelope with a personal wax seal. The message can be opened by anyone, but the presence of the unique seal authenticates the sender. This is termed in Java as Digital Signature.

Saturday, 8 March 2014

Java JAR signing

Java security API provides features to digitally sign a jar. To see how to sign a text refer this blog. In this post we will see how a jar can be signed and what is the need to do so.

As mentioned before in previous posts, a signed data is just like a page with the signature of a person. The person reeving the page can identify that the page is signed by a person who portrays himself to be one. This type of security is same as security we see in bank cheque. The person signs a cheque and deposits it in a bank. In the bank the cashier verifies the signature on the cheque with the signature of the same person from the bank records.

Jar signing is basically and mostly used in Java Applet. A java applet is a piece of code that is embedded in html page and runs when the web page gets loaded. Applet are mostly stated to be harmful as they can run without any prior notification to the user who has loaded the page. To make user believe that the applet is from a secured source the programmer sign the applet. Then at the client side the browser verifies the signature of the signed jar, applet in this case.

Lets see a example below to sign a jar and then verify it.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClass {
 public static void main(String[] args) {
  
 

  File file = new File("C:/Softwares/robots.txt");
  FileInputStream fis = null;

  try {
   fis = new FileInputStream(file);
   int content;
   while ((content = fis.read()) != -1) {
    // convert to char and display it
    System.out.print((char) content);
   }

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fis != null)
     fis.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 }
}


To sign a jar, one needs to generate a private key/public key pair. Note that to sign a jar you will need a private key and the paired public key is send on the other side with the signed jar.
Run below command to generate the private key /public key pair.

keytool -genkeypair -alias client -keyalg RSA -keysize 1024 -storetype jceks -validity 365 -keypass password -keystore clientkeystore.jck -storepass password -dname "cn=localhost, ou=Verisign, o=MyComp Inc, l=Foster City, st=California, c=US"
Before signing the jar we need to create the jar of the java class mentioned above. Use the jar command mentioned below to do it.


jar cf hunaid.jar .


After the keystore is been generate we can sign the jar. Use the jarsigner command mentioned below to sign the jar.

jarsigner -storetype jceks -signedjar SignedApp.jar -keystore C:\Java_Security\To_Be_Shared\JavaSecurity\JavaSecurity\bi\clientkeystore.jck -storepass password hunaid.jar client


This above command will generate a file called SignedApp.jar which contains the same contains of the actual jar with two extra files in MANIFEST directory.

Jar verification is actually done by the browser. But one can manually also do the same. Below commands verifies the signed jar.

jarsigner -verify SignedApp.jar

The above commands verifies the signature of the JAR. This means that the jar was signed by the same a private key whose public key is present in the signed jar. The command gives below output

jar verified.

Warning:
This jar contains entries whose certificate chain is not valid

Re-run with the -verbose and -certs options for more details.

The verification was successful but is also gave a warning. The warning says that the certificate in the jar is not valid. The reason for this is that the keystore was a self signed keystore hence the certificate/public key generate was signed by the same private key and not by a trusted source CA.

To understand more about certificate chain refer blog Java keytool explored.

Share the post