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
    db.default.logSql=true
  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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()
    {
        try
        {
            TrustAllCertificates trustAll = new TrustAllCertificates();
           
            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null,
                    new TrustManager[]{trustAll},
                    new java.security.SecureRandom());         
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(trustAll);
        }
        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);
        }
    }
}

Usage

TrustAllCertificates.install();

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
    -Durl=file:///dev/project/repo/
    -Dfile=somelib-1.0.jar
    -DgroupId=com.example
    -DartifactId=somelib
    -Dpackaging=jar
    -Dversion=1.0

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.

<repositories>
    <repository>
        <id>project.local</id>
        <name>project</name>
        <url>file:${project.basedir}/repo</url>
    </repository>
</repositories>

Define dependency

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

<dependency>
    <groupId>com.example</groupId>
    <artifactId>somelib</artifactId>
    <version>1.0</version>
</dependency>

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.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
                        <includeScope>runtime</includeScope>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

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;
    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 🙂

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.

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