Tag Archives: Java

Enable SQL logging in Play 2.5+

Just a note to self on how to get (in my case) IntelliJ to spit out all SQL statements happening during unit tests.

  1. Add the following to application.conf
  2. Add the following to logback.xml
    <logger name="org.jdbcdslog.ConnectionLogger" level="OFF"  />
    <logger name="org.jdbcdslog.StatementLogger"  level="INFO" />
    <logger name="org.jdbcdslog.ResultSetLogger"  level="OFF"  />

Source: StackOverflow

Java: Ignore SSL certificate errors

Not that we’d do such a thing of course, but here’s how to ignore all SSL certificate errors in Java.

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.*;

 * A {@link X509TrustManager} and {@link HostnameVerifier} which trust everything.
 * @author    Torleif Berger
 * @license   http://creativecommons.org/licenses/by/3.0/
 * @see       http://www.geekality.net/?p=2408

public final class TrustAllCertificates implements X509TrustManager, HostnameVerifier
    public X509Certificate[] getAcceptedIssuers() {return null;}
    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    public boolean verify(String hostname, SSLSession session) {return true;}
     * Installs a new {@link TrustAllCertificates} as trust manager and hostname verifier.

    public static void install()
            TrustAllCertificates trustAll = new TrustAllCertificates();
            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
                    new TrustManager[]{trustAll},
                    new java.security.SecureRandom());         

            // Install the all-trusting host verifier
        catch (NoSuchAlgorithmException e)
            throw new RuntimeException("Failed setting up all thrusting certificate manager.", e);
        catch (KeyManagementException e)
            throw new RuntimeException("Failed setting up all thrusting certificate manager.", e);



HttpURLConnection c = (HttpURLConnection) url.openConnection();
// ...and so on and so forth

Maven: Add 3rd party dependencies in project specific repository

Sometimes we need to use some commercial artifacts which are not available in the usual Maven repositories. These should of course be added to a repository hosted by your company or something like that, but sometimes it’s just simpler to stick those jars in the project directly and check them in with the rest of the code.

Found a nice way of doing that in the heroku devcenter documentation, so noting it down here for future reference.

Create repository

We’ll start with deploying an artifact to a repo folder in our project by using the following command. I split it up so it’s easier to read, but it should of course all be a single command.

mvn deploy:deploy-file

The group and artifact id you’d have to make up yourself of course. For example pull the artifact id from the library name and the group id from the main package used inside the library.

Remember to add this folder to your version control.

Define repository

Add the following to your pom.xml to let Maven know about the project repository we just created.


Define dependency

And finally just define the dependency in your pom.xml like you’d usually do.


Clean and simple.

Maven: Package runtime dependencies in lib folder inside packaged jar

When running mvn package, here’s how to end up with a lib folder inside the resulting jar file which contains all the runtime dependencies of your project. Just add the following to your pom.xml.


Works on my machine anyways. When I now open up the packaged jar archive I find a lib folder containing all jar dependencies, with the exception of those belonging to the scopes test and provided. Which is what I wanted. Score!!

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;
        s = new Socket(host, port);
        return true;
    catch (Exception e)
        return false;
        if(s != null)
            try {s.close();}
            catch(Exception e){}

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

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.


  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.


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.


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 🙂

Maven: Sources and javadocs for Eclipse

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.


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:


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.