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

Saturday, August 18, 2012

H2 In-memory database


In-memory databases  are the databases which reside in main memory.These databases either partially or fully lack the durability property of ACID (atomicity, consistency,isolation and durability).
In-memory databases are used when either we want very quick performance  or in the cases where data used in application does not need to be durable. While developing the testcases of DAO layer, in memory database in embedded mode is preferred.  This provide quick access and full control of databases in the test.
In the arena of in-memory databases H2 has it significant presence.It can be included in the application using maven dependency and can be run in imbedded or standalone mode.
Maven Dependency
  <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>1.3.167</version>
  </dependency>
Bean configuration to start and stop the H2 database along with spring bean factory creation and destroy
<bean id = "org.h2.tools.Server"
            class="org.h2.tools.Server"
            factory-method="createTcpServer"
            init-method="start"
            destroy-method="stop">
    <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,8043" />
</bean>
H2 default connection details
driver - org.h2.Driver
Hibernate Dialect -org.hibernate.dialect.H2Dialect
jdbc url -jdbc:h2:~/test
user name - sa
password -
Starting server from command line-

java -cp h2-1.3.167.jar org.h2.tools.Server
Shutting down server from command line –

java -cp h2-1.3.167.jar org.h2.tools.Server -tcpShutdown tcp://localhost:909

Basic setup to use H2 in unit testing -
To use H2 in unit test cases, we might want to extend H2DBEnabledTestCase class, which starts the H2 server in setup method  so that during test run database could be available and stops server in tearDown method.

import java.sql.SQLException;
import org.h2.tools.Server;
import junit.framework.TestCase;

public abstract class H2DBEnabledTestCase extends TestCase {

 private Server httpServer;

 @Override
 protected void setUp() throws SQLException {
  httpServer = Server.createTcpServer(
    new String[] { "-tcpPort", "8080", "-tcpAllowOthers" }).start();
 }

 @Override
 protected void tearDown() {
  if (httpServer != null && httpServer.isRunning(false)) {
   httpServer.stop();
  }
 }
}
H2 In-memory - The complete in-memory usage, keeps the complete database in main memory.  As soon as the database is shut down all the data gets lost.To use database in this way we neither need to explicitly start not stop it. Database will automatically become available as soon as you try to access it with specific URL.
In-memory jdbc url - jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
Using the database in embedded mode Sample-
While including H2 in our application, we implemented facade for performing H2 related interactions and operations.

Sample use of H2 using above mentioned facade

Running application of above code can be downloaded from here . You will need java 6.0 and maven 3 to get the application running.

Kindly follow below mentioned steps to see it in execution –
  1. Download the application and extract it.
  2. Execute mvn eclipse:eclipse by traversing to the location of pom.xml
  3. Import the application in eclipse
  4. Run H2ServerTest.java  as Junit test.

Reference
http://www.h2database.com/html/tutorial.html
http://en.wikipedia.org/wiki/In-memory_database

Tuesday, June 19, 2012

Environment Troubleshooting commands

Remotely restart the windows machine -
runas /netonly /noprofile /user:<domain>\<administrator of server to reboot> "cmd"
shutdown -r -f -m \\<servername>

We can shutdown and log-off the computer remotely as well by tweaking some parameter in the above command

Testing SMTP server status via command line
telnet smtp.example.com 25
helo testing
First command will establish a connection with smtp server and bring the first response mentioning that smtp server is up. Second command will test that smtp server is responding to the commands.

Updating boot options - http://ask-leo.com/how_do_i_remove_boot_choices_that_i_no_longer_want.html
http://support.microsoft.com/kb/323427

Configuring start-up options -http://www.wintuts.com/System-Configuration-Utility

Dell Laptop drivers -
http://www.dell.com/support/drivers/us/en/19/DriversHome/NeedProductSelection

Dell Laptop Driver installation order -
http://support.dell.com/support/topics/global.aspx/support/kcs/document?c=us&cs=19&l=en&s=dhs&docid=DSN_1A0C0937D62A8739E0401E0A55174744&isLegacy=true

Reference-
runas
-http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true
shutdown- http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/shutdown.mspx?mfr=true
smtp test -  http://www.febooti.com/products/automation-workshop/tutorials/test-smtp-connection-send-test-email.html

Tuesday, June 12, 2012

Jasper subreport – Way to modularize jasper reports


We come across such a situation where a specific report section appears in multiple reports. Example - An external client focused company might have a contact information section in all of its reports. Company’s decision to change the format of contact information section might result in amending all the reports, involving huge manual effort.

Jasper reports provides a modularization mechanism where we can develop the working re-usable part of report independently and plug it in where ever needed.  This binding of reusable part to main report is runtime binding. So any changes in re-usable report would automatically get reflected wherever it has been used.

As an example to deal with above mentioned problem efficiently, we could have developed the contact information section as an independent report and plugged it in all other reports.

Jasper provides subreport tag to achieve modularity, where we can define how and where the included section should appear in the main report. We can pass the parent’s or derived connection, data sources or parameter map to be used for populating the included reports. 

Jasper subreport example - To demo the working of sub-reports, we will develop two reports called simpleSubreport.jrxml, simpleSubreport2.jrxml and use these modular components in simpleMaster.jrxml so that the complete report could be generated in a single shot-

simpleSubreport.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="SimpleSubreport" language="java" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30">

 <field name="subTitle" class="java.lang.String"></field>
 
 <detail>
  <band height="100">
  <textField>
  <reportElement positionType="Float" x="55" y="14" width="75" height="41"/>
  <textElement/>
  <textFieldExpression class="java.lang.String"><![CDATA[$F{subTitle}]]></textFieldExpression>
  </textField>
  </band>
 </detail>
</jasperReport> 

simpleSubreport2.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="SimpleSubreport2" language="java" pageWidth="200" pageHeight="842" columnWidth="200" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">

 <field name="subTitle" class="java.lang.String"></field>
 
 <detail>
  <band height="100">
   <staticText>
   <reportElement positionType="Float" mode="Opaque" x="36" y="8" width="100" height="16" backcolor="#ff8000"/>
   <textElement/>
   </staticText>
   
   <textField>
   <reportElement positionType="Float" x="35" y="35" width="110" height="30"/>
   <textElement/>
   <textFieldExpression class="java.lang.String"><![CDATA[$F{subTitle}]]></textFieldExpression>
   </textField>
  </band>
 </detail>
</jasperReport>

simpleMaster.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="SimpleMaster" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30">
 <parameter name="mainReportParameterMap" class="java.util.HashMap"/>

 <field name="master" class="java.lang.String"/>
 <field name="id" class="java.lang.String"/>
 <field name="id2" class="java.lang.String"/>
 <title>
  <band height="107" splitType="Stretch">
   <textField>
    <reportElement positionType="Float" x="79" y="8" width="167" height="30"/>
    <textElement/>
    <textFieldExpression class="java.lang.String"><![CDATA[$P{mainReportParameterMap}.get("title")]]></textFieldExpression>
   </textField>
   <textField>
    <reportElement positionType="Float" x="86" y="63" width="190" height="32"/>
    <textElement/>
    <textFieldExpression class="java.lang.String"><![CDATA[$F{master}]]></textFieldExpression>
   </textField>
  </band>
 </title>
 <detail>
  <band height="100" splitType="Stretch">
   <subreport>
    <reportElement positionType="Float" x="67" y="18" width="168" height="47"/>
    <subreportParameter name="id">
     <subreportParameterExpression><![CDATA[$P{mainReportParameterMap}.get($F{id})]]></subreportParameterExpression>
    </subreportParameter>
    <dataSourceExpression><![CDATA[$P{mainReportParameterMap}.get($F{id})]]></dataSourceExpression>
    <subreportExpression class="java.lang.String"><![CDATA["simpleSubreport.jasper"]]></subreportExpression>
   </subreport>
   <subreport>
    <reportElement positionType="Float" x="249" y="18" width="168" height="47"/>
    <subreportParameter name="id2">
     <subreportParameterExpression><![CDATA[$P{mainReportParameterMap}.get($F{id2})]]></subreportParameterExpression>
    </subreportParameter>
    <dataSourceExpression><![CDATA[$P{mainReportParameterMap}.get($F{id2})]]></dataSourceExpression>
    <subreportExpression class="java.lang.String"><![CDATA["simpleSubreport2.jasper"]]></subreportExpression>
   </subreport>
  </band>
 </detail>
 <pageFooter>
  <band height="15" splitType="Stretch">
   <textField>
    <reportElement x="0" y="0" width="520" height="15"/>
    <textElement textAlignment="Right"/>
    <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}+"/"]]></textFieldExpression>
   </textField>
   <textField evaluationTime="Report">
    <reportElement x="521" y="0" width="14" height="15"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
   </textField>
  </band>
 </pageFooter>
</jasperReport>

SubReportExample.java
package subreportexample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import utility.JasperUtility;

@SuppressWarnings("rawtypes")
public class SubReportExample {

 static String jrxmlFileLocation = "src\\main\\resources\\subreportexample\\";
 static String jasperFileLocation = "target\\classes\\subreportexample\\";
 String outputPDFFile = "target\\classes\\subreportexample\\SubReportFile.pdf";;
 final int firstDatasourceNumber = 1;
 final int secondDatasourceNumber = 2;

 /**
  * @throws JRException
  */
 @SuppressWarnings("unchecked")
 private void generateReport() throws JRException {

  List simpleSubMasterList = getMapArrayListForReport(firstDatasourceNumber);
  JRMapCollectionDataSource firstReportDataSource = new JRMapCollectionDataSource(
    simpleSubMasterList);

  simpleSubMasterList = getMapArrayListForReport(secondDatasourceNumber);
  JRMapCollectionDataSource secondReportDataSource = new JRMapCollectionDataSource(
    simpleSubMasterList);

  HashMap mainReportParameterMap = new HashMap();
  mainReportParameterMap.put("title", "Title of master report");
  mainReportParameterMap.put("subDS", firstReportDataSource);
  mainReportParameterMap.put("subDS2", secondReportDataSource);

  Map mainReportDSElementMap = new HashMap();
  mainReportDSElementMap.put("master",
    "This portion is from master report");
  mainReportDSElementMap.put("id", "subDS");
  mainReportDSElementMap.put("id2", "subDS2");

  List simpleMasterList = new ArrayList();
  simpleMasterList.add(mainReportDSElementMap);
  JRDataSource simpleDS = new JRMapCollectionDataSource(simpleMasterList);

  Map parameters = new HashMap();
  parameters.put("mainReportParameterMap", mainReportParameterMap);

  JasperRunManager.runReportToPdfFile(jasperFileLocation
    + "simpleMaster.jasper", outputPDFFile, parameters, simpleDS);
 }

 /**
  * @param firstDatasourceNumber
  * @return
  */
 @SuppressWarnings("unchecked")
 private List getMapArrayListForReport(int firstDatasourceNumber) {
  List simpleSubMasterList = new ArrayList();

  for (int i = 0; i < 30; i++) {
   Map simpleSubMasterMap = new HashMap();
   simpleSubMasterMap.put("subTitle", "This is subtitile no " + i
     + " of data source no " + firstDatasourceNumber);
   simpleSubMasterList.add(simpleSubMasterMap);
  }
  return simpleSubMasterList;
 }

 public static void main(String[] args) throws JRException {
  compileJrxmlFiles();
  new SubReportExample().generateReport();
  System.out.println("done");
 }

 private static void compileJrxmlFiles() throws JRException {
  JasperUtility.compileAndGenerateJasperFile(jrxmlFileLocation,
    jasperFileLocation, "simpleMaster", "simpleSubreport",
    "simpleSubreport2");
 }
}

Sample Project -
Sample project can be downloaded from here

 You will need maven-3 along with java 5 or higher version, setup in your machine to run the sample.
Kindly follow the below mentioned steps to run the sample and get the report -
  1. Download & unzip the project
  2. Run- mvn clean eclipse:eclipse install in project's home directory
  3. Import the application in eclipse
  4. Execute SubReportExample.java file
  5. Sample pdf will be generated at target\\classes\\subreportexample\\SubReportFile.pdf location.
References
http://salilstock.blogspot.in/2012/05/jasperreport-open-source-java-reporting.html
http://salilstock.blogspot.in/2012/05/including-page-number-and-page-count-in.html