Monday, January 10, 2011

ResultSet to XML converter

Sometimes there is a need to convert a resultset into a xml file. The xml file can be shared across webservices.
I had a similar requirement but found no example online.
So I created this utility to convert resultsets into xml. The language of development is Java.
The code has provision to accept multiple resultsets. All the resultsets will be appended in the xml file.
The rows of tables can be indentified by row identifiers. Which is user supplied.

Understanding that the resultsets can be very large, I have used stax based parser to write the xml.
Amongst STAX based parsers, I have choosen WOODSTOX as my parser. Because it has very good performance ratings in various benchmark tests.
Details of Woodstox can be found here.

I have uploaded my source files in sourceforge. And can be found at the following location.

https://sourceforge.net/projects/rstoxmlwriter/

A typical usage might be:

  for (String tableName : tableNames) {
          String rowId = "row";
   String query = "Select "+selectClause+" from "+table+restrictions;
   ResultSet tableData = getResult(query);
   XmlElementInfo xmlElementInfo = new XmlElementInfo(tableData,
                        rowId.toUpperCase(),table.toUpperCase());
   xmlElementInfos.add(xmlElementInfo);
  }
  try {
   new XMLWriter().writeXML(xmlElementInfos,parentTag, outputLocation+xmlFileName);
  } catch (XMLWriterException e) {
   e.printStackTrace();
  }
  closeDB();






I would be happy, if anybody finds this useful. 
Also please put your comments. Let me know if there are any bugs. Let me know if there is any further enhancement requests.


Monday, February 22, 2010

Update Twitter status using this java code


import sun.misc.BASE64Encoder;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.net.URLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Twitter {

public static void main(String[] args) throws Exception {


URL url = new URL("https://twitter.com/statuses/update.xml");
URLConnection connection = url.openConnection();

String crendetials = "username" + ":" + "password";

BASE64Encoder encoder = new BASE64Encoder();

String encodedCredentials = new String(encoder.encodeBuffer(crendetials.getBytes())).trim();

connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("status=" + URLEncoder.encode("It was really simple to write simple status message updation code using Java. This message also goes thought my Java code. It's fun", "UTF-8"));
out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response;
while ((response = in.readLine()) != null) {
System.out.println(response);
}
in.close();
}

}

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