Code, Coffee

Full contact Java programming from the trenches.


Follow me on Twitter!
Main | Next page »
Thursday Dec 18, 2008

My other blog on Artima.com, and my first post, "The New Old"

The New Old, my first post on Artima.com. Check it out. Let's talk.

Wednesday Dec 17, 2008

A journey of a thousand miles begins with a single step: “Programming Collective Intelligence”, by O'Reilly

Working through my reading list. You might infer that I'm a bit behind because this review is about a book published in September of 2007.

You'd be correct.

"Programming Collective Intelligence" is astonishingly clear and concise in the examples, and a brilliant introduction to the foundations of a lot of fields of study. A well presented discussion on many of the key items in the AI/algorithm world. Why is this so worth repeating? Because these concepts – genetic algorithms/ AI / optimization, etc, are NOT common nor are they simple. Anybody who manages to make them appear so is worth of praise. The examples are further interesting because they're written in Python, which is as simple as a language can get. (Digression: Python 3.0's out! How come I didn't see a flurry of news? How come there was no ball drop in Times Square? I'm excited, and proportionately confused by some people's reactions, like this one. Get your copy while it's hot!

The book is sort of the first rung of knowledge on a whole gamut of complex topics, but that's OK because these topics become approachable only once you've gotten the introductory tour. Finding that "tour", the source for the inevitable epiphany, is what's so hard about these concepts. It's even further difficult because it's not like there's a lot of mainstream thinking going on here and these concepts just represent a slight tangent on what you're already dealing with. Anything but. People who know why they want to use something like JBoss Rules already knew it. You'll notice there's no good "sales" rhetoric on the JBoss website. It's the chicken and egg problem. Understanding the concepts in this book is key to caring about, and eventually understanding, things like JBoss Rules.

All in all, a very worthy read. If nothing else, it's a good refresher.

A Quick Guide to Posting To (A Few) Blogs with Java

First, How to Post to Any API that supports the (admittedly) outdated MetaWeblog API.

How to Publish A Blog Entry For Roller 4.0 Software I found very little in the way of a solid API in Java on top of this XMLRPC API. However, I did find quite a bit using just good old Apache XMLRPC 3.0. Here's how that solution looks:


 /**
 * @param serverUrl if youve unpacked a stock Roller 4.0 url, it's
likely going to be http://www.YOURHOST.com/roller-services/xmlrpc
 * @param user the user you have configured on Roller itself
 * @param the password for the user name
 * @param blogId the id of the blog. When you log into the Admin
screen most pages will mention it.
 * @param title the title of the post
 * @param content the content of the post (can be in HTML)
*/
  public String createPost( String serverUrl, String user, String
pass, String blogID, String title, String content) throws IOException
{
        String ret = null;
        try {
            XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
            config.setServerURL(new URL(serverUrl));
            XmlRpcClient client = new XmlRpcClient();
            client.setConfig(config);
            Map m = new HashMap();
            m.put("title", title);
            m.put("description", content);
            m.put("dateCreated", new Date());
            m.put("category", "Java");
            Object[] params = new Object[]{blogID, user, pass, m, true};
            ret = (String) client.execute("metaWeblog.newPost", params);
        } catch (Throwable th) {
            System.out.println( "blam!") ;
        }
        return ret;   // a unique ID generated by Roller
    }

How to do the same thing with Blogger Usign Google's GData.


 GoogleService service = new GoogleService("blogger", "");
        service.setUserCredentials(user, pass);
        Entry myEntry = new Entry();
        myEntry.setTitle(new PlainTextConstruct(title));
        myEntry.setContent(new PlainTextConstruct(content));
        Person author = new
Person(StringUtils.defaultString(authorName), null, null);
        if (!StringUtils.isEmpty(authorName)) myEntry.getAuthors().add(author);

        URL postUrl = new URL("http://www.blogger.com/feeds/" + blogID
+ "/posts/default");
        return service.insert(postUrl, myEntry);

The Google Data stuff was using the Java Google Data APIs. The XMLRPC library is quite formidable. I'd not recommend using Apache XMLRPC 3.1.1 from Maven, as it didn't seem to be a valid artifact.

Anyone else noticing the extreme slowness of Java applications on Ubuntu 8.10?

Anyone else noticing the extreme slowness of Java applications on Ubuntu 8.10? I upgraded and was expecting that the seminal Java 6u10 (strike that! 11! ) would do better than this.

I was expecting draggable applets and for the performance of my Java applications to not deteriorate. I was disappointed on both fronts. If you're having issues with IntelliJ crawling, a lot of people have downgraded to 8.04 Ubuntu.

Saturday Dec 13, 2008

How to Ride Spring Integration Head

How to build Spring Integration (for Maven) locally... Posting this for my own reference as much as anyone else.

svn co https://src.springframework.org/svn/spring-integration/trunk/build-spring-integration
cd trunk/build-spring-integration
ant clean jar package publish-maven-local

Saturday Dec 06, 2008

Maven 2.0.9, Andromda 3.[2,3]

I was building a project I have that's using the Maven Andromda plugin to cross compile UML class diagrams into Java EJB3 entity classes. The plugin's worked flawlessly for a long time now, but this time it failed. It complained that it couldn't find the UML file that was referenced in the configuration file. It's no wonder: the file path it was looking for was doubled up, that is, it was equivalent to /myfolders/foo/uml.uml2/myfolders/foo/uml.uml2. I did some research and found this bug report. This proves that it wasn't my Andromda installation, but the Maven installation. This makes sense as I'd just recently upgraded from Ubuntu Hardy Heron (8.04) to Ubuntu Intrepid Ibex (what's an Ibex?; 8.10) and the package I was using (maven2) had been updated to 2.0.9. So, the moral of the story here is: make sure your Maven package didn't change under your nose.

Thursday Dec 04, 2008

JavaFX 1.0 Released

Finally, JavaFX 1.0 – it's been 2 long years, but I'm glad to see this thing get going. Even if it shares the same fate as Silverlight and becomes a clumsier Flash, it's still a MUCH more agile Java. As the libraries enabled via JavaFX are all just Java code, you can still leverage them in standard Java. You needn't use JavaFX, for example. This means that the amazing integration with video and audio is yours for the taking.

It is unfortunate that they haven't released the Linux bits, yet. But that will change, and in the meantime, 1.0 is chock full of goodies. The blogosphere's been abuzz with information leading up tot the 1.0 release. People are interested in graphics on the Java platform (again?)! I've seen everything from information on using Java Webstart with JavaFX (do you remember Java Webstart? That was something I always wished had taken off), information on using the toolkit with Maven, information on using it on Linux (why does every neat graphical platform have to support Linux last? Flash: I don't understand why Flex took so long to get there. Silverlight... well, I'm pleased it ran on more than one version of Windows, so no complaints, I suppose as I should've known. But Java?) and more.

I have some questions: what's the video streaming solution look like on this platform? On the Flash platform you typically use something like LightHTTPD or Nginx and use Flash Video (or, now, H264). I understand that On2 is going to be providing a format for video (similar to FLV?) just as they did for the Flash platform. Do the same rules apply with respect to security and performance? What about remoting? My understanding is that JavaFx will have considerable support for this (which should come as no surprise given the incredible wealth of remoting toolkits on the Java platform) and will even respect the crossdomain.xml file (which comes from the Flash platform).

All in all, this is exciting and I can't wait to see where the platform goes from here. The other redeeming value about JavaFX is the unification of the paradigms: working in J2ME meant learning one set of APIs (CLDC, Midlets, J2ME Polish, and more recently, LWUIT), working on Java on the desktop meant SWT, or Swing (which meant... clawing your eyes out using a toothbrush), and working on the server meant using a web framework that didn't have any rich client functionality. Now, it's JavaFX for the desktop, the client, the mobile clients and soon, the TV. This is very promising.

Wednesday Dec 03, 2008

Spring Integration 1.0 Released

Spring Integration is almost ready (website updates notwithstanding!)

Spring Integration is an API for building integration solutions using Spring. It works, conceptually, very much like Axway Integrator or Mule or ServiceMix or Petals or, well, you get the idea: it provides functionality to respond to messaging / interactions in a system and route / transform the message to an endpoint. These messages could be JMS, FTP submission, a file suddenly appearing, etc. Spring Integration is an API that provides ESB like functionality. Usually, the ESB is a server to which application integrations are deployed. This API flips that idiom on its head and lets your application become the endpoint by which integration is achieved.

Spring Integration itself is significant because it codifies in a Spring API the whole field of knowledge surrounding ESBs, which itself can be said to stem from Enterprise Integration Patterns: this has the boon of making it a commodity. And of course, there are the usual reasons: it works better for the things it does, it's well tested, easy-to-test, etc. But you knew about those already.

I'm waiting with baited breath for the Maven releases :-)

Congratulations to the Spring Integration team! Wonderful tool and I look forward to being able to recommend it moving forward. Get the bits!

Update: The old way still works and they've updated those bits already if you're looking to get the Maven jars

Update:I linked to the wrong book and gave the wrong title, despite having the correct book sitting on a computer tower right next to me. Now that's impressive! Thanks to Mark Fisher (lead on the Spring Integration project!) for the correction.

Tuesday Nov 11, 2008

Intellij 8.0

IntelliJ 8.0's a large step forward (and none back!)

I just downloaded the latest and greatest revision of Jetbrain's flagship product, Intellij IDEA 8.0. It is, in a word, pretty awesome. This is due in large part to the refactoring of the core that has occurred between 7 and 8 to improve the application of the IDE for different languages. Support includes, but is not limited to, Groovy, Scala, Ruby, and Java (wherein you also have a dozen different DSLs with which IDEA contends admirably).

What seems to happen with Intellij is that they include feature and support for a feature that's, shall we say, half baked. Don't get me wrong: a half baked Intellij feature's usually worth 2 or 3 fully baked Eclipse features. Compared to the usual level of quality, some times things slip through that don't meet expectations but that do – nonetheless – work. Where 7.0 of the IDE was pretty revolutionary, version 8.0 seems evolutionary (at least in terms of features.)

Instead, things are better polished, faster. Maven support was good when it was introduced in 7.0. Now, it's remarkably well thought and configurable. Intellij has supported displaying test coverage data when unit tests are running. Now it's possible to jump from a class to a test case. Ever wanted to be able to ride the data flow analysis and see where values in the system come from? Now you can. The support for Subversion and Subversion 1.5 is pretty stellar, and includes the ability to see which version of a change have already been integrated into a branch. Actually, the Subversion support is one of the things I've long liked from Intellij. Eclipse hasn't until version 3.4 officially supported Subversion at all. Eclipse 3.4 includes part of the functionality for accessing Subversion, but due to licensing issues you're on your own to install the remaining bits yourself. Intellij already had support for Flex (and the best JavaScript integration I've ever seen), but not much more than support for referencing and coding ActionScript. Now, you can almost effectively remove Flex Builder from your life if you're not planning on doing anything graphical.

And of course, there are new features, too. Support for Seam, better support for Jruby (which was already being called the best in the industry, and is now the extracted core of Intellij's RubyMine product), 20+ new intelligent refactoring capabilities, the ability to assign and swatch of text a “language” so that Intellij can enable proper editing for it, and the UML capabilities round out the features. One of my favorite new features is the ability to... remove... features. Intellij has a LOT of features. While they're not obtrusive or glaringly present like an overloaded Eclipse instance can be, they are there when you launch the application and they consume RAM. I loaded IntelliJ and it gave me a Plugin configuration wizard by which I could disable plug ins. I'm not likely going to be using the Perforce SCM integration, and nor am I likely going to be using the FreeMarker and Struts configuration tools. So, why not disable them? The speed boost at both runtime and startup is marked.

There are many more new features to like in this tool as well as the coder-friendly editor itself, which is just as tight a fit now as it's ever been. IntelliJ has always taken refactoring to a new plateau hiterto unmatched by Eclipse or Visual Studio, and this release is now exception.

What I didn't like: the tool had some JSP validation errors because of a URL that needs to be downloaded to resolve. In previous versions a little intelligent tooltip would prompt you to let IntelliJ download the file. Not so much in this case. Instead, I was prompted by IntelliLang's tool tip, asking me if I wanted to declare the URL to be a fragment of .. insert your favorite schema/dialect/language/grammar here. Annoying. I still don't know how to get the old functionality to return. Thankfully, in this case, the code was one "old" style JSP and the rest of the site consists of JSP Documents, which all displayed and edited perfectly. And quickly! IntelliJ is pretty quick, anyway, but it seems like the price you pay for invalid HTML is more pronounced in the IDE than, say, with DreamWeaver. )

All in all, a worthy upgrade and I wholeheartedly recommend it.

Tuesday Oct 07, 2008

TestNG, Spring TestContext, and Maven

If you've ever used the testing support in prior versions of Spring you know that it was essentially JUnit 3.x, oriented. There were ways to make those scaffolding classes work for (my personal favorite) TestNG or even Junit 4, but they largely were engineering hacks, not real solutions. For example, with the TestNG case you could override the setUp method and annotate it such that TestNG would call that method for setup, while also complying with Junit's interface requirements. Now there's a better way. Here's how I got it workiung with Maven and Surefire and TestNG 5.7. First, I added support for TestNG 5.7 (which is current as of this writing.):

<dependency> <artifactId>testng</artifactId> <groupId>org.testng</groupId> <version>5.7</version> <classifier>jdk15</classifier> </dependency>

Then I added support for SureFire to the Maven POM:

  <plugins> 
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> >
<version>2.4</version>
<configuration>
<suiteXmlFiles>

<suiteXmlFile>${basedir}/src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>

</plugin>

</plugins>

Finally, it comes time to write the test. Maven has a structure that's realized using the following command:

mkdir -p src/{test,main}/{java,resources};

Your unit test code goes into src/test/java and your testng.xml goes into src/test/resources.

Here's an example of the testng.xml:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"
> <suite name="myProject" verbose="5">
<test name="serviceTests">
<packages>
<package
name="com.joshlong.myProject.test.services"/>
</packages>
</test>

</suite>

And, finally, here's an example of a test class that works:

package com.joshlong.myProject.tests.services;
import com.joshlong.myProject.utils.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
// THIS ONE's IMPORTANT! There are one of these for each of the 3 frameworks you're likely to want to use.
import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
* @author Josh Long
*/
@ContextConfiguration(locations = {"classpath:service-context.xml", "classpath:test-context.xml"})
public class MyProjectTest extends AbstractTransactionalTestNGSpringContextTests {

@BeforeMethod public void announceClass() throws Throwable {
loggingUtils.log("Inside of MyProjectTest!");
}


@Autowired
private LoggingUtils loggingUtils; // this gets automatically injected from one of the contexts listed in the @ContextConfiguration annotations.

@Test
public void testBasicMath() throws Throwable {
loggingUtils.log("foo()");
assertTrue( 1 < 2, "1 < 2 -- pray that this is correct and that this test never does fail!");
}
}