Friday, May 30, 2008

GWT 1.5 M2

Eclipse Members Order

This is not strictly a "Best Practice" topic, but since it is very important to keep code uniform on the project with multiple developers I require that every one Formats and Orders Java classes this way:

Wednesday, May 28, 2008

MyEclipse Memory

To modify memory for myEclipse go to:

Windows --> Preferences --> Edit --> Default VM argument
-Xms128m -Xmx256m -XX:PermSize=128m -XX:MaxPermSize=512m -Dfile.encoding=UTF-8

Tuesday, May 27, 2008

Daily Trigger

Trigger trigger = TriggerUtils.makeDailyTrigger(22, 02);

Friday, May 23, 2008

GWT: running tests filtered by Maven 2

<target name="war" depends="clean">
<echo>Maven Executable: ${MAVEN_EXEC}</echo>
<exec dir="${basedir}" executable="${MAVEN_EXEC}">
<arg line="clean compile war:war -Dtarget=${TARGET}" />
<delete file=".\\target\\csd.war" />

<target name="prep_test" depends="war">
<copyfile dest=".\\src\\main\\resources\\applicationContext_test.xml" src="${WAR_EXPLODED}\\WEB-INF\\classes\\applicationContext.xml" />

<target name="test" depends="prep_test">
<echo>Maven Executable: ${MAVEN_EXEC}</echo>
<exec dir="${basedir}" executable="${MAVEN_EXEC}">
<arg line="compile test -Dtarget=${TARGET}" />

public abstract class TestCaseSpringAutoWire extends AbstractTransactionalDataSourceSpringContextTests implements Constants
    protected String[] getConfigLocations()
return new String[] { "classpath:applicationContext_test.xml" };

GWT: building war with Maven 2 and Ant and deploying to Tomcat - single click

<project name="csd" default="prep_deploy" basedir=".">

<property name="WAR_EXPLODED" value=".\\target\\csd" />





<property file=".\\src\\main\\resources\\${}.properties" />

<target name="clean">

<delete dir="com.ucc.csd.CSD" />

<delete dir="www" />

<delete dir="target" />

<delete dir="bin" />

<delete dir="target-eclipse" />

<delete dir="tomcat" />

<echo>Refresh your Eclipse project (F5)echo>


<target name="war" depends="clean">

<echo>Maven Executable: ${MAVEN_EXEC}echo>

<exec taskname="mvn war" dir="${basedir}" executable="${MAVEN_EXEC}">

<arg line="clean compile war:war -Dtarget=${TARGET}" />


<delete file=".\\target\\csd.war" />


<target name="hibernate_hbm_to_ddl" depends="clean">

<echo>Maven Executable: ${MAVEN_EXEC}echo>

<exec taskname="mvn hbm2ddl" dir="${basedir}" executable="${MAVEN_EXEC}">

<arg line="clean compile hibernate3:hbm2ddl -Dtarget=${TARGET}" />


<delete file=".\\target\\csd.war" />


<target name="prep_test" depends="war">

<copy file=".\\target\\classes\\applicationContext.xml" tofile=".\\src\\main\\resources\\applicationContext_test.xml" />


<target name="test" depends="prep_test">

<echo>Maven Executable: ${MAVEN_EXEC}echo>

<exec taskname="mvn test" dir="${basedir}" executable="${MAVEN_EXEC}">

<arg line="test -Dtarget=${TARGET}" />



<target name="gwt_shell" depends="war">

<echo>GWT: starting hosted (dev)echo>

<java taskname="GWT hosted" classpathref="class_path" classname="" fork="true" maxmemory="256m">

<jvmarg line="-verbose ${JVM_ARG_START}" />

<arg line="-out www com.ucc.csd.CSD/CSD.html" />



<target name="gwt_compile_to_js" depends="war">

<java taskname="GWT compile" classpathref="class_path" classname="" fork="true" maxmemory="512m">

<jvmarg line="-verbose ${JVM_ARG_START}" />

<arg line="-logLevel WARN -out www com.ucc.csd.CSD" />



<target name="prep_deploy" depends="gwt_compile_to_js">

<copy todir="${WAR_EXPLODED}">

<fileset dir="www/com.ucc.csd.CSD" />


<copy file=".\\src\\com\\ucc\\csd\\CSD.gwt.xml" todir="${WAR_EXPLODED}\\WEB-INF\\classes\\com\\ucc\\csd" />


<target name="deploy_locally" depends="prep_deploy">


<delete dir="${DEPLOY_DIR}" />

<copy todir="${DEPLOY_DIR}">

<fileset dir="${WAR_EXPLODED}" />




<path id="class_path">

<pathelement path=".\\src" />

<pathelement path=".\\src\\main\\java" />

<pathelement path=".\\target\\classes\\" />

<fileset dir="${GWT_HOME}">

<include name="*.jar" />


<fileset dir="${WAR_EXPLODED}\\WEB-INF\\lib">

<include name="*.jar" />




UNIX ln -s, or link command

$ sudo ln -s /opt/apache/apache-tomcat-5.5.17 /usr/local/tomcat
$ cd /usr/local/tomcat/webapps/
uki@MacBookPro:/usr/local/tomcat/webapps $ pwd

Email validations

private boolean isEmailBad(String email)
String emailChars = "@.";
if (email.indexOf(emailChars) == 1){
log.warn("Email address does not contains @ and . charachters");
if (email == null || email.length() < 5)
log.warn("Invalid email address length");
return true;
return false;

GWTShell arguments

[java] Google Web Toolkit 1.4.61
[java] GWTShell [-port port-number | "auto"] [-noserver] [-whitelist whitelist-string] [-blacklist blacklist-string] [-logLevel level] [-gen dir] [-out dir] [-style style] [url]
[java] where
[java] -port Runs an embedded Tomcat instance on the specified port (defaults to 8888)
[java] -noserver Prevents the embedded Tomcat server from running, even if a port is specified
[java] -whitelist Allows the user to browse URLs that match the specified regexes (comma or space separated)
[java] -blacklist Prevents the user browsing URLs that match the specified regexes (comma or space separated)
[java] -logLevel The level of logging detail: ERROR, WARN, INFO, TRACE, DEBUG, SPAM, or ALL
[java] -gen The directory into which generated files will be written for review
[java] -out The directory to write output files into (defaults to current)
[java] -style Script output style: OBF[USCATED], PRETTY, or DETAILED (defaults to OBF)
[java] and
[java] url Automatically launches the specified URL

Thursday, May 22, 2008

hibernate: generating a new table from model obj.


Create a Java model object containing the needed properties and Java 1.5 annotations:

@Table(name = "mail_history")
public class MailHistory implements Serializable
@Column(updatable = false, name = "date_sent", nullable = false)
private Date dateSent;

@Column(name = "entity_id", nullable = false)
private int entityId;

@Column(name = "entity_name", nullable = false, length=20)
private String entityName;

@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, name = "id", nullable = false)
private Long id;

@Column(name = "mail_type", nullable = false)
private int mailType;

@JoinColumn(name = "user_id", nullable = false)
private User user;

//generate getter and setter methods

Add the model object to applicationContext.xml and hibernate.cfg.xml configuration file

Run maven:

mvn -e clean compile hibernate3:hbm2ddl -Dtarget=Zainab

Wednesday, May 21, 2008

Java: making list random using List shuffle

A very useful method to randomly order the List:

import java.util.Collections;

List list = fetch();

return list.get(0);

Hibernate Query

public List fetchGamesWithoutHeadlineBetween(Date startDate, Date endDate)
DetachedCriteria dc = DetachedCriteria.forClass(TeamGame.class);
dc.setFetchMode("game", FetchMode.JOIN);
DetachedCriteria dcGame = dc.createCriteria("game");
dcGame.add(Expression.between("startDate", startDate, endDate));
List teamGames = getHibernateTemplate().findByCriteria(dc);
return teamGames;

mysql: select

select* from game where headline = 'U13 Predators Black Vs. U13 Niles Renegades'

Unix: grep

Find WARN and display by page:

grep WARN nohup.out | more

Tuesday, May 20, 2008


This code will return a list of date in the long formate, for example: Fri May 16 14:13:38 CDT 2008

public static List getDatesBetween(Date fromDate, Date toDate)
Calendar calendar = Calendar.getInstance();
List dateList = new ArrayList();
if (fromDate.before(toDate))
Date dateCounter = fromDate;
while (dateCounter.before(toDate))
int nextDate = calendar.get(Calendar.DATE) + 1;
calendar.set(Calendar.DATE, nextDate);
dateCounter = calendar.getTime();
} else if (!fromDate.before(toDate) && !fromDate.after(toDate))
return dateList;


public void test_DatesBetween(){
Date fromDate = DateHelper.incrementDays(new Date(), -4);
Date toDate = new Date ();
log.warn(DateHelper.getDatesBetween(fromDate, toDate));

Try and Catch

1. Never leave an empty catch in a try and catch block:
catch (FileNotFoundException fileNotFoundException) { }
2. Output the log:
catch (FileNotFoundException fileNotFoundException)
log.err(“File was not found” + fileNotFoundException.getStackTrace());
System.err.println(“File was not found” + FileNotFoundException.getStackTrace()”);

3. Inside the catch, return a value that alters the application flow. For example, redirect user to a page “Server temporarily not available”.
4. Do not wrap the whole method in a try and catch block
5. Do not use generic Exception , if more specific exceptions are available.
6. Use method() throws Exception very cautiously and only when there is a very good reason

Firefox - how to clear browser cache

It is important to clear the browser cache when viewing a newly
deployed application.

Monday, May 19, 2008

"Loony" data storage

I was thinking about all this music that was either never recorded, or
which recordings did not survive.
Then, I was thinking about the TV and radio programs that were
broadcasted into the space. They are still there travelling at the
speed of light. Occasionally, they bounce back and we can pick them up.
Then, I thought: Wow!
If we use the broadcasting into the space and bouncing it agaist the
celestial bodies, let's say a few years away, we could create an
unlimited, long term storage device. This storage would be good for
serial data for which we don't have the capacity today, or we don't
have use, but which might come useful in few years.
What might it be? High resolution images taken every second from
satelites, medical, or other fields. Today, these might be useless,
but in few years they might be used in climate comparisons, or
population health studies.

Loony? Maybe, but fun to think of...

Send VC money to this account...

# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=INFO, CONSOLE
#log4j.rootCategory=INFO, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE., CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Programming Best Practices

1. Do not hide exceptions by using a catch and not throwing an error.
2. Avoid nested if statements, the if(object != null) spanning the whole method is a very common mistake:

void methodName(){ if (object != null)
if (more conditions)
{ //100 lines of code }
// 100 more lines of code

Java: swallowing exceptions

This is an example of code that can get us in trouble. We will never know that something went wrong...

public void uploadImportFile(FileContents fileContents, String fileName, String uploadlocation)
OutputStream outFile = null;
File file = new File(uploadlocation);
outFile = new FileOutputStream(uploadlocation + fileName);
outFile.write(fileContents.getFileContents(), 0, fileContents.getFileContents().length - 2);
catch (FileNotFoundException fileNotFoundException)
{ }
catch (IOException ioException)
{ }

1. In the least use:
System.err.println("FileNotFoundException e: " + e.getMessage());


But even better the method should not be void, but return the status.

2. Do not wrap the whole method in try{} with generic exceptions
3. Have a good reason to "push-up" the exception by adding it by the method name "throws ..."

IE 7 Cache Clearing

To clear cache:

IE Menu -> Tools -> Internet Options -> General -> Browsing History -> Delete ... -> Delete Files ...

Safari - empty cache

It is essential that you empty the cache after the deployment of the
new version of application. Otherwise the old files may be breaking
the application.

Friday, May 16, 2008

Java Date Increment

public static Date incrementHours(Date date, int hours)
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();

Linux: ip & gateway addresses

To find your linux ip address:

ipconfig -a

To find your linux gateway address:
netstat -rn

Linux: Creating a new system user

In terminal:

sudo adduser userName

To login with root privlages:
su userName

Check on current user permissions:
ls -ld

Internet Speed Test

Download Speed: 11887 kbps (1485.9 KB/sec transfer rate)
Upload Speed:
1306 kbps (163.3 KB/sec transfer rate)

SQL Truncate

To empty a table in database using SQL statment:
truncate table tableName

Wednesday, May 14, 2008

SQL: inner join

select distinct last_name, first_name, login_name, login_password, email from user
inner join administrator on = administrator.user_id
order by Last_Name

Image Resizer

public static BufferedImage createResizedCopy(String imageLocation)


boolean preserveAlpha = true;

File originalImageFile = new File(imageLocation);

BufferedImage originalImage;



originalImage =;

int width;

int height;

double h = new Double(originalImage.getHeight()).doubleValue();

double w = new Double(originalImage.getWidth()).doubleValue();

double ratio = (h / w);

if (ratio > 1) // vertical (tall image)



width = new Double(height / ratio).intValue();

} else



height = new Double(width * ratio).intValue();


int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

BufferedImage resizedImage = new BufferedImage(width, height, imageType);

Graphics2D g = resizedImage.createGraphics();

if (preserveAlpha)


g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

g.drawImage(originalImage, 0, 0, width, height, null);


return resizedImage;

} catch (IOException e)


System.err.println("Errors resizing the image " + imageLocation);



return null;