Monday, May 13, 2013

Various tool and their benefits


JSHint - JSHint is a community-driven tool to detect errors and potential problems in JavaScript code and to enforce your team’s coding conventions.JSHint can be used in eclipse via it's eclipse plugin  as well as in qunit to develop test cases which will consider each validation failure as test case failure.

W3c Markup validator - This validator checks the markup validity  of Web documents in HTML, XHTML, SMIL, MathML, etc.
Stripe Generator -This is a tool to generate stripe images by few clicks, in few seconds. These images can be used as background of a web page. 
SpriteMe -Sprite me is a javascript utility, whcih can be executed from any browser. During execution, it scans all the background images in current page and suggest possible spriting. The suggestion also include the number of request reduction happening on sptiring implementation. We can export the final spriting image along with corresponding CSS to be used for applying spriting in the page, from this tool. 
Trang - Tool to generate xsd from xml file

Various techniques & their benefit


CSS Sprites:CSS sprites are a way to reduce the number of images by combining several images into one. This technique is useful in reducing the all images load time.
Regular Expression - Regular Expression - Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data. In java regular expression evaluation engine's evaluation process can be tweaked in any of three possible flavors using quantifiers ie Greedy, Reluctant & Possessive

Wednesday, May 8, 2013

Various frameworks and their purposes

DWR (Direct Web Remoting) -DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.

Display tag -Display tag library can just... display tables! Give it a list of objects and it will handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table in a customizable XHTML style.

JQuery - jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

BlazeDS - BlazeDS is a server-based Java remoting and web messaging technology that allows you to connect to back-end distributed data and push data to Adobe Flex and Adobe Integrated Runtime (AIR) Rich Internet applications (RIA).

QUnit -QUnit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself!

Junit - JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

JUnitParamsIts a library, which acts as an extension to write parametric test cases in an easier fashion than conventional JUnit parametric test case writing and execution.It works on JUnit version greater than 4.6. Its change log and java doc can be accessed from  git and javadocslinks respectively.

Tuesday, May 7, 2013

Challenges while developing test for spring beans

Spring provides us options to test beans in application contexts using spring-test module. The detailed explanation of the way to use it can be accessed from the following link

I had maven based application. During the development and running of these test cases, I came accross few challenges. The key ones along with their resolutions are as mentioned below.

Issue - Compilation failure - SpringJUnit4ClassRunner.class and @ContextConfiguration not found
Solution - Included below mentioned maven dependency in the project and executed mvn eclipse:eclipse

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
            <version>3.1.2.RELEASE</version>
        </dependency>

Issue - IDE displying error - The type org.junit.runners.BlockJUnit4ClassRunner cannot be resolved. It is indirectly referenced from required .class files
Solution - BlockJUnit4ClassRunner was included in Junit4.5 so added below mentioned dependency of junit4.5 and executed mvn eclipse:eclipse

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
        </dependency>

Friday, January 18, 2013

Eliminating hibernate boiler plate code


While using Hibernate, we use below mentioned code each time, we perform any database operation.
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
 // your purposefull code goes here

 session.getTransaction().commit();
 return object;
} catch (Exception exception) {
 session.getTransaction().rollback();
 throw new RuntimeException(exception);
} finally {

 session.disconnect();
}
 We can eliminate the duplicity of this code by using the strategy, where this code will reside only  in HibernateUtil and while performing database operation, we will focus only on database operation, we want to perform.
The infrastructure code is as mentioned below - 
HibernateStrategy.java
package hibernate;

import org.hibernate.Session;

public interface HibernateStrategy {
 Object execute(Session session);
}
HibernateUtil.java
package hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

 private static SessionFactory sessionFactory;

 static {

  sessionFactory = new AnnotationConfiguration().configure()
    .buildSessionFactory();
 }

 public static Object performAction(final HibernateStrategy strategy) {
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  try {
   Object object = strategy.execute(session);
   session.getTransaction().commit();
   return object;
  } catch (Exception exception) {
   session.getTransaction().rollback();
   throw new RuntimeException(exception);
  } finally {

   session.disconnect();
  }
 }
}

The sample code using HibernateUtil is as mentioned below - 
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
  <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
  <property name="hibernate.connection.url">jdbc:hsqldb:mem:InMemoryDatabase</property>
  <property name="hibernate.connection.username">sa</property>
  <property name="hibernate.connection.password"></property>


  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">2</property>

  <property name="hibernate.hbm2ddl.auto">create-drop</property>
  <property name="hibernate.show_sql">true</property>

  <mapping class="hibernate.Student"></mapping>
 </session-factory>
</hibernate-configuration> 
Student.java
package hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Student")
public class Student {

 @Id
 @GeneratedValue
 private int studentId;
 private String name;
 private int age;

 public Student(final String name, final int age) {
  this.name = name;
  this.age = age;
 }

 public Student() {
 }

 @Override
 public String toString() {
  return "Student [studentId=" + studentId + ", name=" + name + ", age="
    + age + "]";
 }
}

Maven dependency
<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate</artifactId>
 <version>3.2.7.ga</version>
</dependency>
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> 
 <version>3.2.1.ga</version> </dependency> -->
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-annotations</artifactId>
 <version>3.2.1.ga</version>
 <exclusions>
  <exclusion>
   <artifactId>javax.transaction</artifactId>
   <groupId>jta</groupId>
  </exclusion>
 </exclusions>
</dependency>
<dependency>
 <groupId>javax.transaction</groupId>
 <artifactId>jta</artifactId>
 <version>1.1</version>
</dependency>
<dependency>
 <groupId>org.hsqldb</groupId>
 <artifactId>hsqldb</artifactId>
 <version>2.2.9</version>
</dependency>
HibernateUtilTest.java  (code to test above infrastructure)
package hibernate;

import java.util.List;
import junit.framework.TestCase;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class HibernateUtilTest extends TestCase {

 @Test
 public void testHibernateUtil2() {

  HibernateUtil.performAction(new HibernateStrategy() {
   @Override
   public Object execute(Session session) {
    Student student = new Student("Salil Verma-Test1", 20);
    session.saveOrUpdate(student);
    return new Object();
   }
  });

  List studentList = (List) HibernateUtil
    .performAction(new HibernateStrategy() {
     @Override
     public Object execute(Session session) {
      Criteria criteria = session.createCriteria(
        Student.class).add(
        Restrictions.eq("name", "Salil Verma-Test1"));

      return criteria.list();
     }
    });

  assertNotNull(studentList);
  assertEquals(1, studentList.size());
 }
}

Wednesday, December 26, 2012

How to create Objects in Javascript



JavaScript is an object oriented language. In-spite  of being class based , it is prototype based language, where we can create the prototype of specific objects.

Java script provides us three ways to create objects -
1- Direct instance using JSON ( Java Script Object Notation) syntax - In this way we do not create the prototype but direct object.
The sample code is as mentioned below -

var jsonObject = {
            text : "Json Object has been accessed ",
                  numberOfTimes : 0
  };


2- Direct instance using Object - In this way, we do not create prototype but direct object.
The sample code is as mentioned below -

  var directObject = new Object();
  directObject.text = "Direct created Object has been accessed ",
  directObject.numberOfTimes = 0;

3- Instance from prototype - In this way we create prototype and then create instances based on the prototype. This approach is beneficial when we want to create multiple objects based on the same prototype in the same application or want to use this prototype as utility.
The sample code  is as mentioned below -
function prototypeTest()
 {
    this.text;
    this.numberOfTimes;
 }
 var prototypeObject = new prototypeTest();
 prototypeObject.text="Object created through prototype has been accessed ";
 prototypeObject.numberOfTimes=0;


References -
http://www.w3schools.com/json/json_syntax.asp
http://www.w3schools.com/js/js_objects.asp
http://www.json.org/
 
  

Sunday, December 16, 2012

Copying the resources to and from windows network using Java



Using JCIFS - In this approach we use the implementation of CIFS (Common Internet File System) protocol, which is used for file sharing in windows.  File copy using this  approach is bit slower but suitable on the instances when the user running the program does not have direct access to the network folder and require to pass credentials to access. The sample code to copy file in network drive is as mentioned below - 

Required maven dependency -

<dependency>
 <groupId>org.samba.jcifs</groupId>
 <artifactId>jcifs</artifactId>
 <version>1.2.19</version>
</dependency> 

Sample code -

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

public class CopyFileUsingJCIFS {

 public static void main(String[] args) throws IOException {
  final String userName = "UserName";
  final String password = "Password";
  final String sourcePath = "pom.xml";
  final String destinationPath = "smb://SALIL-HP/Temp/pom.xml";

  copyFileUsingJcifs(userName, password, sourcePath, destinationPath);

  System.out.println("The file has been copied using JCIFS");
 }
 
 public static void copyFileUsingJcifs(final String userName,
   final String password, final String sourcePath,
   final String destinationPath) throws IOException {

  final String user = userName + ":" + password;
  final NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
    user);
  final SmbFile sFile = new SmbFile(destinationPath, auth);
  final SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(
    sFile);
  final FileInputStream fileInputStream = new FileInputStream(new File(
    sourcePath));

  final byte[] buf = new byte[16 * 1024 * 1024];
  int len;
  while ((len = fileInputStream.read(buf)) > 0) {
   smbFileOutputStream.write(buf, 0, len);
  }
  fileInputStream.close();
  smbFileOutputStream.close();
 }
}

 

Using  pure Java IO - This hand coded approach provides better performance than JCIFS but require the user running the java program to have direct access to the network resource. In this case we do not need to import any additional library. The sample code is as mentioned below -

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyingFile {

 public static void main(String[] args) throws IOException {
  final String sourcePath = "pom.xml";
  final String destinationPath = "//SALIL-HP/Temp/pom.xml";

  copyFile(sourcePath, destinationPath);

  System.out.println("The file has been copied using java");
 }

 public static void copyFile(final String sourcePath,
   final String destinationPath) throws IOException {

  final FileOutputStream fileOutputStream = new FileOutputStream(
    destinationPath);
  final FileInputStream fileInputStream = new FileInputStream(new File(
    sourcePath));

  final byte[] buf = new byte[16 * 1024 * 1024];
  int len;
  while ((len = fileInputStream.read(buf)) > 0) {
   fileOutputStream.write(buf, 0, len);
  }
  fileInputStream.close();
  fileOutputStream.close();
 }
}
 



Using commons-io  -  Apache provides FileUtils api, which contains multiple utility functions along with multiple utility methods of copying resources from one folder to network location. In this case code to write will be very small but we will need to include commons-io jar file in the project and user running the program would need to have direct access to the network resources.
The sample code is as mentioned below -

Required maven dependency - 


<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-io</artifactId>
 <version>1.3.2</version>
</dependency>

Sample Code
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CopyFileUsingCommonIO {

 public static void main(String[] args) throws IOException {
  FileUtils.copyFileToDirectory(new File("pom.xml"), new File("//SALIL-HP/Temp"));
 }
}