Archive for January, 2009

URLConnection and https

Saturday, January 31st, 2009
with a java.net.URLConnection i can connect to any http server. it’s also possible to connect to an https server. if i connect to a https server with a browser i might get a message that the certificate is not trusted. i am prompted to examine the certificate and mark it as a trusted certificate. after that i can connect without any problems. the same must be done if i try to connect with an URLConnection. if we try to connect to an https server via URLConnection and the certificate is not trusted a javax.net.ssl.SSLHandshakeException is thrown with the message “PKIX path building failed”… at least for the sun jvm version 1.5.

add certificate to a KeyStore

first we need to download the certificate from the webserver. this can be done with firefox. if you accepted the servers certificate you can save the certificate by selecting: Edit->Preferences->Advanced->Encryption->View Certificates->Your Certificates here you need to select the certificate and then click on export. save it somewhere on your harddisk. with this certificate java cannot work directly… actually it can but it’s easier to transform it into a KeyStore file. with the command keytool -import -alias aliasOfCertifiate -file certificateFile.cer\ -keystore myKeystore the keytool program is distributed with a jdk. with the command we add the certificate certificateFile.cer as a trusted certificate to the keystore file named myKeystore. the tool prompts for a password. this password is used to encrypt the keystore file.
instead of adding the certificate to myKeystore we could also add it to the default keystore of the jvm. this is done with: keytool -import -alias aliasOfCertifiate -file certificateFile.cer\ -keystore $JAVA_HOME/lib/security/cacerts with the password “changeit”. this uses root privileges and it is the default setting of all java programs. it’s a bit like pollution of the “global” environment and it’s better to avoid this.

use that keystore

if i have an URLConnection with https as a protocol it’s an instance of HttpsURLConnection and i can simply cast to it. HttpsURLConnection has a method setSSLSocketFactory. this socketFactary can be configured to accept certain certificates or not. a socketFactory which accepts certificates in myKeystore can be created with the following code: InputStream in = new FileInputStream(new File("path/to/myKeystore")); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, "PasswordUsedWithKeytool".toCharArray()); in.close(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0]; SSLContext context = SSLContext.getInstance(”TLS”); context.init(null, new TrustManager[] {defaultTrustManager}, null); SSLSocketFactory sslSocketFactory = context.getSocketFactory(); here the keystore is loaded at first. you have to provide the password you typed in during creation of the keystore file. after that a TrustManager is created via a TrustManagerFactory initialised with our KeyStore. then the SSLContext is created and initialised with the trustManager. after that a SSLSocketFactory can be created by the getSocketFactory method of the SSLContext. we can use it for our URLConnection like following: URL url = new URL("https://thesecuredomain.org"); URLConnection con = url.openConnection(); ((HttpsURLConnection) con).setSSLSocketFactory(sslSocketFactory); con.connect(); in = con.getInputStream(); ...

jj1 webservice step by step

Friday, January 16th, 2009
we will create a little json-rpc webservice in java using jj1. it’s a step by step tutorial using a fresh install of tomcat and java. if you use an ide it should be easy to adabt it. the webservice will generate an ascii banner from a string. the code to generate the ascii banner exists already and just needs to be made accessible as a webservice.

what you need

you need a default tomcat installation and a jvm (java virtula machine). to test if a jvm is available just type java at the command prompt. if something like java version "1.6.0_07" Java(TM) SE Runtime Environment (build 1.6.0_07-b06) Java HotSpot(TM) Server VM (build 10.0-b23, mixed mode) apears you have one installed. otherwise download one from sun or use your package manager to install one. the easiest way to install tomcat is with your package manager if you use a linux like os. if there is no tomcat support take a look at the tomcat setup page.

directories

i usually create a main folder named after the project. in this folder there is a src folder for the java source, a bin folder for the compiled files and a dist folders for jars and wars. if it’s a webapp there is also a web folder which is the webapp. so for our little example app it looks like: asciiText asciiText/src asciiText/bin asciiText/dist asciiText/web asciiText/web/WEB-INF asciiText/web/WEB-INF/lib

dependencies

we need three jars. at first the jj1 jar. the next jar is the stringtree jar. this is used to encode/ decode json. as next we need the service implementation. save all the jars in the asciiText/web/WEB-INF/lib folder.

create the context object

to access a method via json-rpc we have to expose this method to the web. in jj1 this is done via a context object. this is our first… and only java class. we will create it in a ch/kerbtier/asciitext subfolder of the src folder. the ch/kerbtier/asciiws folders represent the namespace or package where the class lives in. the file should be named AsciiContext and look like: package ch.kerbtier.asciiws; import ch.kerbtier.asciitext.AsciiRenderer; import com.googlecode.jj1.server.JsonRpc; public class AsciiContext{ private AsciiRenderer renderer = new AsciiRenderer(); @JsonRpc public String getText(String input, String font, int size){ return renderer.createAscii(input, font, size); } } thats it. we publish the method getText (with the JsonRpc annotation) as a webservice. internally it just calls the createAscii method of the renderer.

web.xml

a webapplication is configured by a web.xml file which lives in the WEB-INF folder of a webapp. we need the following file: <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>AsciiText</servlet-name> <servlet-class>com.googlecode.jj1.server.Jj1Servlet</servlet-class> <init-param> <param-name>services</param-name> <param-value>root=ch.kerbtier.asciiws.AsciiContext</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>AsciiText</servlet-name> <url-pattern>/ascii</url-pattern> </servlet-mapping> </web-app> this instantiates a Jj1Servlet and loads an AsciiContext instance as a jj1 context and publishes its methods directly under the url ascii.

build the whole stuff

go to your asciiText directory and type: javac -d bin -classpath web/WEB-INF/lib/asciiGenerator.jar:\
web/WEB-INF/lib/jj1.0.1.jar src/ch/kerbtier/asciiws/AsciiContext.java
this compiles the AsciiContext file and places it into your bin directory into the proper package. with the -classpath option you specify the jar files with the classes inside AsciiContext depends on. on windows you need a ; as delimiter between classpath entries. jar cf dist/asciiws.jar -C bin ch this creates a jar file out of the class… it’s useful if you have lots of classes, with one it’s just habit. cp dist/asciiws.jar web/WEB-INF/lib/ copies the generated jar file into the lib folder of the webapp. jar cf dist/asciiws.war -C web WEB-INF this creates the file asciiws.war. now we just need to deploy it with tomcat. one easy way is to just copy it into the webapps folder. after that the webservice should be accessible trough the url http://localhost:8080/asciiws/ascii