Posts tagged: java

Create a Java Keystore

To create a Java keystore file – the minimum

keytool -genkey -alias tomcat -keyalg RSA -keystore /keystore-location -storepass password

You can answer anything to the questions if this is just for internal, development use. Keystore location is typically ~/.keystore.

Note that this merely creates the file. Doesn’t do anything about putting certificates in it.

Javadoc standards

Java coding standards

See http://java.sun.com/javase/6/docs/technotes/tools/windows/javadoc.html

See also http://java.sun.com/j2se/javadoc/writingdoccomments/index.html

All elements are required unless noted

Copyright at start of file

- Optional for internal code
- Required for open-sourced components

Class header

The documentation immediately precedes the class decleration.

/**
* Class description
*
* @author Tracy Flynn
* @since Version 1.0
*/

Can contain in-line HTML, Javadoc keywords

Variables

Public variables must be documented
Private variables should be documented

Methods

Methods must be documented. The documentation immediately precedes the method declaration.

/**
* Method description
*
* @param [param name] Brief parameter description
* @return Brief description of possible return values
* @throws [exception class] Brief description of case(s) where exception is thrown
*/

Javadoc comment structure

/**
* Summary sentence
*
* Additional text
*
* Block tags
*/

The summary sentence is used in the method summary. It is terminated by a period followed by whitespace or by a block tag.

Javadoc tags

Commonly used tags – see the reference given earlier for a complete list

Block tags

@author
@deprecated
@return
@see
@since
@throws

In-line tags

@code
@link

Create and test a simple Java project with Maven and Intellij

How to create and test a simple Java project with Maven and Intellij.

Step 1

Use maven to create the project skeleton.

Either

mvn archetype:generate

and pick Option 15 – maven-archetype-quickstart

Or

mvn org.apache.maven.plugins:maven-archetype-plugin:1.0-alpha-7:create \
    -DgroupId=net.olioinfo \
    -DartifactId=java_simple \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DarchetypeGroupId=org.apache.maven.archetypes

Step 2

  • Import into Intellij as a Maven project.
  • Make sure that the SDK is set to a JAVA SDK
  • On the Run menu, edit the Configurations to add a Junit test suite
    • Select ‘Test all in package’
    • Specify package
    • Pick the top-level project directory as the working directory
    • Ensure that ‘Make’ and ‘Build artifacts’ are checked
    • Save
  • The top two entries on the Run menu are now available
    • The top ‘Run’ menu entry will run the last configuration applied
    • The top ‘Debug’ menu entry will debug the last configuration applied
  • Maven introduces two more entries below the top two entries on the Run menu
    • ‘Run’ will run the configured maven goal (from the last configuration applied).
    • ‘Debug’ should run maven in debug mode. Doesn’t seem to work
  • All the standard maven targets work from command line. They will also function when included in an Intellij run-time configuration.

Intellij Idea 9 – Building a Java webapp + missing dependencies

To build a Java webapp in Intellij Idea 9. follow the standard procedure documented in various places (to be supplied).

When the sample classes are examined, there will be undefined dependencies or imports for all the servlet – and any other J2EE – dependencies.

This is a change from Intellij 8, which included the J2EE libraries as compile-time options. To correct this there are two choices:

  • Java 5  – Use the attached java 5 – J2EE jar and add as a compile-time dependency (taken from Intellij 8 )
  • Java 6 – Use the attached java6 EE jars and add as a compile-time dependency (taken from glassfish v3 dependencies)

Java – Resources and Properties

This article is part of the Java – From the ground up series. This article is mostly summarized from here.

Resource files

Roughly speaking, any file that a Java application needs that isn’t a class file can be thought of as a resource  file.

At its simplest, Java applies the same rules for loading a resource as it does for loading a class – that is uses the Java classpath and class loaders. This typically requires that the resource be included in a JAR file or a WAR file for a web application.

Resource bundles and internationalization (i18n)

Resources are used for a lot things – internationalization being one of them.  The basic idea to is to collect a group of settings that relate to these features:

  • Locales
  • Number formats
  • Data and time
  • Collation order
  • Message formats
  • Messages

The ‘bundle’ notion comes in when the settings for these features are goupred into one or more files. This file or group of files is termed a resource bundle.  Each locale that is supported must have its own resource bundle. A specific naming convention is used for all the files associated with a given locale. Refer to standard documentation for a description of the naming convention and search conventions.

Properties files

.properties files are used in two basic ways:

  • To store strings for internationalization support
  • To store general application-level settings

The second usage for .properties files – application-level settings -  typically doesn’t exploit the locale support described above, even though it is still used ‘under the covers’ to load the .properties file.

There are several aspects of the plain text format for properties files to watch out for:

  • Entries consist of  key/value pairs
  • Both keys and values are treated as Strings
  • The naming of keys uses a ‘flat’ namespace – all keys exist in the same namespace
  • All keys within a namespace must be unique

That leads to properties files that look similar to the following:

first.property=1
second.property=2
apropertylist.entry.1=a
apropertylist.entry.2=b

An alternative that removes some of these limitations is to use an XML format for properties files.

Java – log4j configuration

Log4j is a widely-used Java logging package.

How does Log4j find configuration information?

From the Log4j Manual – Default initialization procedure

The log4j library does not make any assumptions about its environment. In particular, there are no default log4j appenders. Under certain well-defined circumstances however, the static inializer of the Logger class will attempt to automatically configure log4j. The Java language guarantees that the static initializer of a class is called once and only once during the loading of a class into memory. It is important to remember that different classloaders may load distinct copies of the same class. These copies of the same class are considered as totally unrelated by the JVM.

The default initialization is very useful in environments where the exact entry point to the application depends on the runtime environment. For example, the same application can be used as a stand-alone application, as an applet, or as a servlet under the control of a web-server.

The exact default initialization algorithm is defined as follows:

  1. Setting the log4j.defaultInitOverride system property to any other value then “false” will cause log4j to skip the default initialization procedure (this procedure).
  2. Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value “log4j.properties”.
  3. Attempt to convert the resource variable to a URL.
  4. If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string “log4j.properties” constitutes a malformed URL. See Loader.getResource(java.lang.String) for the list of searched locations.
  5. If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL. The PropertyConfigurator will be used to parse the URL to configure log4j unless the URL ends with the “.xml” extension, in which case the DOMConfigurator will be used. You can optionaly specify a custom configurator. The value of the log4j.configuratorClass system property is taken as the fully qualified class name of your custom configurator. The custom configurator you specify must implement the Configurator interface.

From the Log4j Manual – Default initialization under Tomcat

The default log4j initialization is particularly useful in web-server environments. Under Tomcat 3.x and 4.x, you should place the log4j.properties under the WEB-INF/classes directory of your web-applications. Log4j will find the properties file and initialize itself. This is easy to do and it works. You can also choose to set the system property log4j.configuration before starting Tomcat. For Tomcat 3.x The TOMCAT_OPTS environment variable is used to set command line options. For Tomcat 4.0, set the CATALINA_OPTS environment variable instead of TOMCAT_OPTS. Example 1

The Unix shell command

   export TOMCAT_OPTS="-Dlog4j.configuration=foobar.txt"

tells log4j to use the file foobar.txt as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. The file will be read using the PropertyConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

Example 2

The Unix shell command

   export TOMCAT_OPTS="-Dlog4j.debug -Dlog4j.configuration=foobar.xml"

tells log4j to output log4j-internal debugging information and to use the file foobar.xml as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Since the file ends with a .xml extension, it will read using the DOMConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

Example 3

The Windows shell command

   set TOMCAT_OPTS=-Dlog4j.configuration=foobar.lcf -Dlog4j.configuratorClass=com.foo.BarConfigurator

tells log4j to use the file foobar.lcf as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Due to the definition of the log4j.configuratorClass system property, the file will be read using the com.foo.BarConfigurator custom configurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

Example 4

The Windows shell command

   set TOMCAT_OPTS=-Dlog4j.configuration=file:/c:/foobar.lcf

tells log4j to use the file c:\foobar.lcf as the default configuration file. The configuration file is fully specified by the URL file:/c:/foobar.lcf. Thus, the same configuration file will be used for all web-applications.

Different web-applications will load the log4j classes through their respective classloaderss. Thus, each image of the log4j environment will act independetly and without any mutual synchronization. For example, FileAppenders defined exactly the same way in multiple web-application configurations will all attempt to write the same file. The results are likely to be less than satisfactory. You must make sure that log4j configurations of different web-applications do not use the same underlying system resource.

Initialization servlet

It is also possible to use a special servlet for log4j initialization. Here is an example,

package com.foo;

import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.IOException;

public class Log4jInit extends HttpServlet {

  public
  void init() {
    String prefix =  getServletContext().getRealPath("/");
    String file = getInitParameter("log4j-init-file");
    // if the log4j-init-file is not set, then no point in trying
    if(file != null) {
      PropertyConfigurator.configure(prefix+file);
    }
  }

  public
  void doGet(HttpServletRequest req, HttpServletResponse res) {
  }
}

Define the following servlet in the web.xml file for your web-application.

  <servlet>
    <servlet-name>log4j-init</servlet-name>
    <servlet-class>com.foo.Log4jInit</servlet-class>

    <init-param>
      <param-name>log4j-init-file</param-name>
      <param-value>WEB-INF/classes/log4j.lcf</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

Writing an initialization servlet is the most flexible way for initializing log4j. There are no constraints on the code you can place in the init() method of the servlet.

Java – Class loaders

This article is part of the Java – From the ground up series. This article is mostly summarized from here and here.

Java Class loaders and why they’re important.

Every class that’s loaded into a JVM is loaded by a class loader.  So, class loaders are significant, and knowing about them is important.

The most important thing from the point of any class, is that, once it’s been loaded, the JVM assigns it a unique identifier based on the combination of the specific class loader and the class itself. So, the golden rule::

  • Two copies of the same class loaded by separate class loaders are considered distinct by the JVM.

Class loader hierarchy

Class loaders exist in a strict hierarchy:

  • The bootstrap class loader
  • The extension class loader
  • The system class loader (a.k.a. the application class loader)
  • Specific class loaders in an application

The class  loader that is most relevant at the application level is the system class loader.

  • If specific application-level class loaders are not specified, all classes in an application context are loaded by the system classloader.
  • If no parent is specified for a given class loader, the system class loader is implied as the parent

Creating a class loader

The basic design rule for a class loader is simple:

  • Extend the  system class loader
  • Let the system class loader try to load the class first (this is usually automatic)
  • Override the findClass(String className) method

Threads and class loaders

Every thread has a reference to a class loader, known as its context class loader.

  • The main thread starts off with the system class loader
  • When a subsequent thread is created, its context class loader is set to the context class loader of the creating thread unless overridden.

Java – From the ground up

This is the starting point for a set of Java-related topics. These are mostly topics that need clarifications in a lot of cases.

Java and Classpath

Java and Class loaders

Java – Resources and Properties

References for this series ‘Java – From the ground up’

OpenID server

Notes on OpenID server 1.2.0

Installation

jos-1.2.0> mvn install

Missing dependency – net.tanesha.recaptcha4j:recaptcha4j:jar:0.0.7

Found at: http://code.google.com/p/recaptcha/downloads/detail?name=recaptcha4j-0.0.7.zip&can=2&q=label%3Ajava-Latest

  • Unpack
  • mvn install

jos-1.2.0> mvn install

cannot find symbolsymbol  : method authResponse(org.openid4java.message.AuthRequest,java.lang.String,java.lang.String,boolean,boolean)

See http://code.google.com/p/openid-server/issues/detail?id=4

svn checkout http://openid4java.googlecode.com/svn/trunk/ openid4java-read-onlycd openid4java-read-only/maven2mvn install

And thence to dependency hell.

OS X Java Versions

OS X uses a weird and wonderful structure for Java components that allows multiple versions of Java to coexist happily on the same system. Depending on what you want to do, choosing between them can create challenges.

Apple references that were useful compiling this article:

Thanks also go to various others who have already plumbed the mysteries of OS X and Java.

OS X Directory Structure

OS X places all kinds of Java components in the directory structure starting at:

/System/Library/Frameworks

The component that’s of particular interest for this discussion is the JavaVM itself. That structure starts at:

/System/Library/Frameworks/JavaVM.framework

Each distinct Java version has a directory in

/System/Library/Frameworks/JavaVM.framework/Versions

Here’s a sample from my machine

lrwxr-xr-x   1 root  wheel     5B Aug 31 21:35 1.3 -> 1.3.1
drwxr-xr-x   3 root  wheel   102B Jul 20 19:35 1.3.1
lrwxr-xr-x   1 root  wheel     5B Nov 26 03:43 1.5 -> 1.5.0
drwxr-xr-x   8 root  wheel   272B Jan  2  2007 1.5.0
lrwxr-xr-x   1 root  wheel     5B Aug 31 21:35 1.6 -> 1.6.0
drwxr-xr-x   8 root  wheel   272B Oct 18 08:31 1.6.0
drwxr-xr-x   9 root  wheel   306B Oct 18 08:31 A
lrwxr-xr-x   1 root  wheel     1B Aug 31 21:35 Current -> A
lrwxr-xr-x   1 root  wheel     3B Aug 31 21:35 CurrentJDK -> 1.6

There are several interesting points about the subdirectories managed here.

  • The primary release (e.g ’1.5′) is always a link to the corresponding current ‘dot’ or ‘subrelease’ for that version (e.g ’1.5.0′)
  • ‘CurrentJDK’ is linked to whatever is the currently active Java JDK Version
  • ‘Current’ is linked to the currently selected Java SE version

There are several levels of indirection involved. You can stop here if you don’t need a further information or a bad headache. In this excursion, I’ll deal with the 1.6 (Java 6) trajectory.

  • ‘./Current’ is linked to ‘./A’
    • ‘./A’ appears to encompass both Java SE elements and Java JDK elements
    • ‘./A/Commands’ appears to contain JSE binaries
    • ‘./A/Headers’  appears to contain JDK headers
  • ‘./1.6.0′ links to ‘/System/Library/Frameworks/JavaVM.framework/Home’
    • ‘Home’  appears to have JDK binaries fot the specified (default?) version  (debug versions?)

This all serves to set the scene for the most interesting link from the point of view of daily use – ‘/Library/Java/Home’:

/Library/Java/Home -> /System/Library/Frameworks/JavaVM.framework/Home
/System/Library/Frameworks/JavaVM.framework/Home ->
/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home

This is the directory that Apple recommends using to set the ‘JAVA_HOME’ variable – beloved of the Java world, and required to get almost anything Java-based to work.

export JAVA_HOME=/Library/Java/Home
export PATH=${JAVA_HOME}/bin:${PATH}

Java Versions

Changes that affect everything on the system

If you want to change the Java version for everything on the system, you can do so with the Java Preferences application

/Applications/Utilities/Java Preferences

On the ‘General’ tab, follow the instructions to change the selection.

osx-javapreferences-general

If the version you want doesn’t appear on the list, you need something more radical (To be supplied).

Changes that affect the specific command you’re running

The Apple-sanctioned way to run a specific Java version from the command line is simple.  This deliberately does not involve changing the Java Preferences.

These changes shown below will only apply for the lifetime of the (bash) shell in which they are used. Using the setup illustrated above for my machine:

export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.5/Home
$JAVA_HOME/bin/java

This technique has been tested successfully in two environments:

  • Clean Snow Leopard install – Defaults to Java 1.6 – with manual install of Java 1.5 to run Java 1.5
  • Existing Leopard – default Java 1.5 installation – with manual install of Java 1.6 – to run Java 1.6

WordPress Themes