Posts Tagged “java”

I was recently writing a program to find classes that had a certain annotation on them:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation works similarly to the @WebMethod
 * annotation. It is used to indicate that the annotated method is allowed to be
 * made visible on a generated facade, and how to do it.
 *
 */
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface FacadeMethod
{
	/**
	 * This is the operation name that the annotated object will have on the
	 * generated facade. This will be used as the value for
	 * operationName in the @WebMethod
	 * annotation as well as the name of the method in the facade.
	 *
	 * @return the name that the annotated object will have on the generated
	 *         facade
	 */
	String operationName();

	/**
	 * This is a description of the method which will be used to generate
	 * javadoc on the facade.
	 *
	 * @return a description of the method
	 */
	String description() default "";
}

Methods annotated with this method look something like this:

@FacadeMethod(operationName = "effectivelySame",
              description = "Return true if the two strings are identical, both null, "
                            + "or equivalent after converting to same case and trimming")
public static boolean effectivelySame(String s1, String s2) {
...

What I needed to do was look through a whole mess of jar files that weren’t in the classpath, looking for classes with methods annotated with this annotation, so I could read the operationName and the description properties of the annotation.

Read the rest of this entry »

Comments No Comments »

I was looking at some of the core language enhancements being considered for JDK 7.  Some of them look pretty good, others, meh.  Here are a few of the ones I’m looking forward to:

Constructor Inference for Generics

Using generics, your currently have to type both sides of an assignment when doing a constructor:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

Being considered is the ability to omit the types and infer them, such as:

Map<String, List<String>> anagrams = new HashMap<>();

which would be equivalent to the first line.  I like this - improves readability, loses nothing but typing.

Relational operators for Enums

Currently, the only relational operators that you can use for constants in an Enum are == and !=.  Since all enums implicitly implement Comparable, theres no good reason why you should not be able to use <, >, <= and >= on enums.  As it stands now, you need to explicitly invoke compareTo().

Switches on Strings

Sure would be nice if instead of if-else if-else constructs to branch on string values, you could do

switch(someString) {
   case CONST_1:
      return true;
   case CONST_2:
      return false;
   default:
      throw new IllegalArgumentException("Bad value: " + s);
}

Comments No Comments »

The second edition of Josh Bloch’s outstanding book Effective Java is coming out June 8, 2008.  I can’t wait.  If you don’t have the original version of this book, you are truly missing out.  It’s a great near-bible of doing things the right way with Java so code can be maintained and relied upon.

It’s available for order on Amazon.  And in interest of full disclosure, I have no financial interest in his book (unless having co-workers and colleagues write better code counts).

Comments No Comments »

I needed an application, available to my entire development team, to provide RSS feeds for commit activity in our Subversion repository. I found a couple of items that looked reasonable, but they required scripting languages I could not use in my environment - I needed a Java-based solution.

So I decided to write it.

To access Subversion, I used SVNKit, an all-java library for SVN access. To create the RSS feed file (which is just an XML file) I used JDOM, my favorite XML handling library.

To deploy it, just deploy the WAR File to your Servlet container. SvnRss web archive (WAR file)

To use it, hit the app, passing the SVN url as a query parameter (if your aggregator gives you trouble, try URL encoding it). If you need to authenticate to access the repository, specify uid=yourusername and pwd=password as query parameters as well. By default, the feed includes the last 100 revisions, but you can override this with the numRevisions=nn query parameter.

Example invocations:

http://yourserver/SvnRss/SvnRssServlet?svnUrl=svn://yourrepository:1230/java/trunk

http://yourserver/SvnRss/SvnRssServlet?svnUrl=svn://yourrepository:1230/java/trunk&uid=kescobar&pwd=whatsamanmonth

http://yourserver/SvnRss/SvnRssServlet?svnUrl=svn://yourrepository:1230/java/trunk&numRevisions=25

The source code (in an Eclipse project) is also available. SvnRss source code (Zip file)

Comments 6 Comments »

If there’s one thing that really annoys me, it’s opening code with garbage like this in it:

Set foos = new HashSet<foo>();
String queryString = "from FooTable as foo where foo.barField in (:listOfBarFields)";
try
{
	foos.addAll((List<foo>) HibernateSessionFactory
			.getSession().createQuery(queryString)
			.setParameterList("listOfBarFields", getBars()).list());
}
catch (Throwable th)
{
}

First, all the method chaining kinda bugs me — but I can live with that.

What makes me want to barf is chaining all those Hibernate calls together in one statement, and surrounding it with a try/catch that eats Throwable. Throwable. This is not framework code, this is not a library — it’s application code, and application code has no business catching a raw Throwable. And to make it worse, it completely suppresses the Throwable and makes it look like it never happened - it doesn’t even log it.   Oh, and there’s no JUnit test covering the code.

Anyone who writes code like this should be cruelly and severely punished. Or fired.

What’s also sickening is that anyone can write this kind of stuff and call themselves a professional programmer (and lots of them do it all the time), but you need a state license and show some level of competency to give a pedicure, run an auction house, or be an interior designer.

Comments 3 Comments »

I was messing with the Google Web Toolkit yesterday. My friend Jeff is a big fan of it, and he is actually using it for a Navy system that I once worked on. He’s gotten a couple of his coworkers on the bandwagon, so I started messing with it.

If you don’t know, GWT is a tool for creating AJAX applications. You write code in Java, and the GWT compiler translates it into Javascript instead of byte code. Separating the client side from the server side is built in, and they have done things to simplify RPC calls back to the server from the client.

First thing I liked is that the installation is dead easy. Download a zip file, explode it somewhere, and to make things simple, add it to your execution path. There is nice eclipse integration too. Adding and removing widgets (UI elements) from the page was also dead easy, and hooking up listeners to react when things are messed with was a breeze.
Read the rest of this entry »

Comments No Comments »

I’ve been spending some time working with the JPDA - Java Platform Debugger Architecture - and it’s pretty darn cool. Using this framework, which is shipped with the basic Java SE JDK, basically allows you to write debuggers.

I hear you ask: Why on earth would you want to do this when there are so many good debuggers already? Eclipse does everything I need!

True. But what if you need one process to monitor the execution of another? And I don’t mean to have interprocess communication, I mean for one process to MONITOR THE EXECUTION of the other. Sounds like a debugger to me. Why should Eclipse have all the fun?

Read the rest of this entry »

Comments No Comments »

I’ve recently been doing a lot of work with getting stack traces for a project I’m working on, and I’ve had what I sometimes call a “BGO” - Blinding Glimpse of the Obvious: getting Stack Trace information in Java is dead slow.

JDK 1.4 introduced the getStackTrace() method on Thread, which returns an array of StackTraceElement objects. This is way better than what had to be done previously, which was to generate a stack trace dump to a String-backed output stream and parse the dump, but underneath it all (and you can see this if you download the source for the JDK) it calls native code (fillInStackTrace()) to get the actual stack information for the thread. This is because threads are implemented natively using platform-dependent code that will not only vary by platform but by JVM vendor and version.
Read the rest of this entry »

Comments No Comments »

I’ve started a new (mostly) greenfield project recently and after two years of having to code in an existing application with a restrictive framework, I was eager to stretch my legs a bit and break out some of the good ol’ tools that made me so productive in previous gigs - XDoclet being one of them.

For those who don’t know, XDoclet is an open-source tool that lets you put special tags in your javadoc, which XDoclet finds in a post- or pre-compile step, and uses to generate more code, or configuration files, or whatever else you want to generate. Most frequently, XDoclet is used to generate deployment descriptors and helper classes to go with the most important classes of a system. Hibernate promotes (or at least, promoted) XDoclet as part of its suite of tools for easing configuration. Almost any book on Hibernate includes at least one chapter on using XDoclet to build your Hibernate configurations.
Read the rest of this entry »

Comments No Comments »

Those of you who know me or who have read my earlier posts know that I am a static code analysis fan, and some of my favorite tools are PMD, Checkstyle, FindBugs, and JDepend, for their excellent feedback on the state of the quality of your code. In fact, I regularly use all of them and usually in combination with other tools (such as JUnit, Emma, etc) to gather code metrics.

The reports from each of these tools naturally identify problems — why else would you run them? And once you see a problem, you naturally want to run right out and fix them. The report shows them all, rated by severity, with counts and everything, and you can see the types of errors. It’s just a simple refactoring, right?

Better think twice before activating that refactoring in your IDE.

Read the rest of this entry »

Comments No Comments »