Archive for the 'Java' Category

JAVA: XMLGregorianCalendar Dates

Sunday, November 20th, 2011

I was updating some plugins for a project and came to a query for an e-mail program I was writing, I had to send out recently introduced defects to their respective owners and insure that they would only get the defects from the a given offset. It turned out that my API had a XMLGregorianCalendar argument. So I went out to look for a way to offset the date object so I could retrieve the correct information.

I used the following to convert my date:

package com.etechtips;

import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class UpdateDate {

	public static void main(String[] args) {
		XMLGregorianCalendar xgcstart;
		GregorianCalendar gc;
		int daycount = 0;
		if (args.length != 1)
		{
			System.out.println("Need to specify offset");
			System.exit(1);
		}

		daycount = Integer.parseInt(args[0]);

		// This will get the current date based on System time of an object
		gc = new GregorianCalendar();
		System.out.println("CURRENT:" + gc.toString());

		// This will offset the date by daycount days
		gc.add(Calendar.DATE, daycount);
		System.out.println("OFFSET: "+ gc.toString());

		try
		{
			// Now the XMLGregorianCalendar object has an
                        instance that is based on the time set in the gc object
			xgcstart = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
		}
		catch(DatatypeConfigurationException dce)
		{
			dce.printStackTrace();
			System.exit(1);
		}

		// Code omitted
	}
}

Output:

CURRENT:java.util.GregorianCalendar[time=1321793315934,areFieldsSet=true,areAllFieldsSet=true,\
lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,\
dstSavings=3600000,useDaylight=true,transitions=235,\
lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,\
useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,\
startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,\
endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2011,MONTH=10,\
WEEK_OF_YEAR=48,WEEK_OF_MONTH=4,DAY_OF_MONTH=20,DAY_OF_YEAR=324,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,\
AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,MILLISECOND=934,ZONE_OFFSET=-21600000,\
DST_OFFSET=0]
OFFSET: java.util.GregorianCalendar[time=1321706915934,areFieldsSet=true,areAllFieldsSet=true,\
lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,\
dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,\
offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,\
startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,\
endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,\
YEAR=2011,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=19,DAY_OF_YEAR=323,\
DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,\
MILLISECOND=934,ZONE_OFFSET=-21600000,DST_OFFSET=0]

The printouts above show the current date and the new date based on the offset. I made the day of the month bold in the printouts to show what the offset has updated the date. You could put a much larger offset than 1 and Calendar object will take care of updating the day of week, week of year and more. You will not need to deal with checking for leap year or dealing with updating all the month and years, this is all taken care of for you.

Tags: ,

Java: Command line argument processing

Sunday, November 6th, 2011

In each language that I have learned I have found it useful to know how to process command line arguments and here is a simple framework that I use for Java. I usually wrap the java command line in a bat or shell file to make it easier to run so that the user does not have to worry about classpath or path issues.

The following is the basic code to handle the command line arguments.

class CmdArgs
{

  public static void main(String[] args)
  {
      int argsize = args.length;
      String curarg;

      if (argsize > 0 )
      {

      }

      for(int i = 0; i < argsize; i++)
      {
          if (args[i].equals("--host")
          {
             args++;
             host = args[i];
           }
          else if (args[i].equals("--debug")
          {
               debug = 1;
          }
          else
          {
              System.out.println("Unknown option: " + args[i]);
              System.exit(1);
          }
       }

   }
}

The bat file for Dos/Windows might look like this:

@echo off

java -cp c:\javabin;somejar.jar  com.etechtips.CmdArgs %*

The shell based file might look like:


java -cp /home/ecdown/javabin:somejar.jar com.etechtips.CmdArgs $*

Tags: ,

Gallery of Hello World!

Thursday, August 4th, 2011

Here is a list of the Hello World Programs for different languages:

C

#include
int main()
{
printf("Hello World!");
}

C++

#include
int main()
{
cout << "Hello World!" << endl;
}

C#

public class HelloWorld
  public static void Main()
  {
    System.Console.WriteLine("Hello World!");
  }

Java

class HelloWorld {
static void main(String[] args)
{
System.out.println("Hello World!");
}

SHELL

echo "Hello World"

Python

print "Hello World!\n"

Ruby

puts "Hello World!"

Perl

print "Hello World!\n";

PHP

  <?php
    print "Hello World!";
  ?>

This is the simplest form of Hello World for most of these languages.

Tags: , , , , , , ,

Ant unable to find tools.jar

Saturday, January 29th, 2011

When attempting to run ant I get the following message: “Unable to locate tools.jar. Expected to find it in C:\Program Files (x86)\Java\jre6\lib\tools.jar”

This had to do with my JAVA_HOME not pointing to a Java JDK.

So if you download a JDK and update your JAVA_HOME environment variable to point to that directory, ant should run happily.

In BASH:
export JAVA_HOME=/path/to/jdk

IN DOS:
set JAVA_HOME=c:\PATH\to\jdk

Tags: ,

Java Exception java.lang.NoClassDefFoundError and how to resolve it

Wednesday, January 26th, 2011

I had recently reinstalled my system and was trying to run a simple class that consisted
of a “Hello World” program in Java. I received the following:

Compile:

$> javac LottoMain.java

Run:

$> java LottoMain

Exception in thread “main” java.lang.NoClassDefFoundError: LottoMain
Caused by: java.lang.ClassNotFoundException: LottoMain
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: LottoMain. Program will exit.

The compile line completed without errrors and the LottoMain.class file was there, but
what I didn’t know was that I no longer had the current directory “.” in my CLASSPATH variable.

After adding “.” to my CLASSPATH variable the run command gave me what I was expecting.

Run:

$> java LottoMain

Hello Eric!

Updating the CLASSPATH variable in Bash:
in my home directory/.bashrc file

export CLASSPATH=$CLASSPATH:.

Tags: ,

Java: Great link to Swing Examples

Friday, January 21st, 2011

Starting on my road to creating a Java based GUI I stumbled upon the following link within the “Creating a GUI with JFC/Swing” Train in the Java Tutorials from Oracle.

Using Swing Components: Examples

It has code examples and can really get you started on the road to a Java GUI interface.

Tags: , ,

Java: Creating a Window

Thursday, January 20th, 2011

This is the First of some basic articles about creating a GUI in Java. The following code is the basis of the following series of articles. I am using the Java Swing window toolkit.

import java.awt.*;
import java.swing.*;

class FirstWindow
{

  public static void main(String[] args)
  {
      //Create Window object and set title bar text
      JFrame frame = new frame("First Window");

      // Set the Default operation when you close the window
      // This exits the program on closing the window
      // The default behavior is to HIDE_ON_CLOSE
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Now we need to Display the window
      // The null argument will place the element in the center of the screen.
      frame.setLocationRelativeTo(null);
      frame.pack();
      frame.setVisible(true);
   }
}

This is enough to display a simple window, but it will probably not have any useful size associated with it and it does not do anything.

The next step will be to add some useful widgets and eventually functionality to make the window useful.

Helpful info:
Java: Great link to Swing Examples

Tags: ,

Passing JVM options to Maven

Wednesday, June 30th, 2010

If you are using maven to build your projects , then you might have found an out of memory condition in your tests.  Well, setting the MAVEN_OPTS variable with JVM specific options will help with this.

Example:

MAVEN_OPTS=-Xmx1024

Depending on what environment you are in, you will need to set this variable.

This will give the JVM more 1024 megs to work with and you can customize the number to fit your needs.

Java formatting a number with leading zeroes

Friday, July 17th, 2009

Recently, I had a Java project that needed to encode a set of numbers and I needed a fixed number of digits used for each number. I found the DecimalFormat class a good solution for my needs.

Here is a snippet of code to show a simple way to format a number with a fixed number of digits.

import java.text.DecimalFormat;

class TestEncoder
{
        public static void main(String[] args)
        {
                // This program expects one integer
                // argument and places it in the num1
                // variable. This program is not very
                // robust as to watch for no arguments
                // or to check if the argument is not
                // an integer.
                String num1 = args[0];
                String output;

                // This creates the Decimal Format instance
                // and assigns the formatting that we want
                // to use, in this case three characters .
                DecimalFormat dfmt =
                             new DecimalFormat("000");

                // This does the work of formatting the number
                // passed in on the command line to be at least
                // three digits.
                output = dfmt.format(new Integer(num1));

                // This just displays the results of the
                // dfmt.format(new Integer(num1)) command.
                System.out.println("Output: " + output);
}
}

The Decimal format allows for many more formatting options for numbers.

Make sure to look a the API docs for the version of Java that you are using:

http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html

Tags: ,