Thursday, September 29, 2011

JCIFS

The Java CIFS Client Library

JCIFS is an Open Source client library that implements the CIFS/SMB networking protocol in 100% Java. CIFS is the standard file sharing protocol on the Microsoft Windows platform (e.g. Map Network Drive ...). This client is used extensively in production on large Intranets.

1)Download JCIFS using below URL
http://jcifs.samba.org/src/jcifs-1.3.16.zip

2)One sample program for accessing a file of other systems which is in network and writing something on that.

 Logon.java
------------------------------------------------------

import java.io.FileOutputStream;

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

public class Logon {
    public static void main( String argv[] ) throws Exception {
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("ISSHYD.COM", "isshyd\\kirankumar.g", "indiangk1791$");
             String path = "smb://192.168.1.209/D$/file1.txt";
        SmbFile sFile = new SmbFile(path, auth);
             SmbFileOutputStream sfos = new SmbFileOutputStream(sFile,true);
            sfos.write("\n append-kiran6".getBytes());
        System.out.println("Done");
      
        // sFile.delete();
    }
}

Note :
Add jcifs.jar in build path before running this program
In this program,
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", "username", "password");

ISSHYD.COM----------->is domaine name of system to access(MyComputer-->Right click-->then see once your domain name of system)(giving domain name is not necessary you can give empty "" )
isshyd\\kirankumar.g-------->is username of system to access
indiangk1791$------------->is password of system to access.
192.168.1.209-------------->IP Address of system to access.

in this program i am accessing file1.txt file in D drive of System and wrote some thing on that file.

Note2:once  see jcifs home/examples folder sample programs.

3)Another Sample program to access all the folders and files of a specific directory.

Here i am accessing all the files and folders of  D drive.

Sample1.java
---------------------------------------------------------------

import java.io.BufferedInputStream;
import java.io.FileInputStream;

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

public class Sample1 {
    public static void main( String argv[] ) throws Exception {
        //String user = "ISSHYD\\kirankumar.g:indiangk1791$";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domaine", "username", "password");
             String path = "smb://192.168.1.214/D$/";
        SmbFile sFile = new SmbFile(path, auth);
              SmbFile[] files = sFile.listFiles();
        System.out.println("files");
       
        for (SmbFile x : files) {
            System.out.println("file: " + x + ".  path: " + x.getPath() + ".  isDirectory? " + x.isDirectory());
           
       
            if (x.isDirectory()) {
                for (SmbFile dir : x.listFiles()) {
                    System.out.println("dir file: " + dir + ".  path: " + dir.getPath() + ".  isDirectory? " + dir.isDirectory());
                }
            }
        }
    }
}


ANT Tool

1)Download ant tool here

How to find IP Address of System

* you can use command Prompt statement for this.
the commands to find IP Address  are below,
C:\>ipconfig
or
C:\>ipconfig/all

(or)

*Finding IP address using java programme

 FingIPAddress.java
---------------------------------------
import java.net.*;
public class FindIPAddress {
public static void main(String[] args) throws UnknownHostException{
InetAddress ia = InetAddress.getLocalHost();
String s=ia.toString();
System.out.println("IP address to a String is: "+s);
    }
}

Usage of Windows Batch file for java developers

The file which is having (anynameXXX).bat extension then these files are called Windows Batch files.

In this batch file we can write all the commands that we generally use in Command Prompt.
one sample java example with sequence of steps are shown below.

1)create a java class as shown below,

 WindowsBatchFileUsage.java
-------------------------------------------

public class WindowsBatchFileUsage {
    public static void main( String argv[] ) throws Exception {
       
        System.out.println("MyBatch.bat Batch File executed successfully");
    }
}

2)Now i don't want to open my command prompt for compile and execute this java class.
i write a batch file(MyBacth.bat),that contains all the commands to compile and execute my java class.

create a file with extension of .bat ,Right click  edit that file and write following commands and save.
MyBatch.bat
---------------------------------
javac *.java
java WindowsBatchFileUsage
pause


3)Now double click that batch file(MyBatch.bat)
it opens command prompt and executes all the commands that we write in batch file.


Wednesday, September 28, 2011

Create Executable jar

The steps to create Executable jar are as follows,

1) create a java class under the package test.

Executablejar.java
---------------------

package test;
class Executablejar
{
public static void main(String a[])
{
System.out.println("HELLO WORLD");
}

}

2)compile above java class

C:\>javac Executablejar.java -d .

here don't forget to give space between  -d and dot(.) 

3)once run the Executablejar class
to run use following command,
c:\>java test.Executablejar

then you can see "HELLO WORLD" is displayed on console.

4)Then create this manifest file (manifest.txt) with any text editor.

manifest.txt
------------------
Main-Class: test.Executablejar

Note:Don't forget to press enter after write above line and then save.otherwise you get an error
message as "Failed to load Main-Class manifest attribute from
myjar.jar"

5)Next, preparation of executable jar
 
c:\>jar cvfm myjar.jar manifest.txt test
 
here test is the package name of my class .
 
6)Then you are able to start the Executablejar.class by double-clicking on the myjar.jar file (if the JRE is correctly installed) or by typing

c:\>java -jar myjar.jar
 
then you get output as "HELLO WORLD"
 
 
 
Note:
To view the content of the jar file you can use the fallowing command
C:\>jar tf myjar.jar
It displays as:
D:\javaprogramess >jar tf myjar.jar
META-INF/
META-INF/MANIFEST.MF
test/
test/Executablejar.class
 



Read a file using BufferedInputStream

BufferedInputStreamExample.java
----------------------------------------------------------------------------------
import java.io.*;

public class BufferedInputStreamExample {
        public static void main(String[] args) throws Exception {
           
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/logins.txt"));
                while (bis.available() > 0)
                {
                System.out.print((char)bis.read());
                }
                 bis.close();
        }
}

Tuesday, September 27, 2011

Create Folder Using JAVA

FolderCreation.java
-----------------------------------------------------
import java.io.File;
/**
 * @author kirankumarg
 *
 */
public class FolderCreation {
     public static String Path = "D:/SampleFolder/";
    //public static String Path = "D:/SampleFolder/subfolder1/subfolder2/subf3/subf4";
    /**
     * @param args
     */
    public static void main(String[] args) {
        File folder = new File(Path);
        //check whether folder exists or not
        if(!folder.exists()){
            folder.mkdir();//use this for a single folder creation
            //folder.mkdirs();//use this for subfolders creation in a Folder
            System.out.println("Folder has been created Successfully ... ");
        }
    }
}

Add password protection to your PDF

Hi Friends,
            Some times we need security to our Portable Document Format(PDF) files.Because we have some confidential matter in that.So we need Security.

 Add password protection to your PDF files online - it's easy and free.
Go to following site ,
http://www.pdfprotect.net/


Caching in Hibernate

     Cache reduces network round trips between client and server applications.

                           Hibernate uses two different caches for objects:

first-level cache (at Session Object level as built-in cache in Hibernate)
and
second-level cache.(at SessionFactory Object level as Configurable cache )

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.
                        
                                * Second level cache is Configurable cache,the third party vendors are supplying various  second level caching s/w's for hibernate application.But all these caching s/w related jar files are available in  HIBERNATE_HOME/lib.......

Cache Implementations

Hibernate supports four open-source second level cache implementations named 
EHCache (Easy Hibernate Cache),
OSCache (Open Symphony Cache),
Swarm Cache, and
JBoss Tree Cache.
Each cache has different performance, memory use, and configuration possibilities



How To Configure JBoss Tree Cache?

1. Download the latest cache provider jar from JBoss’ Maven2 repository.
(jar files are available in  your_HIBERNATE_HOME/lib....... )
2.Activate Second Level cache
Modify your hibernate.cfg.xml and enable second level cache:
<property name="hibernate.cache.use_second_level_cache">true</property>
 
3. Configure the cache provider in hibernate.cfg.xml , using one of the three options below:
  • If JBoss Cache instance is bound to JMX (i.e. when deploying within JBoss Application Server), select JmxBoundTreeCacheProvider as cache provider and add the cache’s MBean object name:
<property name="hibernate.cache.provider_class">
  org.jboss.hibernate.jbc.cacheprovider.JmxBoundTreeCacheProvider
</property>
<property name="hibernate.treecache.mbean.object_name">
  portal:service=TreeCache,type=hibernate
</property>
  • If JBoss Cache instance is bound to JNDI, select JndiBoundTreeCacheProvider as the cache provider and add the cache’s JNDI name:
<property name="hibernate.cache.provider_class">
  org.jboss.hibernate.jbc.cacheprovider.JndiBoundTreeCacheProvider
</property>
<property name="hibernate.cache.jndi">
  JndiBoundTreeCacheInstance
</property>
  • If running Hibernate and JBoss Cache standalone or within third party Application Server, select TreeCacheProvider as the cache provider and add the path to cache’s configuration file:
<property name="hibernate.cache.provider_class">
  org.jboss.hibernate.jbc.cacheprovider.TreeCacheProvider
</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">
  treecache-optimistic.xml or(treecache.xml)
</property>
 
 once see treecache.xml file in hibernatehome/project/etc folder and copy this
 treecache.xml in our project 
 
Note 1: org.jboss.hibernate.jbc.cacheprovider.TreeCacheProvider is only fully functional since 1.0.1.GA release.
Note 2: In 1.0.0.GA, default value for
* hibernate.cache.provider_configuration_file_resource_path was treecache-optimistic.xml but from 1.0.1.GA, this has been changed to treecache.xml to match old standalone standalone JBoss Cache based cache provider. If treecache.xml is not present, old default, treecache-optimistic.xml, is looked up in case it's present. See JBCLUSTER-217 for more information.

Note : once see Hibernate home/etc folder/Hibernate.properties file  (search second level cache here)

How to Activate Query Cache in Hibernate:
 Query Cache is a sub cache of second level cache,to store Hql Queries related results in the form of hibernate pojo class objectsBy default second level cache does not activate QueryCache .the programmer needs to enable this explicitly by using following property in hibernate.cfg.xml.

<property name="hibernate.cache.use_query_cache"> true </property>







Reference links:
http://community.jboss.org/wiki/NewJBossCache14xBasedHibernate32CacheProvider
http://www.javabeat.net/articles/37-introduction-to-hibernate-caching-1.html


Sunday, September 25, 2011

Robot Class in java

Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.

This sample code will show the use of Robot class to handle the keyboard events. 

 RobotExp.java
-----------------------
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotExp {
   
    public static void main(String[] args) {
 
        try {
         
            Robot robot = new Robot();
           
            // Robot start writting(This Robot is Controlled by KIRAN)
            robot.delay(5000);
            robot.keyPress(KeyEvent.VK_H);
            robot.keyPress(KeyEvent.VK_I);
            robot.keyPress(KeyEvent.VK_SPACE);
            robot.keyPress(KeyEvent.VK_K);
            robot.keyPress(KeyEvent.VK_I);
            robot.keyPress(KeyEvent.VK_R);
            robot.keyPress(KeyEvent.VK_A);
            robot.keyPress(KeyEvent.VK_N);
          // robot.keyPress(KeyEvent.VK_F1);
          
        
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}


If you run this code and open a notepad or wordpad or any other  then this code will write "hi kiran" in the notepad.

Cactus For UnitTesting JEE Code

Cactus is a simple test framework for unit testing server-side Java code (Servlets, EJBs, Tag libs, ...) from the Jakarta Project. The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it. Cactus implements an in-container strategy, meaning that tests are executed inside the container.

The Steps to Configure Cactus are below,

1) the library files it sets up are junit-3.8.1.jar, aspectjrt-1.1.1.jar, cactus-1.6.1.jar, commons-httpclient-2.0.jar, and commons-logging-1.0.3.jar.
As for the web.xml file, it will use the following configuration:

 
<servlet>
	<servlet-name>ServletTestRunner</servlet-name>
	<servlet-class>
		org.apache.cactus.server.runner.ServletTestRunner
	</servlet-class>
</servlet>

<servlet>
	<servlet-name>ServletRedirector</servlet-name>
	<servlet-class>
		org.apache.cactus.server.ServletTestRedirector
	</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>ServletTestRunner</servlet-name>
	<url-pattern>/ServletTestRunner</url-pattern>
</servlet-mapping>

<servlet-mapping>
	<servlet-name>ServletRedirector</servlet-name>
	<url-pattern>/ServletRedirector</url-pattern>
</servlet-mapping>
 
 
2) Take following java classes in default or any other pkg.
                       this is our Test Class
TestSampleServlet.java
--------------------------
import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;


public class TestSampleServlet extends ServletTestCase
{
    public TestSampleServlet(String theName)
    {
        super(theName);
    }

    public static Test suite()
    {
        return new TestSuite(TestSampleServlet.class);
    }
  
   public void beginSaveToSessionOK(WebRequest webRequest)
	    {
             //here we set i/p parameters for testing method

	        webRequest.addParameter("ipparam", "90");
	    }
   
	    public void testSaveToSessionOK()
	    {
	        
	    	 SampleServlet servlet = new SampleServlet();
	         servlet.saveToSession(request);
	         assertEquals(90, session.getAttribute("testAttribute"));
	    }
}	
 
Clearly observe methods,
public void beginXXX(WebRequest theRequest)
public void testXXX()
public static Test suite()
public void endXXX(WebResponse theResponse) 
 (Note : Once see Methods,here   http://jakarta.apache.org/cactus/writing/howto_testcase.html )

 
 
SampleServlet
------------------
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;


public class SampleServlet extends HttpServlet
{
    public void saveToSession(HttpServletRequest request)
    {
       //here we get all  the i/p parameters that we set in beginxxxx(-) in above class
    	String testparam = request.getParameter("ipparam");
 
       //Businessservice to test
    	PatientVitalsBusinessService patbservice = new PatientVitalsBusinessService();
    	PatientVitals pat=null;
        try{
        	 System.out.println("in  ----- try block ----:::::");
       //here findByID() Business Method to test.
		    pat = patbservice.findByID(Integer.parseInt(request.getParameter("ipparam")));
		    System.out.println("patttttttttttttttttt id:::::"+pat.getPavId()+"-"+pat.getPavCreatedbyTxt()+"-"+pat.getPavTmpType()+"-"+pat.getPavWtUnit());
		    request.getSession().setAttribute("testAttribute", pat.getPavId()); 
        }catch(Exception e){
                	e.printStackTrace();
        }
    }
}	

3)Test the Application.
write this url in browser, 
http://localhost:8080/(your WebApplicationName)CactusJakartaExample/ServletTestRunner?suite=TestSampleServlet


Here the steps are,
* our web application call ServletTestRunner class which is configured in web.xml
*this automatically calls TestSampleServlet class 
* Here beginxxxx() executed and calls testxxxxx()
* so finally our Business method calls and output come as XML format.
 

Monday, September 5, 2011

Eclipse plugin Struts2.x

This is the simplest way to install this plugin.
Update site URL is http://mvcwebproject.sourceforge.net/update/

open your eclipse (with a user having sufficient privileges to update eclipse). Open Help/Software updates/Find and Install...

Note:see this site http://mvcwebproject.sourceforge.net/install.html

Eclipse plugin for web application development that used Struts

StrutsIDE is an Eclipse plugin for web application development that used Struts. It requires Eclipse 3.0 (or higher), JDT, GEF and EclipseHTMLEditor. And, it recommends Sysdeo Tomcat Plugin. But it is not indispensable.
StrutsIDE supports Struts 1.2.

Download Following jars ,

 http://sourceforge.jp/projects/amateras/downloads/48176/tk.eclipse.plugin.struts_2.0.7.jar/



http://sourceforge.jp/projects/amateras/downloads/51002/tk.eclipse.plugin.htmleditor_2.1.0.jar/




Put the downloaded JARs file into ECLIPSE_HOME/plugins or ECLIPSE_HOME/dropins.


Restart eclipse, take a new dynamic web project in eclipse.
Right click on web project-->New-->Other-->
you can find Amateras-->Struts.
 


Note: once see this site, http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=StrutsIDE