Private Key PFX to/from JKS Conversion Using OpenSSL and Jetty

Recently I’ve been watching quite a few screencasts which seem to be a really fun way to learn something. This made me want to create something of my own. So for this blog post I’m putting up my first attempts at creating screencasts while trying to explain something useful.

What’s New in Tomcat 7

Recently I watched this webinar about Tomcat 7 presented by Mark Thomas and would like to share my thoughts on the subject and what I’ve learned.

Servlet 3.0

The most prominent change is the support of Servlet 3.0 specification which supports such great features as

  • asynchronous servlets – not used by default
  • web-fragment.xml –  you can specify parts of the configuration in your libraries which you plan to reuse

Improving Architecture with Structure 101

I want to share with you yet another tool this one will help you with the architecture development. The tool is called Structure 101 and you can download a trial version here. That’s right, this tool is not free, but it does it’s job really well and at the time I can’t think of a free alternative that would be just as good. If you do know any good alternative, please, do leave a comment. The first thing you need to do is chose the version that’s right for you. There are three main flavours:

  • JAVA – cross platform

Apache HTTP server (SSL) + Tomcat 6.x on Ubuntu and CentOS

The Environment

From time to time I need to do some Apache httpd + Tomcat installations on Linux servers and usually they come in different flavors. While you’re still experimenting it’s a good idea to use a pre-installed Linux on a virtual machine. I’m using the free VMware player to run virtual appliances, a list of which can be found on VMware page. Personally I like the clean Linux installations without any extras, this way you can install anything you need and create multiple virtual machines of the same Linux flavor with different purposes if you need to. My preferred versions are the Debian based Ubuntu 9.04 server and the CentOS which is a community-supported OS based on Red Hat Enterprise Linux. Sometimes you get a pre-installed server for development and you’re not sure what kind of Linux flavor is on it. Usually a simple uname -a helps, but sometimes it spits out something vague like

Taking over the Spring context from a neighbouring application on Tomcat

A little while ago I was developing a small application from which I wanted to reuse the Spring beans that are defined in a context of another application. I thought this might be useful for someone so here’s a short explanation of how I achieved this result. Both applications were deployed on Tomcat 6.0.18, but I don’t think that minor version number differences would have much of an impact on the technique. The core concept is quite simple – I gave one application the ability to access another application’s classpath, thus all the classes, Spring context and the beans. Let’s call the standard Spring-based application the victim and the application that will take over the context – rogue. There aren’t any specific requirements for the victim application, but I did put the context files in the classpath, not just the WEB-INF directory. The rogue application has two context files, one of them loaded by the Spring context listener is just a stub and contains no beans, but the other one tries to include the spring context file which belongs to the victimapplication:

SSH with Java

Recently I needed to do some server manipulation over the SSH-2 protocol from a Java client program. There are quite a few choices of SSH libraries for Java out there. Usually I prefer BSD license whenever possible, so I thought I’ll give Ganymed SSH-2 for Java a try. It turned out to be pretty simple to use. Here’s a short example of how to connect to the server using the private key and execute some command.

import java.io.*;
import ch.ethz.ssh2.*;

public class Example {
  public static void main(String[] args) throws IOException {
    Connection conn = new Connection("hostname");
    conn.connect();
    File pemKeyFile = new File("privKey.pem");
    boolean isAuth = conn.authenticateWithPublicKey("user", pemKeyFile, "keyPwd");
    if (isAuth == false) {
      throw new IOException("Authentication failed.");
    }

    Session sess = conn.openSession();
    sess.execCommand("netstat -nl | egrep ':80' | wc -l");
    InputStream inp = sess.getStdout();
    InputStreamReader reader = new InputStreamReader(inp);
    BufferedReader br = new BufferedReader(reader);
    String line = br.readLine();

    sess.close();
    conn.close();
  }
}

If you’re unfamiliar with private/public key authentication over SSH, see the links below or just google for “passwordless ssh login”.

iBatis and Stored Oracle procedures/functions

This one took me a while to get it right the first time. I won’t go into details of configuring iBatis datasources and such, and will go straight to putting some queries in the sqlMap file. Just let me note that I’m using iBatis 2.3 for these examples. I’ll start off with a procedure call.

<procedure id="getUserRoles" parameterMap="myParamMap">
    { call SCHEMA.GET_USERS_ROLES(?, ?) }
</procedure>

This one is pretty self-explanatory, just defining a procedure to be called. Notice the questionmarks in the SQL, don’t put the usual #variable# style annotation here. Also instead of parameterClass I use parameterMap here, which means I’ll have to define a parameter map for this query or it won’t work.

Certificate Generation with Java Tools

Java has a useful tool for generating private-public key pair, it’s called keytool and is located in your jdk/bin directory. Here’s a command line that I often use to generate keys and self-signed certificates for testing.

keytool -genkey -keyalg RSA -validity 365 -alias MyKey -keystore new_keystore.jks -dname "CN=SubjectName, OU=My Department, O=My Company, L=Vilnius, S=Vilnius, C=LT"

Also it is sometimes needed to generate a request to get a signed certificate. Having created a keystore as shown above, it is easily done with the following line.

keytool -certreq -alias MyKey -keyalg RSA -keysize 2048 -file myfile.csr -keystore new_keystore.jks

I realize that this is pretty trivial, but it’s nice to have it written down in case I forget something :)

Using maven

Maven is an awesome build tool for JAVA, but it has some long parameter names that I don’t like to remember, so I put my often used tasks of maven in batch files.

install.bat

mvn install:install-file -Dfile=%1 -DgroupId=%2 -DartifactId=%3 -Dversion=%4 -Dpackaging=pom -DgeneratePom=true

This installs the specified .jar file in the local repository located in

C:\Documents and Settings\*User*\.m2\repository

where *User* is your username. Four arguments are required: jar_file, group, artifact and version.

new.bat

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=%1 -DartifactId=%2

I use this one to create new projects for stand-alone java programs. Two arguments required: group and artifact.

webnew.bat

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=%1 -DartifactId=%2

This one creates a new project for a web application. Two arguments required: group and artifact.

More maven commands:

Strings in JAVA

A few days ago I needed to extract all strings from .java files and also thought that it would be a good idea to keep count how many times a string is used. So I came up with this simple python script. It’s kind of a quick and dirty solution, but it met my needs for the particular task.

import sys, os, re
from operator import itemgetter

files = []
strings = {}
exp = re.compile("(\".+?\")")

def klist(bdir):
    dir = os.listdir(bdir)
    for fname in dir:
        if fname.endswith(".java"):
            files.append(bdir+"\\"+fname)
        if os.path.isdir(bdir+"\\"+fname):
            klist(bdir+"\\"+fname)

def get_strings(fname):
    fp = open(fname)
    data = fp.readlines()
    fp.close()
    print fname[fname.rfind("\\")+1:]+":"

for line in data:
        k = 1
        while(k
            m = exp.search(line, k)
            if m!=None:
                fstr = m.groups()[0]
                print "    "+fstr
                cnt = 1
                if strings.has_key(fstr):
                    cnt = strings[fstr] + 1
                strings.update({fstr : cnt})
                k = m.end()
            else:
                k = len(line)

if __name__ == "__main__":
    if len(sys.argv)<2:
        print "Usage: get_strings.py base_directory"
        exit(-1);

klist(sys.argv[1])
    for fname in files:
        get_strings(fname)

print "-"*70
    di = strings.items()
    di.sort(key=lambda x: x[1])
    for (k, v) in di:
        print v, ":", k

So what this basically does is gather the strings and prints out strings for each file and then after a separator line it prints some usage stats. This might contain bugs, because I was in a hurry to write it, so if you use do it at your own risk ;)