GWT 1.5 M2

http://code.google.com/p/google-web-toolkit/downloads/list?can=4&q=version:1.5

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:


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

Daily Trigger

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

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}" />
</exec>
<delete file=".\\target\\csd.war" />
</target>

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


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




public abstract class TestCaseSpringAutoWire extends AbstractTransactionalDataSourceSpringContextTests implements Constants
{
    protected String[] getConfigLocations()
    {
setAutowireMode(AUTOWIRE_BY_NAME);
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" />

<echo>

ATTENTION! CREATE FOLLOWING FILE IF MISSING:

.\\src\\main\\resources\\${user.name}.properties 

echo>

<property file=".\\src\\main\\resources\\${user.name}.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>


<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}" />

exec>

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

target>


<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}" />

exec>

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

target>


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

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

target>


<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}" />

exec>

target>


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

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

<java taskname="GWT hosted" classpathref="class_path" classname="com.google.gwt.dev.GWTShell" fork="true" maxmemory="256m">

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

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

java>

target>


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

<java taskname="GWT compile" classpathref="class_path" classname="com.google.gwt.dev.GWTCompiler" fork="true" maxmemory="512m">

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

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

java>

target>


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

<copy todir="${WAR_EXPLODED}">

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

copy>

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

target>


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

<echo>DID YOU STOP TOMCAT?echo>

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

<copy todir="${DEPLOY_DIR}">

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

copy>

<echo>START YOUR TOMCATecho>

target>


<path id="class_path">

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

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

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

<fileset dir="${GWT_HOME}">

<include name="*.jar" />

fileset>

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

<include name="*.jar" />

fileset>

path>


project>

UNIX ln -s, or link command

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

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

hibernate: generating a new table from model obj.

pom.xml:
Create a Java model object containing the needed properties and Java 1.5 annotations:
@Entity @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; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(updatable = false, name = "id", nullable = false) private Long id; @Column(name = "mail_type", nullable = false) private int mailType; @ManyToOne @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

Java: making list random using List shuffle

A very useful method to randomly order the List:

import java.util.Collections;

List list = fetch();
Collections.shuffle(list);

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)); dcGame.addOrder(Order.asc("startDate")); dc.add(Expression.isNull("headline")); 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

getDatesBetween

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; dateList.add(fromDate); while (dateCounter.before(toDate)) { calendar.setTime(dateCounter); int nextDate = calendar.get(Calendar.DATE) + 1; calendar.set(Calendar.DATE, nextDate); dateCounter = calendar.getTime(); dateList.add(dateCounter); } } else if (!fromDate.before(toDate) && !fromDate.after(toDate)) { dateList.add(fromDate); } return dateList; }
Test:
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.

"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...

Log4j.properties

# 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. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.Threshold=INFO log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.Threshold=INFO log4j.appender.LOGFILE.layout=org.apache.log4j.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;
try
{
File file = new File(uploadlocation);
file.mkdirs();
outFile = new FileOutputStream(uploadlocation + fileName);
outFile.write(fileContents.getFileContents(), 0, fileContents.getFileContents().length - 2);
outFile.close();
}
catch (FileNotFoundException fileNotFoundException)
{ }
catch (IOException ioException)
{ }
}

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

e.printStackTrace();


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.

Java Date Increment

public static Date incrementHours(Date date, int hours) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); 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

http://www.speakeasy.net/speedtest/


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

SQL: inner join

select distinct last_name, first_name, login_name, login_password, email from user
inner join administrator on user.id = 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;

try

{

originalImage = ImageIO.read(originalImageFile);

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)

{

height = Constants.OVERVIEW_TAB_HORIZONTAL_PHOTO_HEIGHT;

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

} else

{

width = Constants.OVERVIEW_TAB_HORIZONTAL_PHOTO_WIDTH;

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.setComposite(AlphaComposite.Src);

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

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

g.dispose();

return resizedImage;

} catch (IOException e)

{

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

e.printStackTrace();

}

return null;

}