Grails

What is grails?
According to grail documentation
Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology.

What are the built-in features of Grails?

Data management:
It is easy with built-in Object Relational Mapping (ORM) using Hibernate

Cool view technology:
Similar to JSP groovy has Groovy Server Pages (GSP)

MVC
Integrated Spring MVC

Commandline
An interactive command line environment and build system based on Gradle

Servlet container: Has embedded Tomcat container with hot loading feature.

Global language
Support for internationalization (i18n) built on Spring

Transaction
A transactional service layer built on Spring’s transaction abstraction
All of these are made easy to use through the power of the Groovy language and the extensive use of Domain Specific Languages (DSLs)

HttpClient

What is HttpClient?
Any program or software that can make call to any url or webapplication using http proptocol is HttpClient.

What are the dependencies of HttpClient?
1. commons-codec jar 1.2
2. commons-logging jar 1.0.4
3. junit
What are the steps for using HttpClient?
1. Intantiate HttpClient.
2. Use any methods (GetMethod/Post etc) .The URL can be passed in the constructor
3. Invoke HttpClient to execute the method.
4. Read the response using stream and store it as string or any other object.
5. Release the connection.
6. Use the response.
Method that can be used in HttpClient
Options: It helps to retrive the options available.
Get: The get method which has the url and query parameters.
Head: The HEAD method similar GET except here message-body is not present in the response.
Post: For a POST request, with large request in the body
Multipart: Generally it is used for file uploads etc.
Put, Delete and Trace are also usable

How to use Google maps in Jaspersoft Studio

How to Use Google Maps in Jaspersoft Studio

The report in this example is developed on Jaspersoft Studio version: 6.3.1 final and deployed on Jaspersoft server version: 6.3.0 Enterprise edition.

Step 1: Create a report in jasper studio. In this example report is called GoogleMapsTest.

Screenshot (193)

1- Delete all the bands except Title and summary band. Use the query “Select 1 as one” in main data-set query.

Step 2: Adding the jasper map component to report.

Screenshot (173)

1- Add the text box to Title band and insert any relevant text into it.

2- Drag the Map component from Palette on to the Summary band of the report.

3- Add a data-set named “Markers” to the report, and use this query in it.

Query:

select ‘NorthCharleston’ as CityName,’-80.02842′ as Longitude,’32.92896′ as Latitude
union
select ‘GREENVILLE’ as CityName ,’-82.33626515′ as Longitude ,’34.79360263′ as Latitude
union
select ‘ZIBO’ as CityName,’117.8351787′ as Longitude,’37.17124911′ as Latitude
union
select ‘Mumbai’ as CityName, ‘72.9227767’ as Longitude, ‘19.10662726’ as Latitude

Step 3: Add markers to the map.

Screenshot (175)      Screenshot (176)

1- Click on the Map and select the Markers tab from the Properties section.

2- Add the created data-set to the marker by selecting the Data-set tab.

Step 4:Add markers properties.

Screenshot (177)

1- For adding marker properties, click the add button on right side, and insert the following details.

i.) Longitude & Latitude : For adding Longitude & Latitude, click the the properties icon on the right hand corner of the input text field. Check the “Use Expression” box and provide the latitude and longitude fields in their appropriate input boxes.

Screenshot (179)

ii.) Adding Mouse-over(Information appearing when hovered on marker) : For mouse-over information, insert data into the “Title” box in the window.

Screenshot (181)

iii.) Adding Pop-up window content(Content shown after clicking the marker) : For adding pop up window content, use the “Info Window”  text boxes.

Screenshot (183)

Step 5: Deploying the report in jaspersoft server

Publish the report on jasper server.

Screenshot (192)

………. and Voila..!!!!!!!!!!!

Thank You

Ravi Bhatta

 

 

Unit Test and JUnit Introduction

Testing is the process of checking the functionality of the application whether it is working as per requirements and to ensure that at developer level, unit testing comes into picture. Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.

A unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested. The percentage of code which is tested by unit tests is typically called test coverage.

 

A unit test examines the behavior of a distinct unit of work. Within a Java application, the “distinct unit of work” is often (but not always) a single method. By contrast, integration tests and acceptance tests examine how various components interact.

 

A unit of work is a task that isn’t directly dependent on the completion of any other task.

 

JUnit is a framework that was started by Kent Beck and Erich Gamma.

Erich Gamma is one of the Gang of Four who gave us the now-classic Design Patterns book

A framework is a semi-complete application. A framework provides a reusable, common structure to share among applications. Developers incorporate the framework into their own application and extend it to meet their specific needs.

 

JUnit (http://www.junit.org) is open source software, released under IBM’s Common Public License Version 1.0 and hosted on SourceForge. The Common Public License is business friendly: people can distribute JUnit with commercial products without a lot of red tape or restrictions.

Unit testing framework should follow several best practices like

– Each unit should run independently of all other unit tests.

– The framework should detect and report errors test by test.

– It should be easy to define which unit tests will run.

Example
public class Calculator {
public double add(double number1, double number2) {
return number1 + number2;
}
}

JUnit has many features that make it easy to write and run tests
– Separate test class instances and class loaders for each unit test to avoid side effects
– JUnit annotations to provide resource initialization and reclamation methods; @Before, @BeforeClass, @After, @AfterClass
– A variety of assert methods to make it easy to check the results of your tests
– Integration with other popular tools like ANT, MAVEN, and popular IDEs like Eclipse, NetBeans, IntelliJ and JBuilder

import static org.junit.Assert.*;
import org.junit.Test;
public class CalculatorTest { (1)
@Test
public void testAdd() { (2)
Calculator calculator = new Calculator(); (3)
double result = calculator.add(10, 50); (4)
assertEquals(60, result, 0); (5)
}
}

At 1, we start by defining a test class. The only restriction is that the class must be public; we can name it whatever we like.

At 2, we mark the method as a unit test method by adding the @Test annotation.
A best practice is to name test methods following the testXXX pattern. JUnit doesn’t
have method name restrictions. You can name your methods as you like; as long as
they have the @Test annotation, JUnit will execute them.

At 3, we start the test by creating an instance of the Calculator class (the “object
under test”), and at 4, as before, we execute the test by calling the method to test,
passing it two known values.
At 5, the JUnit framework begins to shine! To check the result of the test, we call
an assertEquals method, which we imported with a static import on the first line of
the class.

 

Assert Method

– assertTrue(String message, Boolean test)

– assertFalse(String message, Boolean test)

– assertNull(String message, Object object)

– assertNotNull(String message, Object object)

– assertEquals(String message, Object expected, Object actual) (uses equals method)

– assertSame(String message, Object expected, Object actual) (uses == operator)

– assertNotSame(String message, Object expected, Object actual)

 

 

File encryption/decryption using AES Algorithm

In this article the reader will learn about plain text file encryption using AES(Advanced Encryption Standard) algorithm.

In modern day cryptography AES algorithm gained much popularity because of its strength.

The message to be encrypted is called the plain text or clear text. The encrypted message, which is not in human readable format is called as cipher text.

In cryptography systems there are two main types of encryption standards.

  1. Public Key Cryptography
  2. Private Key Cryptography

In public key cryptography, there will be two keys for each party. One is private key and the other one is public key. The public key of the recipient is used by the sender for enctyption and the private key is used by the recipient for decryption. This kind of cryptography is also called as Assymetric key cryptography.

In Private key cryptography, there will be only one shared key between the two parties for both encryption and decryption. In this mode of cryptography maintaining the secrecy of the secret key is very important. This kind of cryptography is also called as Symmetric key cryptography.

In general the Asymmetric key cryptography is used for short messages such as encrypting passwords. Symmetric key cryptography is used for encrypting relatively long messages. In cryptography systems like PGP(Pretty Good Privacy) both kinds of cryptography techniques are used.

AES(Advanced Encryption Standard)

The key size of AES is in general 128 bits. Where as 256 bits and 512 bits keys are also possible to use. The javax.crypto package of the Java language has the implementation of the AES algorithm. For 256 bit key encryption/decryption special policy files should be copied into the \jre\lib\security directory, which can be downloaded from Oracle’s web site.

AES uses a block size of 16 bytes. That means it will encrypt the data in block sizes of 16 bytes. So, the plain text should be in multiples of size 16 bytes. But, a file may consist of data of any length. So, in order to encrypt data of length which is not multiples of 16 bytes we can use the following class CipherInputStream. This class can be used to encrypt a stream of plaintext.

public class Encryptor {

	//The password, salt and initializationVector should be preserved for decryption
	private char[] password;
	private byte[] salt;
	private byte[] initializationVector;

	public Encryptor() {
		this.password = "Some string as password".toCharArray();
		try {
			this.salt = "Some string as salt".getBytes("UTF-8");
			//Note: initializationVector should be of length 16 bytes
			this.initializationVector = "Some string of length 16 bytes".getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Encryptor aes = new Encryptor();
                //Pass the plaintext file and location of the encrypted file as command line arguments
		aes.encrypt(new File(args[0]), new File(args[1]));
	}

	public void encrypt(File plainTextFile, File encryptedLicenceFile) {

		if (encryptedLicenceFile.exists() == false) {
			try {
				encryptedLicenceFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		
		// To read the file to be encrypted
		FileInputStream fileInputStream = null;

		// To write the encrypted file
		FileOutputStream fileOutputStream = null;

		// To read the file information and to encrypt
		CipherInputStream cipherInputStream = null;
		try {
			fileInputStream = new FileInputStream(plainTextFile);
			fileOutputStream = new FileOutputStream(encryptedLicenceFile);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
			KeySpec keySpec = new PBEKeySpec(password, salt, 65536, 128);
			
			SecretKey secretKey = keyFactory.generateSecret(keySpec);
			SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);
			cipher.init(Cipher.ENCRYPT_MODE, secret, ivParameterSpec);

			cipherInputStream = new CipherInputStream(fileInputStream, cipher);

			int read;
			while ((read = cipherInputStream.read()) != -1) {
				fileOutputStream.write((char) read);
			}

			fileOutputStream.flush();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
				if (cipherInputStream != null) {
					cipherInputStream.close();
				}
				if (fileOutputStream != null) {
					fileOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

This code uses one plainTextFile and produces the encryptedFile. For decrypting we need to follow similar steps. The following code demonstrates the decryption. In the decrypt method we can use the following lines of code.

		// To read the ecrypted file
		FileInputStream fileInputStream = null;

		// To write decrypted file
		FileOutputStream fileOutputStream = null;

		// To read encrypted file and decrypt it
		CipherOutputStream cipherOutputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			fileInputStream = new FileInputStream(ecncrypedFile);
			byteArrayOutputStream = new ByteArrayOutputStream();

			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
			KeySpec keySpec = new PBEKeySpec(password, salt, 65536, 128);

			SecretKey secretKey = factory.generateSecret(keySpec);
			SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

			IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);

			cipher.init(Cipher.DECRYPT_MODE, secret, ivParameterSpec);

			cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, cipher);
			byte[] buffer = new byte[4096];

			int read;
			while ((read = fileInputStream.read(buffer)) != -1) {
				cipherOutputStream.write(buffer, 0, read);
			}

			if (cipherOutputStream != null) {
                                //Unless you close here you won't get complete plain text
				cipherOutputStream.close();
			}

			//The byte[] now can be used to obtain the cleartext
			byte[] plainText = byteArrayOutputStream.toByteArray();

The password, salt, and initializationVector must be the same while decrypting the cipher text. The decrypt method is left as reader’s exercise.

Thank you for reading.

Thanks and Regards,

Rajasekhar
Helical IT Solutions

ETL JOB FOR DOWNLOADING AND UNTARING TAR FILE FROM FTP

etlpic1

 

ETL JOB FOR DOWNLOADING AND UNTARING TAR FILE FROM FTP

1. To Download File from FTP , we first have to create connection by providing all credentials of FTP Server (Host-URl, Username, Password, Port No and which type of connection it is like FTP or SFTP)component Name : tFTPConnection
2. Then Next Task is to Provide Ftp File path (For this mention Ftp Location of file’s ) component Name : tFTPFileList
3. Once Done then we have to mention where we want to put that file (Here we mention Local System path where we want to put our Ftp file’s) component Name : tFTPGet

 filedownload

  ETL  JOB   TO PROCESSED TAR  FILE’S  AND ITERATE THEM ONE-BY-ONE

1. To Untar a tar file there is a component tFileArchieve but instead of that I am using GZipCompressor by using Java code in tJava component .
2. Here we just need to drag-n-drop tJava component , and in that provide the location of tar  file  and path  where you  untaring  your  tar file…

File dest = new File(dirName);

TarArchiveInputStream tarIn = new TarArchiveInputStream(

new GzipCompressorInputStream(

new BufferedInputStream( new FileInputStream( TarName ) )

);

TarArchiveEntry tarEntry = tarIn.getNextTarEntry();

while (tarEntry != null)

{

// create a file with the same name as the tarEntry

File destPath = new File(dest, tarEntry.getName());

System.out.println(“working: ” + destPath.getCanonicalPath()+”— Tar Entry: “);

context.csvloc=””+destPath.getParentFile();

System.out.println(“\nCSV FILE Location ::::”+context.csvloc+”\n”);

if(!(destPath.getParentFile().exists()))

{

System.out.println(“Dest: “+dest);

destPath.getParentFile().mkdirs();

}

if (tarEntry.isDirectory())

{

System.out.println(“Createing directory: “+tarEntry.getName());

destPath.mkdirs();

}

else

{

destPath.createNewFile();

byte [] btoRead = newbyte[2048];

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));

int len; //variable declared

while((len = tarIn.read(btoRead)) != -1)

{

bout.write(btoRead,0,len);

}

bout.close();

btoRead = null;

}

tarEntry = tarIn.getNextTarEntry();

}//while loop end here

tarIn.close();

(This  code is capable  of  searching  tar  file  in  given  folder as  well  as  untaring  that  file into  specified  folder  path)

Here “ dirName” denotes location where Tar file is present and “TarName” denotes name of the Tar file.
3. Regarding Iteration you can connect tFTPGet-component to this tJava-component by Iterate. By this way tJava-component get one Tar file at a time and processed it.

So  lastly the  flow  is  similar to  the  below  picture….

etlpic

Reading multiple properties files in spring 3 web MVC

    Reading multiple properties files in spring 3 web MVC

Spring allows us to externalize string literals in its context configuration files into external properties files, in order to separate application specific settings from framework specific configuration. Spring will read all the properties files declared by PropertyPlaceholderConfigurer bean to resolve the placeholders at application’s start up time.

Simple Example

Declare a PropertyPlaceholderConfigurer bean in spring’s application context as follows:
That tells spring to load the properties file name project.properties in the class path. An exception will be thrown if spring could not find specified property file.
The project.properties file should contain the name and value pair for example
Name = xyz
Filepath = C:/Test/Setting.xml
Host = localhost
User = testuser

By default spring look for the properties files in the application directory. So if we specify

Then it will find project.properties file under WEB-INF directory of the application in case of spring MVC application.
We can use prefix classpath: to tell spring load properties file in the application’s classpath. For example:

In the case of spring application the project.properties file should be present in WEB/INF/classes directory or in source directory src in eclipse IDE.

Use the prefix file:/// or file: to load property file from file system.

Spring context load the project.properties file from D:/Applicatin/Config else throws the exception if file is not present in the specified path.
Loading multiple properties files
Spring allows us to specify multiple properties files for the PropertyPlaceholderConfigurer as follows

classpath:/processor.properties
classpath:/datasource.properties

</property

We can add as many as properties file in list as shown above. Spring context will load all the properties files specified in list as shown above at the application start up time.

Loading Properties files values in spring controller
Suppose you have properties file as follows
Name = xyz
Filepath = C:/Test/Setting.xml
Host = localhost
User = testuser

We can use the variable read from properties files in spring controller by declaring @Component annotation in controller class for example:
@Controller
@Component
public class Controller{
@Value(“${Name}”)
String Name;
@Value(“${Filepath }”)
String Filepath;
@Value(“${Host }”)
String Host;
@Value(“${User }”)
String User;
}

The value of properties file automatic assign to declared variable by spring framework we can use these variables inside the application.

Muqtar Ahmed
Helical IT Solutions

INSTALL LIFERAY ON TOMCAT USING WAR

In my previous blog, I shared how to install liferay on existing tomcat using liferay source code. You can found my previous blog here http://helicaltech.com/install-liferay-existing-tomcat-7/

This blog will be talking about how to install liferay on Tomcat using WAR (existing Tomcat)

For this Section, I will refer to your tomcat’s installation folder as $TOMCAT_HOME. Before you begin, make sure that you have downloaded Liferay latest war file. If you haven’t downloaded, you can download from http://www.liferay.com/downloads/liferay-portal/additional-files (Find “Download Wars” section And portal dependencies files from “Dependencies” section).

After downloading, you will get a liferay-portal-6.1.x-<date>.war and liferay-portal-dependencies-6.1.x-<date>.zip.

If you have liferay in your machine, you don’t need to download liferay-portal-dependencies. You can use same Liferay global library as your portal-dependencies files.

Follow these steps, to install Liferay war in Tomcat:

Step-1

Create folder $TOMCAT_HOME/lib/ext.

Step-2

Extract the Liferay dependencies file to $TOMCAT_HOME/lib/ext.

The best way to get the appropriate versions of these files is, If you have liferay in your machine, then copy all .jar from $LIFERAY_HOME/lib/ext to $TOMCAT_HOME/lib/ext  (If you are going through this step, ignore Step-3 and Step-4)

or

Download the Liferay source code and get them from there. Once you have downloaded the Liferay source, unzip the source into a temporary folder and Copy the following jars from $LIFERAY_SOURCE/lib/development to $TOMCAT_HOME/lib/ext

activation.jar

jms.jar

jta.jar

jutf7.jar

mail.jar

persistence.jar

resin.jar

script-10.jar

 

Step-3

Make sure the JDBC driver for your database is accessible by Tomcat. Copy JDBC driver for your version of the database server to $TOMCAT_HOME/lib/ext.

 

Step-4

Liferay requires an additional jar to manage transactions. You may find this .jar here: http://www.oracle.com/technetwork/java/javaee/jta/index.html.

Step-5

Now, Edit $TOMCAT_HOME/conf/catalina.properties file. Change this line

common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar

to

common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar,${catalina.home}/lib/ext,${catalina.home}/lib/ext/*.jar

Step-6

Create setenv.bat in $TOMCAT_HOME/bin folder and add these lines:

if exist “[email protected]@/win” (

    if not “%JAVA_HOME%” == “” (

       set JAVA_HOME=

    )

 

    set “[email protected]@/win”

)

 

set “JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF8 -Djava.net.preferIPv4Stack=true -Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false -Duser.timezone=GMT -Xmx1024m -XX:MaxPermSize=256m”

 

Step-7

I am deploying liferay in $TOMCAT_HOME/webapps/ROOT folder. So we need to Create the directory $TOMCAT_HOME/conf/Catalina/localhost and create a ROOT.xml file in it. Edit this file and populate it with the following contents to set up a portal web application:

<Context path="" crossContext="true">

 
    <!-- JAAS -->
 
    <!--<Realm
       className="org.apache.catalina.realm.JAASRealm"
       appName="PortalRealm"
       userClassNames="com.liferay.portal.kernel.security.jaas.PortalPrincipal"
       roleClassNames="com.liferay.portal.kernel.security.jaas.PortalRole"
    />-->
 
    <!--
    Uncomment the following to disable persistent sessions across reboots.
    -->
 
    <!--<Manager pathname="" />-->
 
    <!--
    Uncomment the following to not use sessions. See the property
    "session.disabled" in portal.properties.
    -->
 
    <!--<Manager className="com.liferay.support.tomcat.session.SessionLessManagerBase" />-->

</Context>

 

Step-8

Now, Deploy Liferay.

If you are manually installing Liferay on a clean Tomcat server, delete the contents of the $TOMCAT_HOME/webapps/ROOT directory. This undeploys the default Tomcat home page. Then extract the liferay-portal-6.1.x-<date>.war file to $TOMCAT_HOME/webapps/ROOT.

Step-9

Start Tomcat by executing $TOMCAT_HOME/bin/startup.sh

Congratulations on successfully installing and deploying Liferay on Tomcat!

For any confusion, please get in touch with us at Helical IT Solutions