Monday, April 30, 2012

Java: File searching program

To search a particular file recursively

Let’s see a Java program which will search a particular file recursively. In this example we will provide a root path from where it will search a particular file recursively. Either you can search a file by its name or you can provide a valid regular expression.

Using this logic you can implement a file searcher program.

About the example:

Logic behind this program is very simple; it searches a root folder recursively. If the current path is a directory then it will call the same function searchFile(String path, String search) again and again till the particular node file is reached. Now if it is a node file then it will search for the String or the given regular expression.

Let’s see a simple self explanatory java code. No need to add any jar file, directly you can run below the below program and see the output. Just provide a root path and String or valid regular expression to search.

/* SearchFile.java */

import java.io.File;

public class SearchFile {

 /* path : provide root directory from where it will search recursively.
  * search : String or valid regular expression. 
  */ 
 public void searchFile(String path,String search) {
  
  File file = new File(path);
  
  //System.out.println("Searching.."+file.getAbsolutePath());
  
  if(file.isDirectory()) {
   File[] allFilesInDirectory = file.listFiles();
   
   for (File eachFile : allFilesInDirectory) {  
    searchFile(eachFile.getAbsolutePath(),search);
   }
  }
  else {
   if(file.getName().matches(search)) {
    System.out.println("File Found >> "+file.getAbsolutePath());
   }
  }
 }
 public static void main(String[] args) {
  
  SearchFile serchObj = new SearchFile();
  //It will search for a jar file in C drive
  serchObj.searchFile("C:/",".*jar");
 }

}

Java : Read / Write excel (.xls) file

Lets see how we can create excel (.xls) file in Java. Below example show how to write a xls file.

Java Excel API is a mature, open source java API enabling developers to read, write, and modifiy Excel spreadsheets dynamically.

Lets look at a Simple Example, which can be used for reading, writing Excel (.xls) file, Even it's cell can be formatted according to our requirement.

To know more about Java Excel API Click here

In this example we will first create Excel file (Sample.xls) using writeXLSFile() method and then we will read same Excel file (Sample.xls) using readXLSFile() method

For Java Excel API Click here

To run below example you will need to Download jxl.jar file, Click here to download.

Assuming you have set jxl.jar in classpath, Lets see a simple self explanatory example.


Friday, April 27, 2012

Liferay : Target "depoly" does not exist in the project "my-greeting-portlet"

After creating a portlet, as mentioned in liferay documentation.While deploying it to tomcat, below mentioned error was seen.

Target "depoly" does not exist in the project "my-greeting-portlet"

Please see the commands below.

C:\liferay-plugins-sdk-6.0.5\portlets>create.bat my-greeting "My Greeting"
Buildfile: C:\liferay-plugins-sdk-6.0.5\portlets\build.xml

create:
    [unzip] Expanding: C:\liferay-plugins-sdk-6.0.5\portlets\portlet.zip into C:
\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet
    [mkdir] Created dir: C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portl
et\docroot\WEB-INF\tld
     [copy] Copying 6 files to C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting
-portlet\docroot\WEB-INF\tld

BUILD SUCCESSFUL
Total time: 4 seconds

C:\liferay-plugins-sdk-6.0.5\portlets>

While deploying using ant deploy command, below mentioned error was seen.

C:\liferay-plugins-sdk-6.0.5\portlets>cd my-greeting-portlet

C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet>ant deploy
Buildfile: C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet\build.xml

BUILD FAILED
Target "depoly" does not exist in the project "my-greeting-portlet".

C:\liferay-plugins-sdk-6.0.5\portlets\my-greeting-portlet>

Java : Simple AES Cryptography example

Advanced Encryption Standard (AES) is a specification for the encryption of electronic data. It has been adopted by the U.S. government and is now used worldwide. It supersedes DES.[3] The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data. (To know more click here).

To run this example you will need below mentioned JAR files in classpath.
  • jce.jar
  • rt.jar

If you are using JDK 6 or higher version, These JAR files are implicitly present. You can cross verify in JRE folder. Probably in "C:\Program Files\Java\jre6\lib"

Hence C:\Program Files\Java\jre6\lib\jce.jar and C:\Program Files\Java\jre6\lib\rt.jar are implicitly set in your classpath. Below is the sample self explanatory Java program using AES Cipher. Directly you can run the program and see output.

Simple AES Cipher Example in java

/* SimpleCryptography.java */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SimpleCryptography {
    
    private String AlgoName = "AES";
    
    private String keyString = "Desire_SecretKey";
    
    public String encrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        
        byte[] encrypted = cipher.doFinal(sValue.getBytes());
        
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        String enStr = bASE64Encoder.encodeBuffer(encrypted);    
        
        return enStr;
    }
    
    public String decrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        BASE64Decoder bASE64Decoder = new BASE64Decoder();
        byte decrytByt[] = bASE64Decoder.decodeBuffer(sValue);
        
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        
        byte decrypted[] = cipher.doFinal(decrytByt);
        
        String deStr = new String(decrypted).trim();
        
        return deStr;
    }
    
    public static void main(String[] args) throws Exception {
        
        SimpleCryptography obj = new SimpleCryptography();
        
        String password = "MadanChaudhary";
        
        System.out.println("password : "+password);
        
        String encrypted_password = obj.encrypt(password);
        
        System.out.println("encrypted_password : "+encrypted_password);
        
        String decrypted_password = obj.decrypt(encrypted_password);
        
        System.out.println("decrypted_password : "+decrypted_password);

    }
}

Wednesday, April 25, 2012

Java: Generate random numeric, alphabetic and alphanumeric numbers

In java many times you may require to generate random numbers. Random number could be numeric, alphabetic or both alphanumeric. Let’s see a java program which generates random numbers. You can also customize length of the number. Directly you can run the below codes and see the output no need to add any jar files.

About the example:

We have 3 methods randomAlphabetic(), randomNumeric() and randomAlphanumeric() which generates alphabetic, numeric and alphanumeric numbers respectively. Just provide the length of the number and see the output. Let’s see the self explanatory code.


/* RandomNumber.java */

import java.util.Random;

public class RandomNumber {

 private static final Random RANDOM = new Random();
 
 private String random(int length, boolean num,boolean alpha) {
  
  StringBuffer result = new StringBuffer();
  char c = 0;

  int min = 48;
  int max = 90;

  int i=0;

  while(i<length) {

   c = (char) (RANDOM.nextInt(max - min) + min);

   if((num && Character.isDigit(c)) || 
   (alpha && Character.isLetter(c)) || 
   (num && alpha && Character.isLetterOrDigit(c))) {
    result.append(c);
    i++;
   }
  }   
  return result.toString();  
 }
 
 //Function to generate only alphabetic numbers
 public String randomAlphabetic(int length) {
  
   return random(length,false,true);
  }
 
 //Function to generate only numeric numbers
  public String randomNumeric(int length) {
  
   return random(length,true,false);
  }
  
 //Function to generate alphanumeric numbers
  public String randomAlphanumeric(int length) {
   
   return random(length,true,true);
  }

 public static void main(String[] args) {

  RandomNumber obj = new RandomNumber();
  
  System.out.println(obj.randomAlphabetic(5));
  System.out.println(obj.randomNumeric(10));
  System.out.println(obj.randomAlphanumeric(15));

 }

}

Note : If you want to generate random unique numbers just add it to Set to make sure that all numbers are unique.