Java: Simple check to see if a server is listening on a port

Here is a simple method to check if a server is listening on a certain port. I used it to ignore certain non-critical SFTP related integration tests in a project when I hadn’t bothered starting the SFTP server.

public static boolean serverListening(String host, int port)
{
    Socket s = null;
    try
    {
        s = new Socket(host, port);
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
    finally
    {
        if(s != null)
            try {s.close();}
            catch(Exception e){}
    }
}

To ignore a test (assuming JUnit) you can then do the following:

@Test
public void some_test()
{
    assumeTrue(serverListening("localhost", 22));

    // Rest of test...
}

Quick’ish way to swap between Java versions on Windows

Here’s a sort of quick way to swap between Java versions on Windows without having to change any environment variables and restarting your console window and such. The short version is to create symlinks to your java versions and then a single symlink called for example ‘active’ which points to the one you want. In your environment variables java_home and path you’d then point to this ‘active’ symlink instead of the actual installation. You can then fairly quickly swap out the target of the ‘active’ symlink and, tadaa’ish, you have a different version.

Setup

  1. Open up an elevated command prompt.
  2. Go/Make somewhere you want this.
    > c:
    > mkdir \dev\java
    > cd \dev\java
  3. Set up the symlinks
    > mklink /d 1.5 "c:\Program Files\Java\jdk1.5.0_22"
    > mklink /d 1.7 "c:\Program Files\Java\jdk1.7.0"
    > mklink /d 1.6 "c:\Program Files\Java\jdk1.6.0_27"
    > mklink /d active 1.7
  4. Set your JAVA_HOME and PATH environment variables. *
    setx JAVA_HOME "C:\dev\java\active" /m
    setx PATH "%JAVA_HOME%\bin;%PATH%" /m
* The second command assumes you don’t have Java in your PATH already. If you do, you should edit it the usual way instead. Also note that if JAVA_HOME is already set, it will be expanded in the second command.

Now open up a new regular command prompt and run the following.

> java -version
> mvn --version

Both (skip mvn if you don’t have maven installed) should report Java version 1.7.

Swapping

So, let’s say we want to change to java 1.5, we just need to run the following in an elevated command prompt.

> cd \dev\java
> rmdir active && mklink /d active 1.5

If you now repeat the version checks we did in our regular command prompt they should both report version 1.5 instead of 1.7. And we didn’t even have to restart the command prompt.

Shortcut

To prevent us from having to do this manually we could also create a simple bat file. I made one I called swap.bat which I put in the same directory as the symlinks with the following contents.

@echo off
cd \dev\java && rmdir active && mklink /d active %~1

You could then create a short cut to for example c:\dev\java\swap.bat 1.5, set it to run as administrator, and you’d have a two click solution to change the Java version to 1.5. I created one shortcut for each version.

If you have a better way, please leave a comment though. Always on the lookout for things and techniques that can make my developer life simpler :)

Sources and javadocs for Eclipse through Maven

Had a Maven project here which used Hibernate for database stuff. I’m kind of a newb when it comes to Hibernate and other Java libraries so I rely quite a bit on learning and discovery through the auto-completion and inline documentation in Eclipse. Problem was that when I edited this project, this auto-completion and documentation was very unhelpful. No documentation at all and parameter names of methods were just series of arg0, arg1, and so on. Quite annoying.

Download sources and javadocs

Turns out you need to tell maven to download this stuff in the pom.xml.

    <build>
        <plugins>
            ...
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    ...
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                    ...
                </configuration>
            </plugin>
            ...
        </plugins>

Then you just need to rebuild the Eclipse project files.

> mvn eclipse:clean eclipse:eclipse

After a refresh of the project in Eclipse you should now have a much more helpful auto-complete and inline java documentation :)

Generate sources and javadocs

Now if you have your own Maven repository with your own artifacts, the above steps will solve nothing since there (by default) won’t be any sources or javadocs to download. For your own artifacts that is. This requires telling Maven to actually generate these things for your artifact and then uploading those together with the regular jar file. This is how you do that:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.2.1</version>
    <executions>
        <execution>
            <id>attach-sources</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.9</version>
    <executions>
        <execution>
            <id>attach-javadocs</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

When you now run mvn package you should get your regular artifact and two more. One with the sources and one with the javadocs. Upload the regular artifact and attach those other two as well. When you then use the downloading config thing I mentioned first, you should now get javadocs and sources for your own artifacts as well.

Java: Simple XSLT transformation without external libraries

Here’s how to do a simple XSLT transformation using only classes in vanilla Java 1.5 (maybe even 1.4?), no external libraries or anything. The classes are found in the javax.xml.transform package.

// Create a factory
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXTransformerFactory.FEATURE))
    throw new RuntimeException("Did not find a SAX-compatible TransformerFactory.");
SAXTransformerFactory stf = (SAXTransformerFactory) tf;

// Create a reusable template for the XSLT
Templates xslt = stf.newTemplates(new SourceStream(inputStreamWithXslt));

// Use the template to transform some XML
templates.newTransformer().transform(
        new StreamSource(inputStreamWithXml),
        new StreamResult(System.out));

Source: XML and XSLT Tips and Tricks for Java

Java: Readable password generator

Needed something to generate random passwords and found Java Password Generator. It generates passwords which are gibberish, but still sort of readable, which I think is a lot nicer than pure gibberish.

I just wanted a simple ‘get me a new random password method’ though, and not all the applet and ‘make several passwords’ stuff. Decided to extract the useful parts and clean it up a bit. In case I need it again, or others need it, and since he states “share your source with others freely”, here is the result :)

Continue reading