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"));
 }
}
 



Friday, December 7, 2012

HTMLCleaner - way to clean and format html files

HTMLCleaner is an open source html parser. This provides us option to convert ill format html to well format xml file and eliminating comments etc . Using HTMLCleaner, we can directly format the html files on the internet or in local system and store it in local file system.

We can include HTMLCleaner in any project using below dependency - 

<dependency>
 <groupId>net.sourceforge.htmlcleaner</groupId>
 <artifactId>htmlcleaner</artifactId>
 <version>2.2</version>
</dependency>
 Sample of command to perform the cleanup is as mentioned below -
mvn exec:java -Dexec.mainClass="org.htmlcleaner.CommandLine" -Dexec.args="src=C:\\Programming\\WorkSpace\\tempTestIndex.html dest=C:\\Programming\\WorkSpace\\abc.html outputtype=compact omitcomments=true"

For detailed list of available options, kindly  refer the below link -
http://htmlcleaner.sourceforge.net/commandlineuse.php

Reference -http://htmlcleaner.sourceforge.net/index.php

Creating executable jar with dependency using maven


Assembly plug-in is available in maven, which can be used to build jar including it's dependencies. We can associate this jar creation action with any one of maven phases. The sample code to build executable jar with dependency is as mentioned below -

<build>
  <plugins>
   <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <finalName>custom-name</finalName>
     <appendAssemblyId>false</appendAssemblyId>
     <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
     </descriptorRefs>
     <archive>
      <manifest>
       <mainClass>StarpApp</mainClass>
      </manifest>
     </archive>
    </configuration>
    <executions>
     <execution>
      <id>make-assembly</id> <!-- this is used for inheritance merges -->
      <phase>package</phase> <!-- bind to the packaging phase -->
      <goals>
       <goal>single</goal>
      </goals>
     </execution>
    </executions>
   </plugin>
  </plugins>
</build>

References -
http://maven.apache.org/plugins/maven-assembly-plugin/
http://salilstock.blogspot.in/2012/03/maven-build-and-dependency-management.html

Thursday, September 6, 2012

Way to use Mockito mocks in TDD


Mockito  is one of the leading mocking framework. It provides us functionality to create stubs and verify the invocation count of any specific method during any specific action.

Mocking is preferred during unit testing, when we either do not have real objects available for testing or want to focus on testing our newly created functionality without worrying about dependency  instantiation.

We need to use below maven dependency to include mockito  in our project -
<dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.8.5</version>
 </dependency>
To see  the way to use mockito, we will take a real life scenario, where we have trade interface and a validation class which has utility methods to validate the trade. In this example we want to test that validation method isTradeValid() is working as expected. 

We will perform below steps to test it -
1.       Create a mock stub of Trade interface using mockito
2.       Specify what the stub should return if any specific function is called.
3.       Call the method under test ,which is isTradeValid() and assert to validate the result
4.       verify that during execution of method under test, which is isTradeValid()  , other methods are called only specific number of times.

The sample code is as mentioned below -
Trade.java
package mockito;

public interface Trade {

 public String getPrincipal();

 public String getCounterparty();

 public Integer getNotional();

}
Validation.java
package mockito;

public class Validation {

 public boolean isTradeValid(Trade trade) {
  return trade.getNotional() > 0 && trade.getPrincipal() != null
    && trade.getCounterparty() != null;
 }
}
ValidateionTest.java
package mockito;

import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import junit.framework.TestCase;

public class ValidateionTest extends TestCase {

 @Mock
 private Trade trade;
 private Validation validation;

 @Override
 protected void setUp() throws Exception {
  super.setUp();
  MockitoAnnotations.initMocks(this);
  validation = new Validation();
 }

 public void testValidTrade() {
  Mockito.when(trade.getPrincipal()).thenReturn("JP Morgan");
  Mockito.when(trade.getCounterparty()).thenReturn("Morgan Stanly");
  Mockito.when(trade.getNotional()).thenReturn(1000);
  assertTrue(validation.isTradeValid(trade));
  Mockito.verify(trade, Mockito.times(1)).getPrincipal();
  Mockito.verify(trade, Mockito.times(1)).getCounterparty();
  Mockito.verify(trade, Mockito.times(1)).getNotional();
 }

 public void testInvalidTradeWithoutCounterparty() {
  Mockito.when(trade.getPrincipal()).thenReturn("JP Morgan");
  Mockito.when(trade.getCounterparty()).thenReturn(null);
  Mockito.when(trade.getNotional()).thenReturn(1000);
  assertFalse(validation.isTradeValid(trade));
  Mockito.verify(trade, Mockito.times(1)).getPrincipal();
  Mockito.verify(trade, Mockito.times(1)).getCounterparty();
  Mockito.verify(trade, Mockito.times(1)).getNotional();
 }
}

Description and use of mock API used in ValidateionTest is as mentioned below -
1.       @mock  is used  to mark which references we want to be initialized with corresponding stubs.
2.       MockitoAnnotations.initMocks(this); is used to ask the class to process and initialize the references, associated with @mock, with corresponding stubs.
3.       Mockito.when(trade.getPrincipal()).thenReturn("JP Morgan"); is used to specify what value should the stub return on invocation of specific function.
4.       Mockito.verify(trade, Mockito.times(1)).getPrincipal(); is used to verify the number of invocation of specific fucntion.

This project can be downloaded from here

References - http://salilstock.blogspot.in/2011/04/creating-mock-objects-for-test-driven.html