Tuesday, May 25, 2010

Determine the Next Month in Java

First, get an instance of the Calendar class:

Calendar cal = GregorianCalendar.getInstance();
Declare a format to be used:
SimpleDateFormat df = new SimpleDateFormat("MMM yyyy");

Set the Calendar's current time to today's Date:

cal.setTime(new Date());

Add a month to the Calendar's date:

cal.add(Calendar.MONTH, 1);

Format the new date into a string:

String nextMonth = df.format(cal.getTime());

The nextMonth String will contain the next month's value.

The following technique allows us to show 12 consecutive months:

cal.setTime(new Date());
for(int i=0; i<12;i++){
   cal.add(Calendar.MONTH, 1);
   String nextMonth = df.format(cal.getTime());
   System.out.println(nextMonth);
}


The Calendar class has a lot of other methods to set its date. For example, you can set the year and month as follows:

cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, 05);
or
cal.set(Calendar.MONTH, Calendar.JUNE);

This code sets the Calendar date to June 2010.

You can also set the date using year, month, and day arguments.

cal.set(2010, 05, 15);

This code sets the Calendar date to June 15, 2010.

Monday, May 24, 2010

Enumerate All Keys of a Hashtable


Set keys = myHashTable.keySet();
Iterator iter = keys.iterator();
while (iter.hasNext())
{
    Object key = iter.next();
    System.out.println("key:"+ (String)key);
}

A Simple Way to Find Data in XML Using dom4j

dom4j is a small but powerful package to parse XML documents. It has the advantage of having a very small footprint and being very easy to use. The dom4j website has a lot of examples that show how to use it.
If you have a simple xml file like the following one, I will show you how to use dom4j to find data.

<?xml version="1.0"?>
<students>
        <student>
                <name>Mike</name>
                <course>JSP</course>
        </student>
        <student>
                <name>Janet</name>
                <course>EJB</course>
        </student>
</students>

The file name is students.xml.
Suppose, you need to find the course for a student named Mike.
First, you need to parse a document:

public Document parse(String file) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);
    return document;
}

Document doc= parse("students.xml"); 

Then, use the following statement:
String course = doc.valueOf("//student[name='Mike']/course");  
This statement uses an XPath Engine library from Jaxen which means you need to have it in your classpath.
If you want to limit your library usage to dom4j proper you'll have to write your own method which may look like the following:

public String findStudentCourse(Document doc, String studentName) {
    Element root = doc.getRootElement();
    for (Iterator i = root.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.elementText("name").equals(studentName)) {
            return el.elementText("course");
        }
    }
    return null;
}
If you want to iterate through all the student elements and print the name-course combinations use the following example:

Element root = document.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();) {
    Element el = (Element) i.next();
    System.out.println("Child Element Path :" + el.getPath());
    System.out.println("    Name:" + el.elementText("name"));
    System.out.println("    Course:" + el.elementText("course"));
}

Convert Collection to Array

The following example converts an ArrayList into an array of strings:

    ArrayList al = new ArrayList();
    //Fill the array 
    ...........

    String[] aStrings = (String[]) al.toArray(new String[0]);

Find and Replace All Occurrencies of a String

Description:
You need to replace all occurencies of a string in a text file

Solution: (For Java 1.4 and higher) '

public static void readReplace(String fname, String oldPattern, String replPattern){
    String line;
    StringBuffer sb = new StringBuffer();
    try {
        FileInputStream fis = new FileInputStream(fname);
        BufferedReader reader=new BufferedReader ( new InputStreamReader(fis));
        while((line = reader.readLine()) != null) {
            line = line.replaceAll(oldPattern, replPattern);
            sb.append(line+"\n");
        }
        reader.close();
        BufferedWriter out=new BufferedWriter ( new FileWriter(fname));
        out.write(sb.toString());
        out.close();
    }
    catch (Throwable e) {
                System.err.println("*** exception ***");
    }
}

Transfer data from Excel to Access through Java

This is sample code that shows how to use Java to transfer data from Excel spreadsheets to Access. The basic idea is to create an ODBC data source for both Excel and Access. Then use the JDBC API to retrieve records from the Excel ODBC source and insert them to Access.
The Excel ODBC source is represented by "jdbc:odbc:BulkMail", and the Access ODBC source is represented by "jdbc:odbc:Whisky" in the code.


import java.sql.*;
public class ExcelToAccess {
public static void main (String[] args)
{
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = "jdbc:odbc:BulkMail";
String sourceAccess = "jdbc:odbc:Whisky";
Connection dbConnection = DriverManager.getConnection(sourceURL);
Connection dbAccess = DriverManager.getConnection(sourceAccess);
String comp;
String fax;
Statement st = dbConnection.createStatement();
Statement stAccess = dbAccess.createStatement();
ResultSet rs = st.executeQuery("Select LastName, FirstName, Company, FaxNumber from Customers");
while (rs.next()){
    comp = rs.getString ("Company");
    fax = rs.getString ("FaxNumber");
    stAccess.executeUpdate("INSERT INTO Company (CompanyName, FaxNumber) VALUES('" 
+ comp + "','" + fax + "')");
}
rs.close();
dbConnection.close();
dbConnection =null;
dbAccess.close();
dbAccess = null;
}
catch(SQLException sqle)
{ System.err.println(sqle); }
catch(ClassNotFoundException cnfe)
{ System.err.println(cnfe); }
}

}