Wednesday, December 30, 2009

Java String array - Single and Multidimensional

In java arrays can be single as well as multi dimentional. This is true not only for Strings, but also for int, double, char etc all datatypes.
Arrays can be declared in two ways. Today i will show you how to declare arrays in Java.
This post will cover both the ways array can be declared and also how to access the elements.
Please comment if this post helps you or if there is something I missed.
Happy Coding.

Lets start with Single Dimension Arrays:





 String [] OneDArray1 = new String[10];
  OneDArray1[0] = "1";
  OneDArray1[2] = "2";
  OneDArray1[5] = "3";

  for(int i=0;i
   System.out.println(OneDArray1[i]);
  }
  
Output of this code snippet:

 1
 null
 2
 null
 null
 3
 null
 null
 null
 null



Another way of declaring single dimension arrays:


 String [] OneDArray2 = {"1","2","3"};
  
  for(int i=0;i
   System.out.println(OneDArray2[i]);
  }
  
Output of this code snippet:

 1
 2 
 3
 

Multi Dimensional Arrays


  String TwoDArray1[][] = new String[2][3];
  
  TwoDArray1[0][0] = "1";
  TwoDArray1[0][1] = "2";
  TwoDArray1[0][2] = "3";
  
  TwoDArray1[1][0] = "4";
  TwoDArray1[1][1] = "5";
  TwoDArray1[1][2] = "6";
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray1[i][j]);
   }
  }

Output of this code snippet:

 1
 2
 3
 4
 5
 6
 

Another way of declaring multi dimensional arrays:


 String TwoDArray2[][] = { {"1","2"},{"3","4"} };
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray2[i][j]);
   }
  }
 
Output of this code snippet:
 1
 2
 3
 4



Friday, December 18, 2009

Java find longest matching part or substring of string

Finding largest common sub string from an array of strings is often very useful. Recently I had this requirement, where I was trying to exclude a list of strings by using regex patterns. For this I had to find the greatest matching substring among the strings, so that I put that substring as a regex, and save a lot of effort.
Unfortunately I didn't find any ready made code on the net, that does the same thing. So I wrote my own.

I tried to make the logic as optimum as possible.
If anyone has a better algorithm in mind, please share it with me.

I have used a custom string length comparator, so optimise the string traversing. Readers can write their own implementation of the comparator, or copy my custom string length comparator class from here.



 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;

 public class SubString {

  public static void main(String[] args) {
    String [] strs = {
     "this is a very big first string which should be processed at last",
     "this is a very small string" ,
     "this is a very boring string nothing special",
     "this is a very simple yet bigger string, second large"
    };

   //Arrays.sort(strs, new CustomStringLengthComparator());
   String sub = strs[0];
   Map subStrings = new HashMap();
   int j=strs[0].length();

   String comparingString =strs[1];
   while (j>=0) {
    for(int i=0;i< j;i++) {
     sub = strs[0].substring(i, j);
     if (comparingString.contains(sub)) {
      subStrings.put(sub.length(),sub);
     }
    }
    j--;
   }
   boolean flag =false;
   if(!subStrings.isEmpty()) {
    Set set = subStrings.keySet();
    TreeSet treeSet = new TreeSet(set);     
    String matchedString = subStrings.get(treeSet.last());   
    for(int k=2;k
     if (strs[k].contains(matchedString)) {
      flag=true;     
     }else {
      flag=false;     
      break;     
     }   
    }     
    if (flag) { 
     System.out.println("Matched : " + subStrings.get(treeSet.last()));
    }else {       
     System.out.println("No Match");     
    }   
   } 
  } 
 }

Custom String Length Comparator Java

The default sort method for strings is Java is it's character values. For example, If we have a string array:



String [] strs = {"abc", "xyz", "mnop123"};
And we use Arrays.sort(strs), the output will be in the following order:


abc
mnop123
xyz
But there are times, when we want to sort strings, by their length. The following custom string length comparator will serve the purpose:


import java.util.Comparator;

public class CustomStringLengthComparator implements Comparator{

 public int compare(String o1, String o2) {
  if (o1.length() < o2.length()) {
        return -1;
      } else if (o1.length() > o2.length()) {
        return 1;
      } else {
        return 0;
      }
 }

}


Instead of using


Arrays.sort(strs)
we have to use


Arrays.sort(strs, new CustomStringLengthComparator());



Wednesday, December 9, 2009

Currency format

As we know the way of formatting currency are different in many country. Main there is a big difference in European and British way. This code snippet converts the currency to appropriate formats and also does the reverse parsing.



 
public static void main(String args[]){
  // Format
     Locale locale = Locale.FRANCE;
     String string1 = NumberFormat.getCurrencyInstance(locale).format(123456789.12);
     System.out.println(string1);
    
     locale = Locale.US;
     String string = NumberFormat.getCurrencyInstance(locale).format(123456789.12);
     System.out.println(string);
    
     // Parse
     try {
         Number number = NumberFormat.getCurrencyInstance(locale).parse(string1);
         System.out.println(number.toString());
         number = NumberFormat.getCurrencyInstance(locale).parse(string);
         System.out.println(number.toString());
     } catch (ParseException e) {
     }
 }
 
 

List The Contents of a ZIP File

This is a utility program to view the contents of a zip file


import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 *
 * @author Rakesh P
 * ZipFile Function Accept the Path of the Zip File 
 */
public class ZipContents{
   
    public void listContentsOfZipFile() {
       
        try {
            ZipFile zipFile = new ZipFile("d:/FeedtoInterfaces.zip");
           
            Enumeration zipEntries = zipFile.entries();
           
            while (zipEntries.hasMoreElements()) {
               
                //Process the name, here we just print it out
                System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
               
            }
           
        } catch (IOException ex) {
            ex.printStackTrace();
        }
       
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        new  ZipContents().listContentsOfZipFile();
       
    }
}

Sunday, October 25, 2009

Java Swing Example: Image dimension from url

This code can be used to get the dimension of any image using its url. Minor tweaks can be made to get localized image dimensions too.Hope this helps.


import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;

public class ImageDimensions extends JFrame {
 
 protected static Toolkit tool = Toolkit.getDefaultToolkit();
 
 public ImageDimensions() {
 }

 protected void calculateHeightWidth()
   throws InterruptedException {
  Image image = null;
  try {
   image = tool.createImage(new URL("Image URL"));
   
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }catch(Exception e1){
   e1.printStackTrace();
  }
  
  MediaTracker mTracker = new MediaTracker(this);
  mTracker.addImage(image, 1);
  int i = 0;
  do {
   mTracker.waitForID(1);
   //added counter and break for the 404 or bad url 
   i++;
   if (i==5) break;
  } while (mTracker.statusID(1, true) != MediaTracker.COMPLETE);

System.out.println(image.getHeight(null));
System.out.println(image.getWidth(null));
 }
 
 public static void main(String[] args) {
 try {
  new ImageDimensions().calculateHeightWidth();
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } 
 }
 
}





Wednesday, October 21, 2009

Date to calendar,date utils... a simple example

Sometimes in you application you will require the calendar logic. In java the Date class methods are mostly deprecated and usage of Calendar class is encouraged. This utility class will do the operations using the Calendar api. This also can be use as Date to calendar converter or calendar to date converter. The methods are synchronized, so are threadsafe. I didn't make the calendar static, you can do that is required.


import java.util.Calendar;
import java.util.Date;

/**
 * This class will operate as a calendar. First set a date.
 * Then change the day,month or year as require. 
 * Then get the date back. There is also a feature of getting the current date, if needed,
 * which you can set as the base date again and do operations. 
 * Only date operations are permitted. 
 * Add logic, if you want the time related operations too.
 */
public class CustomCalendar {

private Calendar date;
private static final int BASEYEAR = 1900;
//Set the date before operation. Converts date to calendar for easier operation
public CustomCalendar(Date date) {
 super();
  this.date = Calendar.getInstance();
  this.date.setTime(date);
}

public CustomCalendar(Calendar date) {
 super();
 this.date = date;
}

//sets the prev year relative to the date already set(In constructor).
public  synchronized void prevYear() {
 int year = date.get(Calendar.YEAR)-BASEYEAR;
 date.set(Calendar.YEAR, year + BASEYEAR - 1);
}

//sets the next year relative to the date already set(In constructor).
public synchronized void nextYear() {
 int year = date.get(Calendar.YEAR)-BASEYEAR;
 date.set(Calendar.YEAR, year + BASEYEAR + 1);
}

//sets the prev month relative to the date already set(In constructor).
public synchronized void prevMon() {
int month = date.get(Calendar.MONTH);
date.set(Calendar.MONTH, month - 1);
}

//sets the next month relative to the date already set(In constructor).
public synchronized void nextMon() {
 int month = date.get(Calendar.MONTH);
 date.set(Calendar.MONTH, month + 1);
}

//sets the prev day relative to the date already set(In constructor).
public synchronized void prevDay() {
 int day = date.get(Calendar.DAY_OF_MONTH);
 date.set(Calendar.DAY_OF_MONTH, day - 1);
}

//sets the next day relative to the date already set(In constructor).
public synchronized void nextDay() {
 int day = date.get(Calendar.DAY_OF_MONTH);
 date.set(Calendar.DAY_OF_MONTH, day + 1);
}

//sets the current system date, in case it is needed.
public static synchronized Date currentSystemDate() {
 return new Date();
}

//returns the date, after all the year,month,day operation.
public  synchronized Date getDate() {
 return date.getTime();
}
}

Tuesday, October 13, 2009

Log4j Custom Performance Logger.

If you are a java coder, logging is indispensable part of your life. Often in your life you may have been in a situation, where you need a special purpose logging.

For example performance logging. If you have performance bottleneck in your application and if you suspect a few classes to be the culprit (or methods for that matter), then you may need a separate logger, that will log the performance of those classes. It will be in addition to the existing logging you have in your application.

Performance logging is just an example, but in these special situations, you feel the need of a custom logger.

Writing a custom logger is very simple, yet very helpful.

I a hereby giving the example of a performance logger. It will note the START time, END time and the time difference in the form of a CSV. As you dont want this to mess with your main application logs, you will need a separate log appender for this(TimingStats in this example).

Though it talks about performance logging, this code snippet can be modified to implement any kind of custom logger.

PerformanceLogger.java

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class PerformanceLogger {
 
 
 private static Logger logger = Logger.getLogger(PerformanceLogger.class);
 String methodName; 
 long startTime;
 long endTime;
 
 public PerformanceLogger() {
  super();
  logger.setLevel(Level.ERROR);
 }
 public PerformanceLogger(Level level) {
  super();
  
  logger.setLevel(level);
 }
public static boolean debug(){
 return logger.getLevel()==Level.DEBUG?true:false;
}

 public void writeTime(String operation){
  logger.debug(operation);
 }
 public void startMethod(String methodName){
  this.methodName = methodName;
  startTime = System.currentTimeMillis();
  writeTime(methodName+":START: ,"+startTime+", milliseconds");
 }
 public void endMethod(String methodName) {
  this.methodName = methodName;
  endTime = System.currentTimeMillis();
  writeTime(methodName+":END: ,"+endTime+", milliseconds");
  writeTime(methodName+":TIME TAKEN: ,"+((endTime-startTime)/1000)+", seconds");
 }
 
}

log4j.xml

<appender name="Your_Default_appender" />
    <!-- this appender will be used by performance logger class -->
 <appender name="TimingStats" class="org.apache.log4j.RollingFileAppender"> 
    <param name="File" value="./logs/TimingStats.csv"/> 
    <param name="Append" value="false" />
    <param name="MaxFileSize" value="10MB"/>
    <param name="MaxBackupIndex" value="1"/>
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%d , [%t] , %x , %-5p , (%F) , %m%n"/> 
    </layout> 
   </appender>
 
 
 <!-- All your loggin levels for classes would be here. -->
 
 <logger name="some class" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="Your_Default_appender" />
  </logger>

<!-- There will be a special declaration of the PerformanceLogger class. Note that it is not using the default appender. -->
  <logger name="PerformanceLogger" additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="TimingStats" />
  </logger>

Put the following lines in the class you want to log the performance.

private static PerformanceLogger log = new PerformanceLogger(Level.DEBUG);

You can use a singleton pattern if you want. But that is another topic.

At the start of any methos put
log.startMethod(methodName);

At the end of any method put
log.endMethod(methodName)


That should serve your purpose. If you see any issue with my code, please comment and help me improve

Monday, October 12, 2009

Setting up a cron job in unix/linux

What is CRON?
Cron is a time-based job scheduler in Unix-like computer operating systems. 'cron' is short for Chronograph. It is a long running process that enables users to schedule jobs (commands or shell scripts) to run automatically at a certain time or date. 

What are the common uses?
It is commonly used to perform system maintenance or administration. Though it can be used for all other practical purposes

What is CRONTAB?
Cron is driven by a crontab, a configuration file that specifies shell commands to run periodically on a given schedule.
crontab -e (Edit your crontab file).
crontab -l Show your crontab file.
crontab -r Remove your crontab file.
MAILTO=user@domain.com Emails the output to the specified address.

Each entry in a crontab file consists of six fields:

minute(s) hour(s) day(s) month(s) weekday(s) command(s)

The fields can be separated by spaces or tabs.

Field  Value  Description 
minute(0-59) - The exact minute that the command sequence executes.
hour(0-23) - The hour of the day that the command sequence executes.
day(1-31) - The day of the month that the command sequence executes.
month(1-12) - The month of the year that the command sequence executes.
weekday(0-6) - The day of the week that the command sequence executes. Sunday=0, Monday = 1 and so on.

Example: Print "Hello" after every hour

Sample cron job command:-  * 1 * * * echo "Hello"
Sample cron job script:-  * 1 * * * whatever_you_want.sh

Steps to setup the above cron job:-
  1. In you unix prompt fire "crontab -e" . It will open the crontab file in the default editor (Most commonly vi editor)
  2. Press "i" to change the mode to INSERT.
  3. At the end of the file, type in the above sample command and/or script.
  4. Wait for the stipulated time mentioned in the cronjob and then check your mail, you should be able to see the output (if any) there.

Happy Scheduling




Friday, October 9, 2009

Date and Big Decimal utilities

Problem Description

We need various small utilities regardign numbers and dates.
This code snippet has included some of the common conversions for convenience.



Solution Description

There are two separate classes "DateUtils" and "NumberUtils". MyMain class shows the usage.



Code Snippet


NumberUtils.java



import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


public class NumberUtils {

    /**
     * Method takes Object as parameter and returns decimal number.
     * if argument is float or double and contains tailing zeros
     * it removes them. If argument is float or double then no change in return type.
     * Change the Format of the Number by changing the String Pattern
     */
    public static String changeToDecimalFormat(Object number) {

        BigDecimal bdNumber = new BigDecimal(number.toString());
        bdNumber = bdNumber.stripTrailingZeros();           //Returns a BigDecimal with any trailing zero's removed
        String pattern = "###,##0.0###########";        //To apply formatting when the number of digits in input equals the pattern
        DecimalFormat newFormat = new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.US));
        return newFormat.format(bdNumber);

    }

    /* Method takes Object as parameter and removes commas from the parameter */
    public static double removeCommasFromNumber(Object number) {
        try {
            StringBuffer inputNo = new StringBuffer(number.toString());
            if (inputNo.length() > 0) {
                while (inputNo.indexOf(",") != -1) {
                    inputNo.deleteCharAt(inputNo.indexOf(","));
                }
            } else {
                return 0.0;
            }
            return Double.parseDouble(inputNo.toString());

        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    /* Some times its required to have a fixed set of decimal places for a
     * number. We can set that by changing the precision number for a particular
     * input BigDecimal Input String
     */
    public static String changeToRequiredDecimals(String bigDecimalString,
            int precision) {
        String newFormattedString = null;
        String afterDecimal = null;
        if (bigDecimalString == null || bigDecimalString.length() == 0) {
            return "0.0";
        }
        if (bigDecimalString.contains(".")) {
            afterDecimal = bigDecimalString.substring(bigDecimalString
                    .indexOf(".") + 1);
            int length = Math.abs((afterDecimal.length() - precision));
            if (afterDecimal.length() < precision) {
                newFormattedString = bigDecimalString;
                for (int i = 0; i < length; i++) {
                    newFormattedString = newFormattedString + "0";
                }
            } else if (afterDecimal.length() > precision) {
                newFormattedString = bigDecimalString.substring(0,
                        bigDecimalString.length() - length);
                if (precision == 0) {
                    newFormattedString = newFormattedString.substring(0,
                            newFormattedString.indexOf("."));
                } else {
                    newFormattedString = bigDecimalString;
                }

            } else {
                    if (precision > 0)
                        newFormattedString = bigDecimalString + ".";
                    else
                        newFormattedString = bigDecimalString;
                    for (int i = 0; i < precision; i++) {
                        newFormattedString = newFormattedString + "0";
                    }
            }
        }
        return newFormattedString;
    }

}


DateUtils.java



import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class DateUtils {

    public static Date getNthFromCurrentDate(int field, int nValue) {
        Calendar current = Calendar.getInstance();
        current.setLenient(true);
        current.add(field, nValue);
        return current.getTime();
    }
   
    public static Date convertStringToDate(String dateString, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }
    public static Date convertStringToTimestamp(String dateString, String pattern) {
        return new Timestamp(convertStringToDate(dateString, pattern).getTime());
    }
}


MyMain.java



import java.math.BigDecimal;


/**
 *
 */
public class MyMain {

    /**
     *Method
     * @param args
     */
    public static void main(String[] args) {

       
        System.out.println(DateUtils.convertStringToDate("11.10.2010", "dd.MM.yyyy"));
        System.out.println(DateUtils.convertStringToTimestamp("11.10.2010", "dd.MM.yyyy"));
        System.out.println(DateUtils.getNthFromCurrentDate(1,2));
       
        int intVar = 10;
        double doubleVar = 10.504000;
        float floatVar = 343534534348.5687654F;
        String commaString = "343,534,535,000.0";
        BigDecimal bdNumber = new BigDecimal("1234.8765");
       
       
        System.out.println(NumberUtils.changeToDecimalFormat(new Integer(intVar)));
        System.out.println(NumberUtils.changeToDecimalFormat(new Double(doubleVar)));
        System.out.println(NumberUtils.changeToDecimalFormat(new Float(floatVar)));
       
        System.out.println(NumberUtils.removeCommasFromNumber(commaString));
       
        System.out.println(NumberUtils.changeToRequiredDecimals(bdNumber.toString(), 8));

    }


}