Date, TimeZone, Calendar – converter in Java

April 5, 2010 Leave a comment

have enough wasted working with java.util.Time(Sun named it as java.util.Date), and SimpleDateFormat(UnSpecifiedTimeZoneAndByDefaultJVMTimeZone).

Whenever dealing with Date object remember that your working with time. If you need to pass different timezones of date then it is named as Calendar in java. So pass Calendar and not date. That is what I learn after struggling with it for hours.

<pre>
package com.nikias.calendar;

import java.util.Calendar;
import java.util.TimeZone;

/*
 * Helps to print current time in GMT, local JVM, Indian Time, Singapore Time, New-york Time
 *
 * America/New_York
 * Asia/Calcutta
 * Asia/Singapore
 * GMT
 *
 */
public class TimeZoneConverter {

 public TimeZoneConverter() {
 }

 public static void main(String[] args) {
 TimeZoneConverter converter = new TimeZoneConverter();
 String[] timeZones = new String[] { "Asia/Calcutta", "America/New_York", "Asia/Singapore", "GMT" };

 for (String tz : timeZones) {
 System.out.printf(tz + " --    %tc\n", converter.fromGMT(Calendar.getInstance(), tz));
 }
 }

 public Calendar fromGMT(Calendar sourceTime, String targetZone) {
 return fromGMT(sourceTime, TimeZone.getTimeZone(targetZone));
 }

 public Calendar fromGMT(Calendar sourceTime, TimeZone targetZone) {
 Calendar target = Calendar.getInstance(targetZone);
 target.setTime(sourceTime.getTime());
 return target;
 }
}

Below is the unit testcase to prove them

package com.nikias.calendar;

import java.util.Calendar;
import java.util.TimeZone;

import junit.framework.Assert;

import org.junit.Test;

public class TimeZoneConverterTest {

	// Sunday, January 31st, 8:00AM

	long day = 24 * 60 * 60 * 1000;
	long year = (long) day * 366;
	long time = (long) year * (2010 - 1970);
	long dsttime = (long) year * (2010 - 1970) + 93*day;
	long dsttime2 = (long) year * (2010 - 1970) + 90*day;

	@Test
	public void testSingaporeTime() {
		TimeZone tzSNG = TimeZone.getTimeZone("Asia/Singapore");
		TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
		Calendar calendarSNG = Calendar.getInstance(tzSNG);
		calendarSNG.setTimeInMillis(time);
		Calendar calendarNY = Calendar.getInstance(tzNY);
		calendarNY.setTimeInMillis(time);

		Assert.assertEquals(calendarNY.get(Calendar.YEAR), calendarSNG.get(Calendar.YEAR));
		Assert.assertEquals(calendarNY.get(Calendar.MONTH), calendarSNG.get(Calendar.MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.DAY_OF_MONTH) + 1, calendarSNG.get(Calendar.DAY_OF_MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.HOUR_OF_DAY) , calendarSNG.get(Calendar.HOUR_OF_DAY)+ 11);
	}

	@Test
	public void testDSTAndSingaporeTime() {
		TimeZone tzSNG = TimeZone.getTimeZone("Asia/Singapore");
		TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
		Calendar calendarSNG = Calendar.getInstance(tzSNG);
		calendarSNG.setTimeInMillis(dsttime);
		Calendar calendarNY = Calendar.getInstance(tzNY);
		calendarNY.setTimeInMillis(dsttime);

		Assert.assertEquals(calendarNY.get(Calendar.YEAR), calendarSNG.get(Calendar.YEAR));
		Assert.assertEquals(calendarNY.get(Calendar.MONTH), calendarSNG.get(Calendar.MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.DAY_OF_MONTH) + 1, calendarSNG.get(Calendar.DAY_OF_MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.HOUR_OF_DAY) , calendarSNG.get(Calendar.HOUR_OF_DAY)+ 12);
	}
	
	@Test
	public void testDSTAndSingaporeTimeAndEndOfMonth() {
		TimeZone tzSNG = TimeZone.getTimeZone("Asia/Singapore");
		TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
		Calendar calendarSNG = Calendar.getInstance(tzSNG);
		calendarSNG.setTimeInMillis(dsttime2);
		Calendar calendarNY = Calendar.getInstance(tzNY);
		calendarNY.setTimeInMillis(dsttime2);

		Assert.assertEquals(calendarNY.get(Calendar.YEAR), calendarSNG.get(Calendar.YEAR));
		Assert.assertEquals(calendarNY.get(Calendar.MONTH) + 1, calendarSNG.get(Calendar.MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.DAY_OF_MONTH)-29, calendarSNG.get(Calendar.DAY_OF_MONTH));
		Assert.assertEquals(calendarNY.get(Calendar.HOUR_OF_DAY) , calendarSNG.get(Calendar.HOUR_OF_DAY)+ 12);
	}	

	
}
Advertisements
Categories: Uncategorized

Programming building blocks with real world object comparison

March 13, 2010 1 comment

Nowadays I try to compare programming building blocks with real world objects. Especially interface is my special interest.

Finally I am able to compare interface with real world thing.

When I was walking close to ShengSiong shop in Singapore, I came across a person lifting 100’s of cases of Coke using pallet and jack. Here lift can handle weight, but doesn’t know what shape it is? Pallet knows that it will be lifted, so it gives place holder for other things to stack upon it. Coke cases are flat, and don’t know anything about transportation.

Pallete

The magic is when lift seamlessly plugs itself into pallet, and on top of pallet it could be anything. Imagine if you work as an employee in shopping mall without lift, pallet and customer :).

When I asked the same question to Hanspeter, he explained using screw and bolt-nut. As long as they have the same size, bolt nut can fit to any screw. When screw hole in any machine matches, any bolt nut and screw can be used to fit them.

He also shared that he imagines programming problems as some model in his mind. Sometime it takes time, but will help to give strategic (clean, perfect) solution. But sometime problems can’t wait, so it reaches a person who solves it somehow (tactical), may not be clean solution.

And today, I want to pour a glass of lemon tea from a glass tumble to another to filter it. Unfortunately, I don’t have second tumbler. Imagine, how if recursion is possible in real world, so I could pour tea into the same tumbler, in between I can also filter them 🙂

Categories: Uncategorized

Find jar file location of a class [Fastest way]

March 11, 2010 Leave a comment

If you have folder which has all jar, then following command is quicker way to find your jar file of anyclass.

java -verbose:class -classpath $(echo *.jar | sed ‘s/ /:/g’)  com.anything.yourclass | grep “yourclass”

Categories: Uncategorized

Unzip failure

January 19, 2010 Leave a comment

skipping file:  unable to create a sensible filename out of C:\DevTools\spring-framework-3.0.0.RELEASE-with-docs\spring-framework-3.0.0.RELEASE\projects\org.springframework.test\src\test\java\org\springframework\test\context\configuration\ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties
Error:  The system cannot find the path specified.
Cannot create C:\DevTools\spring-framework-3.0.0.RELEASE-with-docs\spring-framework-3.0.0.RELEASE\projects\org.springframework.test\src\test\java\org\springframework\test\context\configuration\ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java

Categories: Uncategorized

Scala [Some Option None]

November 1, 2009 Leave a comment

I personally think to work with LiftWeb framework basic Scala  knowledge is very important. Till today I really struggle to understand some pieces of code in LiftWeb.

For a change, I would like to write blog about few important classes of Scala and LiftWeb while I learn about them.

Classes which I would like to cover them are Option, Some, None, Full and Box. Last two classes are available in LiftWebCommon.

scala> val i = Some(5)
i: Some[Int] = Some(5)

Observation is Some container, it can hold any other type.

scala> None
res34: None.type = None

None is Singleton object.

scala> Option
res36: Option.type = scala.Option$@f3b83

Option is again Singleton object

scala> var t = Option
t: object Option = scala.Option$@f3b83

scala> t.getClass().getMethods().map(println(_))
public int scala.Option$.$tag() throws java.rmi.RemoteException
public scala.Iterable scala.Option$.option2Iterable(scala.Option)
…………………….(java.lang.Object.methods)
public final native void java.lang.Object.notifyAll()
res38: Array[Unit] = Array((), (), (), (), (), (), (), (), (), (), ())

Here are my observation, Option is a container, which holds some other value. None is special type of Option, which is Singleton, which represents Container which has no value, kind of null in Java.

Some is again special type of Option, which holds value. Option also is a singleton object, which has a utility method called option2Iterable.

They are heavily used when pattern matching is applied. It makes code more elegant. In simple, wherever y0u use null check in Java, you have to consider using above type of classes by encapsulating actual result using Some or None, and comparing with Some(x) or None.

Let us consider the following method, whenever we invoke rollDice method, either it may return Integer value or unexpected value called None. Wherever we need to check if it could be zero, we can just compare it with None.

scala> def rollDice:Option[Int]  = {
|   Some(Math.random*6 toInt) match {
| case Some(0)=>return None
| case Some(x)=> return Some(x)
|   }
| }
rollDice: Option[Int]

scala> rollDice
res13: Option[Int] = Some(3)

scala> rollDice
res17: Option[Int] = None

Let us write some piece of code which invokes the rollDice method.

rollDice match {
case None        => println(“Failed Roll”);
case Some(x)     => println(“I have got the valid value :”  + x);
}

If you observe the other method, which is not comparing either zero or null, rather it compares with None.

Some Scala utility methods which I am using for learning

scala> def printMethods(x:String):Unit = {
|                   Class.forName(x).getMethods().map(println(_))
| }
printMethods: (String)Unit

The above is used to find few methods available in classes, I may not use them in this blog.

Let us continue remaining in next blog…

Categories: Uncategorized

HashCode and Equals

October 27, 2009 Leave a comment

HashCode, HashSet, HashTable,  java.lang.Object.equals(), java.lang.Object.hashCode() – are related to each other

Below is a sample code to prove that.

findSize() is a method, which accept class whose constructor accepts an Integer. This method will create 5 object and push into HashSet, finally will print Set’s size. It should be 5, if all each object is unique. Output should be 1, if all are having same content.

Case – One (If hashCode is equal, doesn’t mean objects are equal)

I have Customer object, regardless of content, it’s hashCode will remain same. When executing findSize method with Cusomer.class as argument, Set contains 5 unique object.

It proves that even if content and hashCode is equal, hashSet can’t understand unless we override equals method.

Case – Two (If hashCode is unique, doesn’t mean objects are unique)

I have Customer2 object, whose hashCode was not overriden, hence it would be unique (provided by JVM). Its equals method is overriden. When two Customer2 object has same name, they are considered equal.

But when invoking findSize, even Customer2 will have same effect as Case-One.  so even if we override equals without overriding hashCode, They are considered as 5 different Object as their hasCode is unique.

Case – Three (If you override equals, override hashCode )

Now we have Customer3 object, whose hashCode,equals methods have overridden.  Here when invoking findSize with argument as Customer3.class, now it recognize that all the Objects are same.

Case – Four (Object hashCode, and its Clone hashCode will not match)

I have a method, which creates Customer4 object, it clones it and checks if original and cloned objects are equal, But output was false. This ensures that Cloned object will not contain same hashCode as its original.

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashSet;

public class HashTest {
public static void main(String args[]) throws InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, NoSuchMethodException,
InvocationTargetException {
findSize(Customer.class);
findSize(Customer2.class);
findSize(Customer3.class);
findSize2(Customer3.class);
proveHashcodeIsUnique();
}

private static void findSize(Class<? extends Obj> clazz) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InvocationTargetException {
HashSet<? super Obj> set = (HashSet<? super Obj>) new HashSet(5);
for (int i = 0; i < 5; i++) {
Constructor<Obj> constructor = (Constructor<Obj>) clazz.getConstructor(Integer.class);
set.add(constructor.newInstance(Arrays.asList(1).toArray()));
}
System.out.println(set.size());
}

private static void findSize2(Class<? extends Obj> clazz) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InvocationTargetException {
HashSet<? super Obj> set = (HashSet<? super Obj>) new HashSet(5);
for (int i = 0; i < 5; i++) {
Constructor<Obj> constructor = (Constructor<Obj>) clazz.getConstructor(Integer.class);
set.add(constructor.newInstance(Arrays.asList(i).toArray()));
}
System.out.println(set.size());
}

private static void proveHashcodeIsUnique() {
Customer4 cus1 = new Customer4(1);
Customer4 cus2 = cus1.clone();
System.out.println(cus1.hashCode() == cus2.hashCode());
}

}

interface Obj {
}

class Customer implements Obj {
private String name;

public Customer(Integer i) {
name = i + "";
}

@Override
public int hashCode() {
return 17;
}
}

class Customer2 implements Obj {
private String name;

public Customer2(Integer i) {
name = i + "";
}

public boolean equals(Object other) {
Customer2 c1 = (Customer2) other;
return c1.name.equals(this.name);
}

}

class Customer3 implements Obj {
private String name;

public Customer3(Integer i) {
name = i + "";
}

public boolean equals(Object other) {
Customer3 c1 = (Customer3) other;
return c1.name.equals(this.name);
}

public int hashCode() {
return name.hashCode();
}

}

class Customer4 implements Cloneable, Obj {
private String name;

public Customer4(Integer i) {
name = i + "";
}

public boolean equals(Object other) {
Customer4 c1 = (Customer4) other;
return c1.name.equals(this.name);
}

@Override
public Customer4 clone() {
Customer4 result = null;
try {
result = (Customer4) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return result;
}
}
Categories: Uncategorized

How to back-up Geocities pages?

October 19, 2009 Leave a comment

Within another 7 days, decade old Geocities pages will not be accessible. If you are one among me, who has 100’s of page, and require to download them. Here there are option

1) use Win-HttpTrack to backup

2) Use FireFox and login into Geocities account and using Downthem all plguin, you can download all your pages.

2.1) Go to FileManager after you login into account.

2.2) Once you see all the files in your account, using downthem all use the reg-ex like (/accountname/(.*)$/).. and download your files

Mohan

Categories: Uncategorized