tag:blogger.com,1999:blog-81559677851196274152024-03-14T10:18:21.415+01:00Java EE NotesOnline blog of a Java EE Developer.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.comBlogger98125tag:blogger.com,1999:blog-8155967785119627415.post-8677409425419284412014-12-16T21:25:00.000+01:002014-12-16T21:32:47.604+01:00FreeBSD on Raspberry Pi B+<p>
It has been almost 10 years since I ran my own UNIX-like server at home. The last Debian machine died because of hardware failures. It was an old Pentium II machine. It started itching again a week ago. I wanted to run a server at home 24/7 at a very low cost. It would also be a great opportunity to refresh my C programming skills again.
</p>
<p>
I you think about low cost, then <a href="http://www.raspberrypi.org">Raspberry Pi</a> would undoubtedly come to mind. It's a very small but capable device. The costs of running it 24/7 is about 5 EUR per year. So I looked around online, and finally bought the model B+ with a nice translucent casing, a 1A power adapter, an HDMI cable, and a SanDisk Extreme 16GB MicroSD card. The total costs for the complete server setup: 70 EUR.
</p>
<iframe src="https://www.flickr.com/photos/glcheng/16036605765/player/" width="500" height="333" frameborder="0" allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>
<p>
Now I had the hardware set. Next, I needed to select a nice OS image to put on the memory card. I narrowed it down to Raspbian, and FreeBSD. Raspbian is based on Debian, which I’m very familiar with. I've been running Debian for years. I really like their packaging system, and the minimal install. But I really wanted something closer to UNIX than Linux, so I went for FreeBSD.
</p>
<h1>Installation</h1>
<p>
Lucky me, the latest release supports Raspberry Pi. So I downloaded the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/releases/arm/armv6/ISO-IMAGES/10.1/">image</a> (FreeBSD-10.1-RELEASE-arm-armv6-RPI-B.img) from their site. This is how I put the FreeBSD image on the memory card. I used Mac OS X to do it. On the Mac, I changed to the root user, so I’m allowed to write to a device directly.
</p>
<pre class="brush: shell">
sudo su -
</pre>
<p>
(Yes, you can also do "su", but SyntaxHighlighter rendered that command invisible.)
Now I needed to determine the name of our memory card device. So I executed the following command, before inserting the memory card.
</p>
<pre class="brush: shell">
diskutil list
</pre>
<p>
I memorized the list, and inserted the memory card. Now I executed the previous command again and checked that there is a new device in the list. This would then be my memory card device. On my computer, it was the “/dev/disk1” device. Now I unmounted the file system cleanly with:
</p>
<pre class="brush: shell">
diskutil unmountDisk /dev/disk1
</pre>
<p>
Now I wrote the FreeBSD image directly to disk with the next command. Please be careful, and make sure the device is correct. Otherwise you risk damaging the existing file system used by your computer!
</p>
<pre class="brush: shell">
dd if=FreeBSD-10.1-RELEASE-arm-armv6-RPI-B.img of=/dev/disk1 bs=1m
</pre>
<p>
After this, I ejected the card:
</p>
<pre class="brush: shell">
diskutil eject /dev/disk1
</pre>
<p>
Now I inserted the memory card in the Raspberry Pi, and I connected the HDMI cable to my TV. The moment of truth: connect the USB power supply, and see if it boots!
</p>
<p>
Unfortunately, my TV screen remained black. So I double checked the cables and screen settings, but to no avail. FreeBSD didn’t boot. After some Google research, I found out there was probably something wrong with the boot/firmware files. So I replaced the following files on my memory card with the files downloaded from: <a href="https://github.com/kientzle/crochet-freebsd/tree/master/board/RaspberryPi/boot">https://github.com/kientzle/crochet-freebsd/tree/master/board/RaspberryPi/boot</a>
<ul>
<li>bootcode.bin
<li>fixup.dat
<li>fixup_cd.dat
<li>start.elf
<li>start_cd.elf
</ul>
</p>
<p>
That did the trick, Raspberry Pi booted successfully to a FreeBSD login prompt!
</p>
<h1>Post installation tasks</h1>
<p>
To be able to be root, I needed to be member of the “wheel” group:
</p>
<pre class="brush: shell">
pw user mod gin -G wheel
</pre>
<p>
I also wanted the system date to be automatically synced. So I enabled the time daemon:
</p>
<pre class="brush: shell">
tzsetup (set local time zone)
echo 'ntpd_enable="YES"' >> /etc/rc.conf
echo 'ntpd_sync_on_start="YES"' >> /etc/rc.conf
service ntpd start
</pre>
<p>
There are no binary packages available, but there is an alternative called “portsnap”. With portsnap you basically download a directory structure of all packages available. Go into the directory of the port you want, and execute the makefile in the directory to automatically download and install the port.
</p>
<p>
To install portsnap run:
</p>
<pre class="brush: shell">
portsnap fetch
portsnap extract
portsnap fetch
portsnap update
</pre>
<p>
With portsnap I successfully compiled and installed the following programs:
<ul>
<li>screen
<li>git
<li>subversion
<li>wget
<li>autoconf
<li>automake
<li>libtool
</ul>
</p>
<h2>References:</h2>
<p>
<ul>
<li><a href="http://www.raspberrypi.org">http://www.raspberrypi.org</a>
<li><a href="http://www.freebsd.org">http://www.freebsd.org</a>
<li><a href="http://www.raspberrypi.org/forums/viewtopic.php?f=85&t=30148">http://www.raspberrypi.org/forums/viewtopic.php?f=85&t=30148</a>
<li><a href="http://vzaigrin.wordpress.com/2014/04/20/porting-applications-to-freebsd-on-raspberry-pi/">http://vzaigrin.wordpress.com/2014/04/20/porting-applications-to-freebsd-on-raspberry-pi/</a>
</ul>
</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com5tag:blogger.com,1999:blog-8155967785119627415.post-33482623553876185932014-03-05T10:12:00.000+01:002014-03-05T10:12:33.296+01:00Restore/Setup Android project without IDESometimes when the Android project directory is broken, you can restore the structure using the android executable in the Android "tools" directory.
<pre>
android update project -p <path_to_project_directory> -n <project_name> -t <android_sdk_version>
</pre>
You can also create a new project with:
<pre>
android create project -p <path_to_project_directory> -n <project_name> -k <package_name> -a <activity_name> -t <android_sdk_version>
</pre>
The android version parameter looks like this: "android-18".Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com14tag:blogger.com,1999:blog-8155967785119627415.post-69465856116229196322013-04-11T10:02:00.000+02:002013-04-11T10:02:37.546+02:00Package by featuresA must-read about how to divide your Java application into packages that are modular and highly cohesive:
<a href="http://www.javapractices.com/topic/TopicAction.do?Id=205">http://www.javapractices.com/topic/TopicAction.do?Id=205</a>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-10564269857164901762013-02-07T11:07:00.000+01:002013-02-09T13:20:34.311+01:00Solution for jQuery plugin conflicts in Wicket<p>
While I was working on a web application based on Wicket, I noticed that jQuery was not functioning in a way I expected. Using FireBug I noticed that a method call to a jQuery plugin failed, because it couldn't find the method. The HTML code I used in the <head>-element looks like this:
</p>
<pre class="brush:html;">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-plugin.js"></script>
<script type="text/javascript">
function callbackToPlugin() {
return function () {
$('#plugin').callToPlugin();
};
}
</script>
</pre>
<p>
The code-fragment includes the jQuery file and the custom plugin file. A function is defined below that returns a callback function that calls the plugin. The code in a Wicket web page class, decides if this callback is used or not. In the code below, the call is rendered in the <head>-element, when the boolean variable "callPlugin" is true.
</p>
<pre class="brush:java;">
@Override
public void renderHead(IHeaderResponse response) {
if (callPlugin) {
response.render(
OnDomReadyHeaderItem.forScript("$(document).ready(callbackToPlugin())"));
}
}
</pre>
<p>
The problem with this code is that Wicket includes its embedded jQuery file in the HTML output automatically, when it detects certain JavaScript function provided by Wicket is used. In this case it includes the jQuery file AFTER the definition of the callback function. What happens is that the definition of the plugin method "callToPlugin" is lost, because the second inclusion of jQuery resets the "$" jQuery variable. This will make our call fail.
</p>
<p>
The easiest solution I found is to assign another variable to jQuery using the "jQuery.noConflict()" function.
</p>
<pre class="brush:html;">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-plugin.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
function callbackToPlugin() {
return function () {
$j('#plugin').callToPlugin();
};
}
</script>
</pre>
<p>
Now, the jQuery variable is "$j" instead of "$". Make sure you call the correct method from the Wicket page.
</p>
<pre class="brush:java;">
@Override
public void renderHead(IHeaderResponse response) {
if (callPlugin) {
response.render(
OnDomReadyHeaderItem.forScript("$j(document).ready(callbackToPlugin())"));
}
}
</pre>
<p>
If you have a better solution for this, please let me know in the comments.
</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-56398806282272434992012-11-05T11:58:00.000+01:002013-02-09T13:21:24.258+01:00Login twice in WicketSince the last time I upgraded my Wicket application, I noticed I had to login twice to be authenticated in the application. After careful research using the number one research tool (Google), I found the cause of this problem.
The problem is that my login page is stateless. Wicket will create a temporary dummy session for stateless pages, which will not be saved internally in the session store.
The solution is to let the session stick after authentication by calling bind in the session:
<pre class="brush:java;">
@Override
public boolean authenticate(String userName, String password) {
// Your authentication code here...
// Only reach this when authenticated...
if (isTemporary()) {
bind();
}
}
</pre>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-23211962282811538372012-11-03T19:56:00.000+01:002013-02-09T13:21:56.378+01:00Reload JQuery when DOM is changed by Wicket/AJAXI'm using many jQuery plugins in my Wicket application. When Wicket AjaxBehaviors change the DOM of the page, the initial changes made by the jQuery plugins are often lost. To solve this, we have to initiate the jQuery plugins again when the AjaxBehavior executes. We can do that by appending the plugin initialization JavaScript code like below:
<pre class="brush:java;">
aTextField.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
target.add(aContainerThatIsRefreshed);
target.appendJavaScript("$('.jQueryPluginClass').initiatePlugin();");
}
});
</pre>
Change the ".jQueryPluginClass" CSS class, and ".initiatePlugin()" plugin call for your specific project.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-56324765493525288942012-08-04T14:07:00.002+02:002012-08-04T14:07:32.314+02:00Java Collection Matrix<p>
Looking for a Java Collection class for your project, but don't know which one to use or is available? The link below will take you to a Java Collection Matrix, which lists the summarized properties of the standard Java Collection implementations.
</p>
<a href="http://www.janeve.me/articles/which-java-collection-to-use">http://www.janeve.me/articles/which-java-collection-to-use</a>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com2tag:blogger.com,1999:blog-8155967785119627415.post-76907112248975636812012-07-26T13:41:00.002+02:002013-02-09T13:25:35.226+01:00Custom Wicket FeedbackPanel markupI had to add custom static markup to the Wickets FeedBackPanel for a project I'm currently working on. The markup has to be visible only when the the feedback panel itself is visible. The easiest way to do this is to extend the original class, and provide a corresponding HTML file with the custom markup.
<pre class="brush:java">package com.javaeenotes;
import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
public class ErrorPanel extends FeedbackPanel {
private static final long serialVersionUID = 1L;
public ErrorPanel(String id, IFeedbackMessageFilter filter) {
super(id, filter);
}
public ErrorPanel(String id) {
super(id);
}
}
</pre>
<pre class="brush:html">
<wicket:panel>
<div class="feedbackPanel" wicket:id="feedbackul">
<b>Error</b>
<div class="errorlevel" wicket:id="messages">
<span class="errorlevel" wicket:id="message">A message</span>
</div>
</div>
</wicket:panel>
</pre>
The HTML file is basically the same as the original file. I added an error header as an example.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-76173559455779895522012-05-02T18:20:00.000+02:002013-02-09T13:32:20.458+01:00Configurable, and modular Java classes using Annotations and Enumerations<p>
In todays blog post, I'm showing how I implemented highly configurable, and modular classes with the help of annotations, and enumerations. From now on, let's call these modular classes "modules". Let's suppose we have the following architectural problem:
</p>
<ol>
<li>There is a need for modules that are highly configurable.
<li>The modules implement the same interface.
<li>The configuration parameters vary.
<li>Some configuration parameters are required.
<li>Some configuration parameters have a default value.
<li>A configuration parameter should have an explanation for the enduser.
<li>It should also be easy to add new modules.
</ol>
<h2>UML Class Diagram</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-ZsrL_S4jXTk/T6FJg_iQjUI/AAAAAAAACps/0GRibBP8Wsk/s1600/configurable_modules.png" imageanchor="1" style=""><img border="0" height="236" width="400" src="http://3.bp.blogspot.com/-ZsrL_S4jXTk/T6FJg_iQjUI/AAAAAAAACps/0GRibBP8Wsk/s400/configurable_modules.png" /></a></div>
<h3>ModuleFactory and ModuleFactoryImpl</h3>
<p>
The module factory is responsible for creating a configured module. It takes the class name, and Properties object as parameters. I'm using a class name here instead of a class type, because the list of supported modules are stored in the database as names. The Properties object contains the configuration for the module to be created.
</p>
<h3>ModuleType</h3>
<p>
This enumeration is basically a list of supported types by the factory. When a new module is implemented, it should be added to this enumeration, otherwise the factory doesn't know how to translate the class name to the actual class. I tried to find a way to avoid the need of this enumeration, like searching in the class path for classes that correspond to the name. Unfortunately, this is too complex to achieve without adding a lot of boilerplate code. If you find a better way to solve this problem, please let me know in the comments.
</p>
<h3>Module</h3>
<p>
This interface formalizes the methods implemented by all modules. Their parameters are defined in an enumeration of type ModuleParameter. Every module should have a corresponding ModuleParameter enumeration. An example implementation for this demo is called "ExampleModule", and it uses "ExampleModuleParameter" to define its configuration.
</p>
<h3>ModuleParameter</h3>
<p>
This interface specifies the required methods for every subclass enumeration implementation. The enumeration is basically a list of configuration parameters for a module. Per configuration parameter, it also defines: if the parameter is required, the default value, and a brief explanation. An example implementaton for this demo is called "ExampleModuleParameter", and it has two configuration parameters.
</p>
<h2>The Implementation</h2>
<h3>ModuleParameter</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
// This interface enforces required methods for the parameter enumerator.
public interface ModuleParameter {
boolean isRequired();
String getDefaultValue();
String getExplanation();
}
</pre>
<p>This interface defines the methods used to retrieve the properties of the configuration parameter.</p>
<h3>ExampleModuleParameter</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
// This enum class contains the parameters used to configure a module.
public enum ExampleModuleParameter implements ModuleParameter {
PARAM1("param1", true, "DEFAULT", "This is parameter 1."),
PARAM2("param2", false, null, "This is parameter 2.");
// Code below is boiler plate code. It is not possible to move the
// code to an abstract class, because enumerators are not allowed
// to extend classes.
private final String name;
private final boolean isRequired;
private final String defaultValue;
private final String explanation;
private ExampleModuleParameter(
String name,
boolean isRequired,
String defaultValue,
String explanation) {
this.name = name;
this.isRequired = isRequired;
this.defaultValue = defaultValue;
this.explanation = explanation;
}
@Override
public String toString() {
return name;
}
@Override
public boolean isRequired() {
return isRequired;
}
@Override
public String getDefaultValue() {
return defaultValue;
}
@Override
public String getExplanation() {
return explanation;
}
}
</pre>
<p>
Everything you should know about the specific parameters is defined here, and nowhere else (high cohesion)! It forces the developer who is adding new parameters to define the extra properties as required.
</p>
<p>
I tried to eliminate the boiler plate code, by moving them to a shared abstract enumeration class, but that is not possible. Now we have to copy the same code for every new "ModuleParameter" implementation. Is there a better solution for this?
</p>
<h3>Module</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
public interface Module {
void doBusinessStuff();
}
</pre>
<p>Just the interface of a module, containing a common method.</p>
<h3>ExampleModule</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
// Annotate this module with parameter class that contains the
// configurable parameters for this module.
@ParameterClass(parameterClass = ExampleModuleParameter.class)
public class ExampleModule implements Module {
private String param1;
private String param2;
@Override
public void doBusinessStuff() {
System.out.println("Hello, I am "
+ this.getClass().getSimpleName()
+ ". I am configured with param1='" + param1
+ "', and param2='" + param2 + "'.");
}
public void setParam1(String param1) {
this.param1 = param1;
}
public void setParam2(String param2) {
this.param2 = param2;
}
}
</pre>
<p>This is an example implementation of a module. As you can see, it's just a POJO, making it very easy to write new ones. The class is linked to its parameter class using the annotation placed just before the class definition. The attributes and setters are important here. The names must correspond with the names defined in the parameter class.</p>
<h3>ParameterClass</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Only usable on classes.
@Target(ElementType.TYPE)
// Annotation must be available during runtime.
@Retention(RetentionPolicy.RUNTIME)
public @interface ParameterClass {
Class<? extends ModuleParameter> parameterClass();
}
</pre>
<p>This is the annotation, which links the module to its parameter class. The factory uses this annotation to find out which configuration values to set.</p>
<h3>ModuleType</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
// This is basically a list of supported modules by the factory.
public enum ModuleType {
EXAMPLE_MODULE(ExampleModule.class);
private Class<? extends Module> moduleClass;
private ModuleType(Class<? extends Module> moduleClass) {
this.moduleClass = moduleClass;
}
public Class<? extends Module> getModuleClass() {
return moduleClass;
}
}
</pre>
<p>This enumeration is a list of supported modules. The purpose of this enumeration is to map the name to its class type. This information is required by the module factory to instantiate the correct module class.</p>
<h3>ModuleFactory</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
import java.util.Properties;
public interface ModuleFactory {
Module getModule(String moduleName, Properties configuration)
throws Exception;
}
</pre>
<p>The interface of the module factory. It requires the class name, and a "Properties" object containing the configuration of the module.</p>
<h3>ModuleFactoryImpl</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class ModuleFactoryImpl implements ModuleFactory {
private Map<String, ModuleType> nameToModuleType;
public ModuleFactoryImpl() {
// The Map contains all the supported module types.
nameToModuleType = new HashMap<String, ModuleType>();
for (ModuleType moduleType : ModuleType.values()) {
nameToModuleType.put(
moduleType.getModuleClass().getSimpleName(),
moduleType);
}
}
@Override
public Module getModule(String moduleName, Properties configuration)
throws Exception {
if (nameToModuleType.containsKey(moduleName)) {
ModuleType moduleType = nameToModuleType.get(moduleName);
Module module = moduleType.getModuleClass().newInstance();
configureModule(module, configuration);
return module;
}
throw new IllegalArgumentException(
"Class not supported: " + moduleName);
}
private void configureModule(
Module module, Properties configuration)
throws Exception {
if (module.getClass().isAnnotationPresent(ParameterClass.class)) {
Map<String, Method> methodNameToMethod =
getMethodNameToMethod(module);
for (ModuleParameter param : getModuleParameters(module)) {
String configValue = configuration.getProperty(
param.toString());
// Set default value if configuration value is empty.
if (configValue.isEmpty()) {
configValue = param.getDefaultValue();
}
// Check if value is required.
if ((configValue == null || configValue.isEmpty())
&& param.isRequired()) {
throw new IllegalArgumentException(
"Configuration value missing for: "
+ param.toString());
}
// Set configuration value in module.
invokeParameterSetter(methodNameToMethod, module,
param.toString(), configValue);
}
}
}
private Map<String, Method> getMethodNameToMethod(Module module) {
Map<String, Method> methodNameToMethod =
new HashMap<String, Method>();
for (Method method : module.getClass().getMethods()) {
methodNameToMethod.put(method.getName(), method);
}
return methodNameToMethod;
}
private ModuleParameter[] getModuleParameters(Module module) {
return module.getClass()
.getAnnotation(ParameterClass.class)
.parameterClass().getEnumConstants();
}
private void invokeParameterSetter(
Map<String, Method> methodNameToMethod,
Module module, String paramName, String configValue)
throws Exception {
String setterMethodName = getSetterMethodName(paramName);
if (methodNameToMethod.containsKey(setterMethodName)) {
methodNameToMethod.get(setterMethodName).invoke(
module, configValue);
} else {
throw new IllegalArgumentException(
"No setter found for: " + paramName);
}
}
private String getSetterMethodName(String paramName) {
return "set" + Character.toUpperCase(paramName.charAt(0))
+ paramName.substring(1);
}
}
</pre>
<p>
Using the name of the module class, this factory instantiates the correct class with the help of the "ModuleType" enumeration class. Then it tries to find out if this module requires configuration, by detecting the annotation. The annotation specifies the use of the "ExampleModuleParameter" enumeration for configuration. Using the enumeration, and the "Properties" object, it calls the setters with the configuration values. It also checks if a required configuration value is present. The result is a module with all required configuration values set.
</p>
<p>
A drawback is that the method name of the setters is restricted. It must be the same as the name of the parameter (excluding the "set" string), which is defined in the enumeration. A solution for this is to use annotations in the setter method definition to specify which configuration parameter it corresponds to. Using string literals to tie things together makes the code brittle.
</p>
<h3>Main</h3>
<pre class="brush:java">
package com.javaeenotes.modules;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
// Build the configuration properties.
Properties configuration = new Properties();
configuration.setProperty(
ExampleModuleParameter.PARAM1.toString(), "");
configuration.setProperty(
ExampleModuleParameter.PARAM2.toString(), "param2");
try {
// Get instance of configured module from factory.
Module module = new ModuleFactoryImpl()
.getModule("ExampleModule", configuration);
// Run the module.
module.doBusinessStuff();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</pre>
<p>This class demonstrates the whole solution. If run, it prints: <i>Hello, I am ExampleModule. I am configured with param1='DEFAULT', and param2='param2'.</i></p>
<h2>Conclusion</h2>
<p>As you can see, writing new modules is very easy by implementing just the two interfaces. All the configuration code is centralized in the factory implementation.</p>
<p>If you have ideas for improvements or better solutions, please don't hesitate to share them in the comments.</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com2tag:blogger.com,1999:blog-8155967785119627415.post-79583482151204849532012-03-05T11:50:00.000+01:002012-03-05T11:50:00.085+01:00Quick introduction to OpenSSL<a href="http://www.openssl.org/">OpenSSL</a> is an open source Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) implementation. I exclusively use this for handling SSL related tasks, and diagnostics. I will explain the OpenSSL commands I frequently use in this blog post.
Before we go to the commands, let's do a quick explanation of the terminology used in SSL:
<ul>
<li><b>Certificate Signing Request (CSR)</b>: a message format for a certificate signing request for a Certificate Authority. This message is required for generating/requesting certificates.
<li><b>Public/Private key</b>: a private key should be kept secret by the owner, and can be used to sign data, or decrypt messages encrypted with the public key. The public key is used to encrypt message which are only to be read by the owner of the private key. The encryption/decryption process tends to be slow compared to using a symmetric encryption key.
<li><b>Symmetric key</b>: one key for encrypting and decrypting. This process is fast. When we use SSL in our browser, the public/private key is only used to negotiate a symmetric key encryption method. The actual data transfer encryption is therefore symmetric (fast).
<li><b>(Root) Certificate</b>: a certificate contains identification information, a public key that can be used to encrypt messages, and a signature of a Certificate Authority. The signature tells us that the identification information is trusted/verified by the Certificate Authority. If we trust the Certificate Authority, then we also trust the identity of the owner of the certificate (authentication).
<li><b>Certificate Authority (CA)</b>: an organization we consider to be trusted. A CA will sign and issue certificates. Using the root certificate of a CA, we can verify if other certificates are indeed signed by this particular CA. Your browser has a standard set of root certificates of commonly recognized CA's.
</ul>
<h2>Common commands</h2>
<b>To generate a CSR for a certificate with a 2048-bit private key:</b>
<pre>
openssl req -out certificate.csr -new
-newkey rsa:2048 -nodes -keyout private.key
</pre>
<b>Generate a self-signed certificate (we are our own CA):</b>
<pre>
openssl req -x509 -nodes -days 365 -newkey rsa:2048
-keyout private.key -out certificate.crt
</pre>
<b>Print out the information contained in a certificate, such as identification, and the public key:</b>
<pre>
openssl x509 -in certificate.crt -text -noout
</pre>
<b>To check a web server for its SSL-certificates:</b>
<pre>
openssl s_client -showcerts -connect google.com:443 </dev/null
</pre>
<h2>References:</h2>
<ul>
<li><a href="http://www.openssl.org">http://www.openssl.org</a>
<li><a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">http://en.wikipedia.org/wiki/Transport_Layer_Security</a>
<li><a href="http://en.wikipedia.org/wiki/Public_key_infrastructure">http://en.wikipedia.org/wiki/Public_key_infrastructure</a>
<li><a href="http://en.wikipedia.org/wiki/Certificate_authority">http://en.wikipedia.org/wiki/Certificate_authority</a>
<li><a href="http://en.wikipedia.org/wiki/X.509">http://en.wikipedia.org/wiki/X.509</a>
<li><a href="http://www.sslshopper.com/article-most-common-openssl-commands.html">http://www.sslshopper.com/article-most-common-openssl-commands.html</a>
</ul>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-84415776974014241622011-12-26T19:48:00.000+01:002013-02-09T13:33:45.754+01:00Annotated callback methods in custom class<p>
We're implementing a simple message service framework to demonstrate how we can implement a framework that uses annotations, like <a href="http://docs.oracle.com/javaee/5/tutorial/doc/bnayl.html">JAX-WS</a>. Using annotations minimizes boilerplate code, and promotes high cohesion of classes. It also promotes decoupling, because it prevents forcing the use of framework classes on clients as much as possible.
</p>
<p>
The messaging framework has one interface with a register method, which is used to register custom objects that handle incoming messages. The framework does not know what the type is of this object. It uses the reflection API to check for annotated methods, which tell the messaging framework to call these methods when a message has to be handled.
</p>
<p>
The message service framework supports two types of messages, which we define in as an <i><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html">enum</a></i> type in <i>MessageType.java</i>:
</p>
<pre class="brush:java">
package com.javaeenotes;
public enum MessageType {
NORMAL,
URGENT
}
</pre>
<p>
The interface of the message service framework has a method to register custom client objects that will handle incoming messages. The second method of the interface is only included, so we can send messages through this framework. The interface of the message service framework is defined in <i>MessageService.java</i>:
</p>
<pre class="brush:java">
package com.javaeenotes;
public interface MessageService {
void registerMessageHandler(Object object);
void sendMessage(String message, MessageType messageType)
throws Exception;
}
</pre>
<p>
Now, we define our annotation. This annotation can be used by the client application to mark methods that will handle incoming messages generated by the message service framework. It also has a message type <i>enum</i> parameter, so the framework will only call this method if the type of the message matches the specified type parameter. The annotation is defined in <i>MessageMethod.java</i>:
</p>
<pre class="brush:java">
package com.javaeenotes;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Only usable on methods.
@Target(ElementType.METHOD)
// Annotation must be available during runtime.
@Retention(RetentionPolicy.RUNTIME)
public @interface MessageMethod {
MessageType messageType() default MessageType.NORMAL;
}
</pre>
<p>
A client object will use the annotation to mark callback methods for specified message types. The example client handler has one method for both message types. An example client message handler class for this demo is defined as <i>ExampleMessageHandler.java</i>:
</p>
<pre class="brush:java">
package com.javaeenotes;
public class ExampleMessageHandler {
@MessageMethod(messageType = MessageType.NORMAL)
public void handleNormalMessage(String message) {
System.out.print("NORMAL MESSAGE: " + message + "\n");
}
@MessageMethod(messageType = MessageType.URGENT)
public void handleUrgentMessage(String message) {
System.out.println("URGENT MESSAGE: " + message + "\n");
}
}
</pre>
<p>
The most important class of this tutorial is: <i>MessageServiceImpl.java</i>, which you can find below. This is the implementation of our message service framework interface. This class is responsible for determining callback methods provided by the client, and call them when messages arrive.
</p>
<pre class="brush:java">
package com.javaeenotes;
import java.lang.reflect.Method;
public class MessageServiceImpl implements MessageService {
private Object messageHandler;
@Override
public void registerMessageHandler(Object messageHandlerObject) {
messageHandler = messageHandlerObject;
}
@Override
public void sendMessage(String message, MessageType messageType)
throws Exception {
for (Method method : messageHandler.getClass().getMethods()) {
if (method.isAnnotationPresent(MessageMethod.class)) {
MessageMethod messageMethod
= method.getAnnotation(MessageMethod.class);
if (messageMethod.messageType() == MessageType.NORMAL
&& messageType == MessageType.NORMAL) {
method.invoke(messageHandler, message);
} else if (messageMethod.messageType()
== MessageType.URGENT
&& messageType == MessageType.URGENT) {
method.invoke(messageHandler, message);
}
}
}
}
}
</pre>
<p>
Now, we only need a <i>Main</i> class to get this demonstration working. The class will create the example client object, and register it in the framework. Then, it will create two example messages, and pass them to the framework, which then will call the annotated callback methods of the example client object. The <i>Main</i> class is defined in: <i>Main.java</i>.
</p>
<pre class="brush:java">
package com.javaeenotes;
public class Main {
public static void main(String[] args) {
// Create message service and register message handler.
MessageService messageService = new MessageServiceImpl();
messageService.registerMessageHandler(
new ExampleMessageHandler());
try {
// Sending test messages through the message service.
messageService.sendMessage("This is a normal message.",
MessageType.NORMAL);
messageService.sendMessage("This is an urgent message!",
MessageType.URGENT);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</pre>
<p>
If we run the <i>Main</i> class, we should get the following output:
</p>
<pre>
NORMAL MESSAGE: This is a normal message.
URGENT MESSAGE: This is an urgent message!
</pre>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-36447793983254839042011-12-20T10:06:00.001+01:002013-02-09T13:37:11.901+01:00Custom SLF4J Logger adapter<p>The <a href="http://www.slf4j.org/">Simple Logging Facade for Java</a> or (SLF4J) is a simple facade for various logging frameworks. It decouples the logging framework from the application. The deployer can choose which logging framework to use. For every popular logging framework, an adapter Jar file is available. Deploy this file together with the core SLF4J Jar file, and the logging automagically works.</p>
<p>In my current work situation, a financial application I developed has to be integrated into an existing server application. This server application uses its own logging framework. Luckily, I've been using SLF4J, so logging integration is just a matter of writing a custom SLF4J adapter and replace the current adapter (SLF4J-Log4J) with it.</p>
<p>
Writing an adapter is very easy. You only need to create three files:
<ol>
<li>Create an implementation of the logger interface: <i>org.slf4j.Logger</i>
<li>Create a factory for the new logger using this interface: <i>org.slf4j.ILoggerFactory</i>
<li>Create your own binder class, so SLF4J knows which factory to use to get loggers: <i>org.slf4j.spi.LoggerFactoryBinder</i>
</ol>
It is important to create these files in the package: <i>org.slf4j.impl</i>, because SLF4J is using this to find the correct adapter.
</p>
<p>Firstly, we create the class that implements the SLF4J <i>Logger</i> interface. The implementation of this interface is used by SLF4J to delegate the logging. It's an interface with a large number of methods, so let the IDE generate the empty methods for you. Next is to implement the bodies of the methods to do the actual logging. In my case, I call the custom logging framework.</p>
<pre class="brush:java">
package org.slf4j.impl;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.helpers.MessageFormatter;
public class MyLoggerAdapter implements Logger {
// Bunch of inherited methods here. Let your IDE generate this.
// Implement these methods to do your own logging.
}
</pre>
<p>
Now, we create a factory implementation for the <i>Logger</i> class. This class is used to retrieve <i>Logger</i> objects used by the application. Make sure it implements the <i>ILoggerFactory</i> interface.
</p>
<pre name="code" class="brush:java">
package org.slf4j.impl;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import java.util.HashMap;
import java.util.Map;
public class MyLoggerFactory implements ILoggerFactory {
private Map<String, MyLoggerAdapter> loggerMap;
public MyLoggerFactory() {
loggerMap = new HashMap<String, MyLoggerAdapter>();
}
@Override
public Logger getLogger(String name) {
synchronized (loggerMap) {
if (!loggerMap.containsKey(name)) {
loggerMap.put(name, new MyLoggerAdapter(name));
}
return loggerMap.get(name);
}
}
}</pre>
<p>
Finally, we need a way to register or bind the logger factory to SLF4J. To do that, we have to customize the <i>StaticLoggerBinder</i> class. You can almost use the same code provided by other adapters. I shamelessly ripped my code from the Log4J adapter.
</p>
<pre name="code" class="brush:java">
package org.slf4j.impl;
import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;
public class StaticLoggerBinder implements LoggerFactoryBinder {
/**
* The unique instance of this class.
*/
private static final StaticLoggerBinder SINGLETON
= new StaticLoggerBinder();
/**
* Return the singleton of this class.
*
* @return the StaticLoggerBinder singleton
*/
public static final StaticLoggerBinder getSingleton() {
return SINGLETON;
}
/**
* Declare the version of the SLF4J API this implementation is
* compiled against. The value of this field is usually modified
* with each release.
*/
// To avoid constant folding by the compiler,
// this field must *not* be final
public static String REQUESTED_API_VERSION = "1.6"; // !final
private static final String loggerFactoryClassStr
= MyLoggerFactory.class.getName();
/**
* The ILoggerFactory instance returned by the
* {@link #getLoggerFactory} method should always be the same
* object.
*/
private final ILoggerFactory loggerFactory;
private StaticLoggerBinder() {
loggerFactory = new MyLoggerFactory();
}
public ILoggerFactory getLoggerFactory() {
return loggerFactory;
}
public String getLoggerFactoryClassStr() {
return loggerFactoryClassStr;
}
}
</pre>
<p>
Compile and deploy this code together with the SLF4J jar, and logging will be handled by the our new adapter.
</p>
<p>
<b>Links:</b>
<ul>
<li><a href="http://www.slf4j.org/manual.html">SLF4J manual</a>
<li><a href="http://www.slf4j.org/faq.html">SLF4J FAQ</a>
</ul>
</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com14tag:blogger.com,1999:blog-8155967785119627415.post-43452907735515023032011-12-16T16:13:00.000+01:002011-12-17T19:14:22.208+01:00Running Wicket on Jetty<p>
If you're only using the web functionality provided by an application server, or you want to optimize HTTP performance, it would be a good idea to consider embedding the Jetty HTTP server inside your application. This way, you don't even have to generate a WAR-file and a web.xml file. The application is just a basic Java application, which you can run on any server with a Java VM.
</p>
<h2>Maven setup</h2>
<p>If you're using a Maven project, add the following dependencies to the pom-file in the "dependencies"-element in order to start working right away:</p>
<pre name="code" class="xml">
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-hightide</artifactId>
<version>8.0.4.v20111024</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>1.5.3</version>
</dependency>
</pre>
<h2>Minimal Wicket application</h2>
<p>For our example, we use a minimal Wicket application that consists of one page.</p>
The ExampleWicketApplication.java file:
<pre name="code" class="java">
package com.javaeenotes;
import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;
public class ExampleWicketApplication extends WebApplication {
@Override
public Class<? extends Page> getHomePage() {
return HomePage.class;
}
}
</pre>
The HomePage.java file:
<pre name="code" class="java">
package com.javaeenotes;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
public class HomePage extends WebPage {
public HomePage() {
add(new Label("message", "Hello World!"));
}
}
</pre>
The HomePage.html file:
<pre name="code" class="html">
<html>
<body>
<span wicket:id="message"></span>
</body>
</html>
</pre>
<p>The final class we need is a main class with the static main-method, in which we tie the Wicket servlet to the Jetty server.</p>
The Main.java file:
<pre name="code" class="java">
package com.javaeenotes;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
public class Main {
public static void main(String[] args) {
// Object that holds, and configures the WicketServlet.
ServletHolder servletHolder =
new ServletHolder(new WicketServlet());
servletHolder.setInitParameter(
"applicationClassName",
"com.javaeenotes.ExampleWicketApplication");
servletHolder.setInitParameter(
WicketFilter.FILTER_MAPPING_PARAM, "/*");
servletHolder.setInitOrder(1);
// Web context configuration.
WebAppContext context = new WebAppContext();
context.addServlet(servletHolder, "/*");
context.setResourceBase("."); // Web root directory.
// The HTTP-server on port 8080.
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(8080);
server.setConnectors(new Connector[]{connector});
server.setHandler(context);
try {
// Start HTTP-server.
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</pre>
<p>
Run the main method in a VM, and connect to port 8080 with a browser to check that the application is working.
</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com3tag:blogger.com,1999:blog-8155967785119627415.post-82360319950619788932011-10-28T13:57:00.000+02:002011-10-28T13:57:29.273+02:00MyBatis and Oracle Database<p>
While I was using <a href="http://www.mybatis.org/">MyBatis</a> with the <a href="http://www.oracle.com/us/products/database/index.html">Oracle Database</a>, I ran into two problems:
<ol>
<li>Generating primary keys when inserting database rows
<li>Mapping Java boolean type to a database type
</ol>
The next sections describe how I solved these problems.
</p>
<b>Inserting new rows</b>
<p>
Unlike other databases like MySQL, the Oracle database does not provide the functionality to generate primary keys automatically when inserting rows. Normally, I would create a <a href="http://www.orafaq.com/wiki/Sequence">sequence</a> together with a <a href="http://www.orafaq.com/wiki/Trigger">trigger</a> in the Oracle database. The sequence is a thread-safe number generator, and the trigger is custom code that is called on certain type of events. In this case an "insert" event, which will update the row with the primary key.
</p>
<p>
With MyBatis, we still need the sequence. The trigger functionality is provided by MyBatis. Let's get started by creating an example class in Java. I left the "getters" and "setters" out, but we still need them in the actual code ofcouse.
</p>
<pre name="code" class="java">
public class Client {
private Integer id;
private String name;
// Setters and Getters for the attributes here.
}
</pre>
<p>
Next, we have to prepare the database by create a table that corresponds with the "Client" class, and a sequence.
</p>
<pre name="code" class="sql">
CREATE TABLE client (
id INTEGER primary key,
name VARCHAR2(100)
);
CREATE SEQUENCE client_seq
START WITH 1
INCREMENT BY 1
NOCACHE
NOCYCLE;
</pre>
<p>
MyBatis uses "mapper" interfaces (defined and provided by us) to map the class to actual SQL-statements. Additional configuration can be provided by either XML, or annotations. When the configuration is simple, I prefer using annotations. Complex configurations are often only possible by using XML. The following mapper interface provides mapping for inserting the "Client" class. The interface is only used by MyBatis, we don't have to provide an actual implementation of it.
</p>
<pre name="code" class="java">
public interface ClientMapper {
@Insert("INSERT INTO client (id, name) VALUES (#{id}, #{name})")
@SelectKey(
keyProperty = "id",
before = true,
resultType = Integer.class,
statement = { "SELECT client_seq.nextval AS id FROM dual" })
public Integer insertClient(Client client);
}
</pre>
<p>
The "@SelectKey" annotation tells MyBatis to get the primary key value from the sequence, and use it as primary key when executing the insert statement.
</p>
<b>Mapping boolean types</b>
<p>
The final example illustrates how we deal with boolean types when using MyBatis. We extend the "Client" class with a boolean attribute "admin".
</p>
<pre name="code" class="java">
public class Client {
private Integer id;
private String name;
private boolean admin;
// Setters and Getters for the attributes here.
}
</pre>
<p>
Add a "VARCHAR(1)" column that acts like a boolean attribute to the corresponding "Client" database table. The column value "Y" corresponds to boolean value true, and "N" to boolean false.
</p>
<pre name="code" class="sql">
CREATE TABLE client (
id INTEGER primary key,
name VARCHAR2(100),
admin varchar(1)
);
</pre>
<p>
MyBatis doesn't know how the Java boolean is mapped to a database type, as there's no primitive database boolean type. We have to provide MyBatis with a converter, which implements the "TypeHandler" interface. This converter will then be used to convert a Java boolean to a database type, and vice versa.
</p>
<pre name="code" class="java">
package com.javaeenotes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class BooleanTypeHandler implements TypeHandler<Boolean> {
private static final String YES = "Y";
private static final String NO = "N";
@Override
public Boolean getResult(ResultSet resultSet, String name)
throws SQLException {
return valueOf(resultSet.getString(name));
}
@Override
public Boolean getResult(CallableStatement statement, int position)
throws SQLException {
return valueOf(statement.getString(position));
}
@Override
public void setParameter(
PreparedStatement statement,
int position,
Boolean value,
JdbcType jdbcType) throws SQLException {
statement.setString(position, value.booleanValue() ? YES : NO);
}
private Boolean valueOf(String value) throws SQLException {
if (YES.equalsIgnoreCase(value)) {
return new Boolean(true);
} else if (NO.equalsIgnoreCase(value)) {
return new Boolean(false);
} else {
throw new SQLException("Unexpected value "
+ value
+ " found where "
+ YES
+ " or "
+ NO
+ " was expected.");
}
}
}
</pre>
<p>
Now, configure MyBatis to use the type handler for booleans in the mapper interface where needed.
</p>
<pre name="code" class="java">
@Insert("INSERT INTO client (id, name, admin) VALUES (#{id}, #{name}, #{admin,typeHandler=com.javaeenotes.BooleanTypeHandler})")
@SelectKey(
keyProperty = "id",
before = true,
resultType = Integer.class,
statement = { "SELECT client_seq.nextval AS id FROM dual" })
public Integer insertClient(Client client);
@Select("SELECT * FROM client WHERE id = #{clientId}")
@Results(
value = {
@Result(
property = "id",
column = "id"),
@Result(
property = "name",
column = "name"),
@Result(
property = "admin",
column = "admin",
typeHandler = BooleanTypeHandler.class)
})
public Client getClient(int clientId);
@Update("UPDATE client SET name = #{name}, admin = #{admin,typeHandler=com.javaeenotes.BooleanTypeHandler} WHERE id = #{id}")
public void updateClient(Client client);
</pre>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com5tag:blogger.com,1999:blog-8155967785119627415.post-55023784705508651472011-10-13T11:53:00.000+02:002011-10-13T12:50:16.426+02:00Adding Oracle JDBC driver to Maven 2 repository<p>
I like my library JAR-files to be managed by Maven 2. It makes life much easier. Sadly, due to the binary license there is no public Maven 2 repository with the Oracle JDBC driver. So we have to add the JDBC driver manually to our local Maven 2 repository.
</p>
<p>
First, download the latest Oracle JDBC driver here: <a href="http://www.oracle.com/technetwork/indexes/downloads/index.html">http://www.oracle.com/technetwork/indexes/downloads/index.html</a>. Do a search on "JDBC" to find the correct download link.
</p>
<p>
If you're using Maven inside Eclipse like I am, the "mvn" command will not work from the command prompt. We have to install Maven 2 on our system. You can download Maven 2 here: <a href="http://maven.apache.org/download.html">http://maven.apache.org/download.html</a>. Simply unzip, and make sure the "bin" directory is in your command path.
</p>
<p>
Now, we can install the JAR file with the following command:
<pre>mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6
-Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true</pre>
Be sure to check the parameters, like the version number.
</p>
<p>
Finally, we can use the Oracle JDBC driver in our Maven 2 project by adding the following dependency to our "pom.xml" file:
<pre name="code" class="xml">
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
</pre>
</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-56047826690224654532011-09-13T18:44:00.000+02:002011-09-13T18:45:00.380+02:00Extensible Factory Method implementation<p>One of my favourite design pattern is the <a href="http://scea.djcheng.com/page.php/13/Factory_Method.html">Factory Method</a>. The design pattern encapsulates object creation, i.e. the factory method decides which implementation you'll get. I often use a slightly different version of the pattern, which returns a specific implementation of an interface based on a name parameter. The supported names are defined as static constants in the factory class. This way, I decouple the actual implementation from its user. The only link to the actual implementation is the name constant.</p>
<p>The implementation I use has several problems. Everytime I add a new manufacturable class, I have to change the factory class by adding a new name constant to identify the new manufacturable. And I have to add nearly the same code to actually instantiate and return the new type by the factory, which violates the <i><a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a></i>-principle. This also makes the factory tightly coupled to the new type, which I want to avoid if possible.</p>
<p>Another problem I had in the past was that I use to same code in every <a href="http://scea.djcheng.com/page.php/15/Singleton.html">Singleton</a> class (Factory Methods are often Singletons). I solved this by using a Dependency Injection Framework like Google Guice or Spring. It's possible to mark singleton classes using these frameworks by annotations or configuration. The frameworks will then make sure that the marked classes are singletons during execution.
<p>So, I felt a need to improve my implementation of the factory methods. I wanted the following properties for my factory methods:</p>
<ol>
<li>It should be easy to create new factories, without much (duplicate) code.
<li>It should be easy to add new manufacturables, without changing code in the factory class.
</ol>
<p>The result is the implementation I'll describe next. Before we go to the actual implementation, let's create an interface for the manufacturable classes, and two example implementation of the manufacturable classes.</p>
<p>The manufacturable interface:</p>
<pre name="code" class="java">
package com.javaeenotes;
public interface MyManufacturable {
public String getName();
}
</pre>
<p>Two implementations of the manufacturable interface:</p>
<pre name="code" class="java">
package com.javaeenotes;
public class MyManufacturableAImpl implements MyManufacturable {
@Override
public String getName() {
return getClass().getSimpleName();
}
}
</pre>
<pre name="code" class="java">
package com.javaeenotes;
public class MyManufacturableBImpl implements MyManufacturable {
@Override
public String getName() {
return getClass().getSimpleName();
}
}
</pre>
<p>The abstract factory method class:</p>
<pre name="code" class="java">
package com.javaeenotes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public abstract class AbstractFactory<T> {
private static final String CONFIG_FILE_EXTENSION = ".conf";
private final String factoryName;
private final Map<String, Class<? extends T>> manufacturableClasses;
public AbstractFactory(String name) {
this.factoryName = name;
this.manufacturableClasses = new HashMap<String, Class<? extends T>>();
try {
loadClasses();
} catch (IOException ioException) {
throw new IllegalArgumentException(
"Error reading factory configuration file.",
ioException);
} catch (ClassNotFoundException classNotFoundException) {
throw new IllegalStateException(
"Could not find class for name in factory configuration file.",
classNotFoundException);
}
}
@SuppressWarnings("unchecked")
private void loadClasses() throws IOException, ClassNotFoundException {
BufferedReader configReader = null;
try {
configReader = new BufferedReader(new InputStreamReader(getClass()
.getResourceAsStream(factoryName + CONFIG_FILE_EXTENSION)));
String className;
while ((className = configReader.readLine()) != null) {
manufacturableClasses.put(
className,
(Class<? extends T>) Class.forName(className));
}
} finally {
if (configReader != null) {
configReader.close();
}
}
}
public Set<String> getNamesManufacturables() {
return manufacturableClasses.keySet();
}
public T getInstance(String nameManufacturable)
throws InstantiationException, IllegalAccessException {
return manufacturableClasses.get(nameManufacturable).newInstance();
}
}
</pre>
<p>The factory method class contains no hard references to our manufacturable implementation classes. Hey, there's even no reference to our manufacturable interface, because we use generics!</p>
<p>The factory is designed as a generic abstract class, which should be extended by every factory method class in the application. The manufacturables are defined in a configuration file in the class path, which has the same name as the factory. The configuration file has a <i>.conf</i> file extension, and should contain the fully qualified names of the manufacturable classes. Upon factory instantiation, the configuration file is read, and all supporting manufacturable classes are loaded.</p>
<p>Here is the example factory:</p>
<pre name="code" class="java">
package com.javaeenotes;
public class MyFactory extends AbstractFactory<MyManufacturable> {
private static final String name = "MyFactory";
public MyFactory() {
super(name);
}
}
</pre>
<p>The factory configuration file we use to support our manufacturable classes (<i>MyFactory.conf</i>):</p>
<pre>
com.javaeenotes.MyManufacturableAImpl
com.javaeenotes.MyManufacturableBImpl
</pre>
We can use the following main class, which prints the names of the manufacturables, as demonstration:
<pre name="code" class="java">
package com.javaeenotes;
public class Main {
public void run() {
MyFactory factory = new MyFactory();
for (String name : factory.getNamesManufacturables()) {
try {
MyManufacturable myManufacturable = factory.getInstance(name);
System.out.println(myManufacturable.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Main().run();
}
}
</pre>
<h2>Conclusion</h2>
<p>The factory method class implementation makes adding new factories very simple. Every factory class just has to extend the abstract factory class, and call its constructor with the name of the factory. The whole factory class consists of just several lines!</p>
<p>Registering new manufacturable classes to the factory is also much easier. Just add the fully qualified name of the new class to the factory configuration file, and we're done!</p>
<p>This concludes this post. If you have any improvements, please don't hesitate to share them in the comments.</p>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com2tag:blogger.com,1999:blog-8155967785119627415.post-54568326156566442512011-09-09T21:19:00.000+02:002011-11-30T09:50:23.269+01:00Inject instances in Quartz jobs with Google Guice<p>This post explains how to use <a href="http://quartz-scheduler.org/">Quartz 2</a> with <a href="http://code.google.com/p/google-guice/">Google Guice</a>. Before you read any further, I assume you have some basic understanding about Guice and Quartz 2, and what problems they solve.</p>
<p>Normally, Quartz will instantiate job classes itself. You only need to supply the job class, so Quartz knows which class to instantiate when a job is ready to be executed. The job itself is pretty hidden (encapsulated) by Quartz.</p>
<p>In some cases, you want to let Google Guice inject references of (singleton) objects to the job. Such as a <a href="http://scea.djcheng.com/page.php/52/Data_Access_Object.html">Data Access Object</a>, so the job can access or store data.</p>
<p>The solution is to supply our own job factory to the Quartz class that is responsible for job instantiation. Our factory will use Guice to create instances for Quartz to use.</p>
<pre name="code" class="java">
package com.javaeenotes.guicequartz;
import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import com.google.inject.Inject;
import com.google.inject.Injector;
public class MyJobFactory implements JobFactory {
@Inject
private Injector injector;
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler)
throws SchedulerException {
return (Job) injector.getInstance(
bundle.getJobDetail().getJobClass());
}
}
</pre>
To complete this example, we need an example DAO class, and a Quartz job class that will hold the injected DAO object.
<pre name="code" class="java">
package com.javaeenotes;
public interface Dao {
public abstract String getData();
}
</pre>
<pre name="code" class="java">
package com.javaeenotes;
import com.google.inject.Singleton;
@Singleton
public class DaoImpl implements Dao {
@Override
public String getData() {
return "Data from DAO.";
}
}
</pre>
<pre name="code" class="java">
package com.javaeenotes;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.google.inject.Inject;
public class MyJob implements Job {
@Inject
private Dao dao;
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println(dao.getData());
}
}
</pre>
Now, we need a Guice module that defines and maps the factory and DAO classes.
<pre name="code" class="java">
package com.javaeenotes;
import org.quartz.spi.JobFactory;
import com.google.inject.AbstractModule;
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(JobFactory.class).to(MyJobFactory.class);
bind(Dao.class).to(DaoImpl.class);
}
}
</pre>
Finally, a Main class to demonstrate the application:
<pre name="code" class="java">
package com.javaeenotes;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Main {
public void run() {
// The Guice injector used to create instances.
Injector injector = Guice.createInjector(new MyModule());
// Object that contains the job class.
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("jobId", "jobGroup").build();
// Create the trigger that will instantiate and execute the job.
// Execute the job with a 3 seconds interval.
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerId")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(3).repeatForever())
.build();
try {
// Retrieve the Quartz scheduler to schedule the job.
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
// Here we tell the Quartz scheduler to use our factory.
scheduler.setJobFactory(injector.getInstance(MyJobFactory.class));
scheduler.scheduleJob(jobDetail, trigger);
// Start the scheduler.
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Main().run();
}
}
</pre>
This will output the following every 3 seconds:
<pre>
Data from DAO.
</pre>
<h2>Installation of Quartz 2 and Google Guice</h2>
If you use Maven 2 for your project, you can install both frameworks by simply adding the following configuration to your <i>pom.xml</i> file.
<pre name="code" class="xml">
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
</dependency>
</pre>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com5tag:blogger.com,1999:blog-8155967785119627415.post-90743787708380390452011-09-08T17:11:00.000+02:002011-09-09T14:25:14.288+02:00Kick-start Quartz 2 Tutorial<a href="http://www.quartz-scheduler.org">Quartz</a> is a job scheduling framework, which provides a powerful way of executing and controlling scheduled jobs. This tutorial is based on the official <a href="http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/">tutorial</a> on the main website of Quartz. The goal of this tutorial is to get a kick-start in using Quartz. Most details are left out. The example is designed to be easy to follow.
The example consists of three classes:
<ul>
<li><b>Main</b>: instantiates, and initiates Quartz classes
<li><b>JobTask</b>: the actual job definition
<li><b>JobTaskListener</b>: a listener class that monitors the execution of the job
</ul>
Let's get right into the code. The first code fragment represents the state of a job. Job classes that Quartz uses are stateless. So we are forced to use the <a href="http://scea.djcheng.com/page.php/28/Memento.html">Memento design pattern</a> to externalize state. This class should be serializable to prevent problems when we use Quartz to persist job states in the future. The state is meant to be accessed by the main thread and Quartz, so make sure it's thread-safe.
<pre name="code" class="java">
package com.javaeenotes;
import java.io.Serializable;
public class JobContext implements Serializable {
private static final long serialVersionUID = 1L;
private String state = "Initial state.";
public String getState() {
synchronized (state) {
return state;
}
}
public void setState(String state) {
synchronized (state) {
this.state = state;
}
}
}
</pre>
The next code is the job definition class, which implements the method called by the Quartz scheduler. It's recommended to wrap the whole body of the method in a try-block in order to catch any exceptions that might occur. Wrap the exception in the checked <i>JobExecutionException</i> before throwing it. The main thread can deal with the exception later.
<pre name="code" class="java">
package com.javaeenotes;
import java.util.Date;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
// Disallow running multiple jobs based on this class at the same time.
@DisallowConcurrentExecution
public class JobTask implements Job {
@Override
public void execute(JobExecutionContext executionContext)
throws JobExecutionException {
// It's a good idea to wrap the entire body in a try-block, in order to
// catch every exception thrown.
try {
// Retrieve the state object.
JobContext jobContext = (JobContext) executionContext
.getJobDetail().getJobDataMap().get("jobContext");
// Update state.
jobContext.setState(new Date().toString());
// This is just a simulation of something going wrong.
int number = 0;
number = 123 / number;
} catch (Exception e) {
throw new JobExecutionException(e);
}
}
}
</pre>
The next class is responsible for monitoring the job. It's also responsible for dealing with exceptions thrown by the job.
<pre name="code" class="java">
package com.javaeenotes;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
public class JobTaskListener implements JobListener {
public static final String TRIGGER_NAME = "Trigger";
@Override
public String getName() {
return TRIGGER_NAME;
}
@Override
public void jobToBeExecuted(JobExecutionContext context) {
System.out.println("Job is going to be executed: "
+ context.getJobDetail().getKey().toString());
}
@Override
public void jobExecutionVetoed(JobExecutionContext context) {
System.out.println("Job is vetoed by trigger: "
+ context.getJobDetail().getKey().toString());
}
@Override
public void jobWasExecuted(
JobExecutionContext context,
JobExecutionException jobException) {
System.out.println("Exception thrown by: "
+ context.getJobDetail().getKey().toString()
+ " Exception: "
+ jobException.getMessage());
}
}
</pre>
Now, we can use these classes to see how it runs. We use the <i>Main</i>-class for this purpose.
<pre name="code" class="java">
package com.javaeenotes;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;
public class Main {
@SuppressWarnings("unchecked")
public void run() {
// The state of the job.
JobContext jobContext = new JobContext();
// The value or transfer object provided by Quartz that contains the
// state of the job. Save it in JobDetail or Trigger.
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("jobContext", jobContext);
// Create an identifier for the job.
JobKey jobKey = new JobKey("jobId", "jobGroup");
// Object that contains the job class and transfer object.
JobDetail jobDetail = JobBuilder.newJob(JobTask.class)
.withIdentity(jobKey).usingJobData(jobDataMap).build();
// Create the trigger that will instantiate and execute the job.
// Execute the job with a 5 seconds interval.
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("triggerId")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5).repeatForever())
.build();
// Setup a listener for the job.
JobListener jobListener = new JobTaskListener();
// Use the Quartz scheduler to schedule the job.
try {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.scheduleJob(jobDetail, trigger);
// Tell scheduler to listen for jobs with a particular key.
scheduler.getListenerManager().addJobListener(
jobListener,
KeyMatcher.keyEquals(jobKey));
// Start the scheduler after 5 seconds.
scheduler.startDelayed(5);
} catch (SchedulerException e) {
e.printStackTrace();
}
// Print the job state with a 3 seconds interval.
while (true) {
try {
System.out.println(jobContext.getState());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Main().run();
}
}
</pre>
<p>
The first thing we do is to create the state object, and wrap it in the <a href="http://scea.djcheng.com/page.php/49/Transfer_Object.html">transfer or value object</a> provided by Quartz. The reason we do this, is because Quartz doesn't let us instantiate the job class ourselves.
</p>
<p>
The next step is to define and instantiate a <i>JobKey</i> object, which acts as the identifier for our job. This is also used together with the listener to tell the scheduler which jobs we want to monitor.
</p>
<p>
Then we create a <i>JobDetail</i> object, which contains details of the job. A trigger object is also needed to tell the scheduler <i>when</i> we want our job to be run. This provides a nice separation of the job and run schedule. Using multiple triggers we can run the same job at different times.
</p>
<p>
Next, we instantiate the listener class.
</p>
<p>
Finally, we retrieve an instance of the Quartz scheduler to schedule the job with the trigger. The listener class is also added, together with a matcher based on the job identifier. This way, the scheduler knows which jobs the listener is listening to. The scheduler is then started with a delay of 5 seconds.
</p>
The resulting output, when we run the Main class:
<pre>
Initial state.
Initial state.
Job is going to be executed: jobGroup.jobId
Exception thrown by: jobGroup.jobId
Exception: java.lang.ArithmeticException: / by zero
Job is going to be executed: jobGroup.jobId
Exception thrown by: jobGroup.jobId
Exception: java.lang.ArithmeticException: / by zero
Thu Sep 08 18:07:03 CEST 2011
Thu Sep 08 18:07:03 CEST 2011
Job is going to be executed: jobGroup.jobId
Exception thrown by: jobGroup.jobId
Exception: java.lang.ArithmeticException: / by zero
</pre>
<h2>Quartz installation for Maven 2</h2>
To add Quartz to a Maven 2 project, just add the following code to your <i>pom.xml</i> file.
<pre name="code" class="xml">
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.0.2</version>
</dependency>
</pre>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com8tag:blogger.com,1999:blog-8155967785119627415.post-81114740619260740532011-08-26T11:50:00.003+02:002011-09-08T21:03:33.084+02:00A stoppable Thread in JavaI am currently working on an application that has multiple different threads running. The threads are running loops and cannot be stopped using interrupts, because a clean up method has to run after the thread stops.
Because I don't want to implement the same code for all these thread classes, I created an abstract subclass of the Thread class. The new class provides the following new functionality to its subclasses:
<ol>
<li>Automatically call start up method when started
<li>Automatically call a method in an endless loop
<li>A way to stop the thread
<li>Automatically call clean up method when stopped
</ol>
The implemenation of this abstract class:
<pre name="code" class="java">
package com.javaeenotes;
public abstract class AbstractStoppableThread extends Thread {
private volatile boolean stopThread = false;
@Override
public final void run() {
startUp();
while (!stopThread) {
runInLoop();
}
cleanUp();
}
public void stopThread() {
stopThread = true;
}
protected void startUp() {
;
}
protected abstract void runInLoop();
protected void cleanUp() {
;
}
}
</pre>
A subclass of this class has to provide the actual overriding implementations of the last three methods. A class that demonstrates the use of the abstract class is shown next:
<pre name="code" class="java">
package com.javaeenotes;
public class ExampleThread extends AbstractStoppableThread {
@Override
protected void startUp() {
System.out.println("Thread started!");
}
@Override
protected void runInLoop() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
;
}
System.out.println("Running in a loop!");
}
@Override
protected void cleanUp() {
System.out.println("Cleaning up resources!");
}
public static void main(String[] args) {
ExampleThread exampleThread = new ExampleThread();
exampleThread.start();
try {
Thread.sleep(10000);
exampleThread.stopThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</pre>
When the example is class is run, the program will output the following:
<pre>
Thread started!
Running in a loop!
Running in a loop!
Running in a loop!
Running in a loop!
Running in a loop!
Cleaning up resources!
</pre>
<span style="font-weight:bold;">Other interesting links about stopping threads:</span>
<ul>
<li><a href="http://www.java2s.com/Code/Java/Threads/Thesafewaytostopathread.htm">The safe way to stop a thread</a>
<li><a href="http://www.roseindia.net/javatutorials/shutting_down_threads_cleanly.shtml">Shutting down threads cleanly</a>
</ul>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com2tag:blogger.com,1999:blog-8155967785119627415.post-47155444443140455902011-07-16T20:15:00.002+02:002011-07-16T20:18:37.036+02:00Some tips for application logging in JavaSome tips for application logging in Java<br /><br />In this blog post I want to share some of my thoughts about application logging in Java. Hopefully, you'd find them useful!<br /><br /><span style="font-weight:bold;">1. Consistent use of logging levels</span><br /><br />Have a good understanding of the available log levels, and make sure you use them consistently throughout the application. Especially, if you're using the old JDK 1.4 Logger framework. What is the difference between FINER and FINEST?<br /><br />Below is an abstract list of common log levels and a description of when to use them. This list is based on the Log4J log levels, but can be mapped to other logging frameworks.<br /><br /><span style="font-weight:bold;">FATAL</span><br />Unrecoverable errors. Leads to termination of the process (or a crash). Example: the application is in a corrupt state, and has no clue how to restore state.<br /><br /><span style="font-weight:bold;">ERROR</span><br />Errors that are not recoverable, but application can continue running. Example: an user request could not be executed, because some inputs are missing or invalid.<br /><br /><span style="font-weight:bold;">WARN</span><br />Undesirable or unexpected situations, but not necessarily "wrong". Example: the application expects a value in the cache, but could not find it. The application attempts to get the value in another way. Or a network connection is broken. The application tries to recover by reconnecting.<br /><br /><span style="font-weight:bold;">INFO</span><br />Important but normal run time events useful for monitoring. Example: a business process is finished.<br /><br /><span style="font-weight:bold;">DEBUG</span><br />Detailed information useful for debugging the system. Example: the content of a variable is printed in strategic locations of the application.<br /><br /><span style="font-weight:bold;">TRACE</span><br />Detailed control flow information. Example: a method is called message.<br /><br />Below is a mapping of log levels of different logging frameworks. Levels that have the same level of severities are placed on the same row.<br /><table><br /><tr><th style="text-align:left;vertical-align:top;">Carbon Severity Enum</th><th style="text-align:left;vertical-align:top;">Commons Log</th><th style="text-align:left;vertical-align:top;">Log4J</th><th style="text-align:left;vertical-align:top;">JDK 1.4 Logger</th><th style="text-align:left;vertical-align:top;">LogKit</th></tr><br /><tr><td>FATAL</td><td>FATAL</td><td>FATAL</td><td>SEVERE</td><td>FATAL_ERROR</td></tr><br /><tr><td>ERROR</td><td>ERROR</td><td>ERROR</td><td>SEVERE</td><td>ERROR</td></tr><br /><tr><td>WARN</td><td>WARN</td><td>WARN</td><td>WARNING</td><td>WARN</td></tr><br /><tr><td>INFO</td><td>INFO</td><td>INFO</td><td>INFO</td><td>INFO</td></tr><br /><tr><td>DEBUG</td><td>DEBUG</td><td>DEBUG</td><td>FINE</td><td>DEBUG</td></tr><br /><tr><td>DEBUG</td><td>DEBUG</td><td>DEBUG</td><td>FINER</td><td>DEBUG</td></tr><br /><tr><td>TRACE</td><td>TRACE</td><td>DEBUG</td><td>FINEST</td><td>DEBUG</td></tr><br /></table><br /><br /><span style="font-weight:bold;">2. Proper error logging</span><br /><br />Error logging should not be done at the location where an exception is thrown, but at the location where the exception is handled to prevent double logging.<br /><pre class="java" name="code"><br />public void doSomething() throws ACheckedException {<br /> if (someErrorCondition) {<br /> String errorMessage = "Hey, some error occurred.";<br /> logger.error(errorMessage);<br /> throw new ACheckedException(errorMessage);<br /> }<br />}<br /><br />public void callerMethod() {<br /> try {<br /> doSomething();<br /> } catch (ACheckedException exception) {<br /> logger.error(exception.getMessage());<br /> doSomethingElse();<br /> }<br />}<br /></pre><br />The code above will log the same error twice. The log statement in the first method can be removed. Exceptions should "bubble up" to the method of the class that can handle the error, and then be logged. In most cases this class will play the controller role in a MVC style application.<br /><br /><span style="font-weight:bold;">3. Prevent unnecessary string concatenations</span><br /><br />SLF4J is considered by many the best Java application logging framework. It's a logging facade that masks existing logging frameworks, which can be determined at deployment time. A great feature is that SLF4J allows you to avoid unnecessary string concatenation, which is really expensive.<br /><pre name="code" class="java"><br /> logger.error("The error '" + errorMessage +<br /> "' occurred in the " +<br /> component.getName() + " component.");<br /></pre><br />Of course, you can use logging guards like this:<br /><pre name="code" class="java"><br /> if (logger.isEnabledFor(Level.ERROR) {<br /> logger.error("The error '" + errorMessage +<br /> "' occurred in the " +<br /> component.getName() + " component.");<br /> }<br /></pre><br />But this will clutter your code, and degrades code readability.<br /><br />The SLF4J way looks like this:<br /><pre name="code" class="java"><br /> log.error("The error '{}' occurred in the {} component.",<br /> errorMessage, component.getName());<br /></pre><br />As you can see, the use of SLF4J makes the logging statement more readable, and SLF4J will not compile the log message when the message will not be logged (i.e. not running in a high enough log level).<br /><br /><span style="font-weight:bold;">4. Use complete logging messages</span><br /><br />Read logs, and check that the information in the log messages is complete, and can be used to reverse engineer back to the original state of the system.<br /><pre><br />01/02/2011 ERROR The user has a missing property.<br /></pre><br />The log message above could be improved by adding: the identifier for the user, and the name of the property, so it's easier to understand (and recreate) the situation that caused the log message. Another improvement is to add a message that gives information about what will happen next.<br /><br />If you also have tips or views about application logging in Java, please don't hesitate to share them in the comments!Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-44736928778428522542011-07-06T09:24:00.002+02:002011-07-06T09:30:17.623+02:00Restarting a Java application programmaticallyI found an interesting article through DZone (excellent site) about how to start a Java application programmatically. The original article can be found on the blog of Leo Lewis. Restarting a Java application is pretty useful for certain applications, where you don't have direct access to the deployment environment.<br /><br />Here is the orginal link to the article:<br /><a href="http://leolewis.website.org/wordpress/?p=499">http://leolewis.website.org/wordpress/?p=499</a>Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com1tag:blogger.com,1999:blog-8155967785119627415.post-68189123325199668202011-07-01T13:00:00.004+02:002011-07-01T13:10:05.657+02:00Mocking classes with JMockNormally, you'll get the following exception when you try to mock a class with <a href="http://www.jmock.org">jMock</a>:<br /><pre><br />java.lang.IllegalArgumentException:<br /> com.javaeenotes.YourClass is not an interface.<br /></pre><br />The solution is to use the ClassImposteriser when instantiating the <span style="font-style:italic;">Mockery</span> class.<br /><pre name="code" class="java"><br />context = new Mockery() {<br /> {<br /> setImposteriser(ClassImposteriser.INSTANCE);<br /> }<br />};<br /></pre><br />Now you can mock any class, just as interfaces. The complete instructions can be found on <a href="http://www.jmock.org./mocking-classes.html">this</a> web page.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-51389490763950558942011-06-28T16:11:00.003+02:002011-06-28T16:14:23.265+02:00Introduction to Java Concurrency / MultithreadingI came across a nice complete article about Java Concurrency:<br /><br /><a href="http://tutorials.jenkov.com/java-concurrency/index.html">Introduction to Java Concurrency / Multithreading</a><br /><br />Well written by Jakob Jenkov.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-87817852970743940082011-06-05T17:36:00.006+02:002011-09-15T10:17:58.404+02:00Short introduction to jMockThe jUnit framework is a great tool for testing your Java application. But writing test cases can be complex. Especially when the object under test is dependent on several other objects, which in turn depend on other objects. This means the whole dependency graph has to be created before the test can be executed. Building this graph can be complex, and error-prone.<br /><br />Luckily for us, there exists a framework called jMock. jMock enables you to create <a href="http://en.wikipedia.org/wiki/Mock_object">mock objects</a> that mimic behavior of dependent objects. We can configure the expected interaction and behavior of these objects.<br /><br />Let's start with an example class we want to test:<br /><pre name="code" class="java"><br />package com.javaeenotes;<br /><br />public class TestSubject {<br /> private DependentClassInterface depObject;<br /><br /> public TestSubject(DependentClassInterface depObject) {<br /> this.depObject = depObject;<br /> }<br /> <br /> public String method() {<br /> return depObject.method();<br /> }<br />}<br /></pre><br />The class is dependent on a class with the following interface:<br /><pre name="code" class="java"><br />package com.javaeenotes;<br /><br />public interface DependentClassInterface {<br /> public String method();<br />}<br /></pre><br />The interface specifies a method that returns a String. The actual implementation of this interface is not required for jMock. jMock uses the interface to create an object with the same interface you can use in your test cases.<br /><br />An example test case:<br /><pre name="code" class="java"><br />package com.javaeenotes;<br /><br />import static org.junit.Assert.assertTrue;<br /><br />import org.jmock.Expectations;<br />import org.jmock.Mockery;<br />import org.junit.Test;<br /><br />public class TestSubjectTest {<br /> @Test<br /> public void testMethod() {<br /> Mockery context = new Mockery();<br /> // Create mock object.<br /> final DependentClassInterface depObject = context<br /> .mock(DependentClassInterface.class);<br /><br /> // Test object is instantiated with mock object.<br /> TestSubject testSubject = new TestSubject(depObject);<br /><br /> // Configure expectation and behavior.<br /> context.checking(new Expectations() {<br /> {<br /> oneOf(depObject).method();<br /> will(returnValue("hello"));<br /> }<br /> });<br /><br /> // Test outcome.<br /> assertTrue(testSubject.method().equals("hello"));<br /><br /> // Check if expectations are satisfied.<br /> context.assertIsSatisfied();<br /><br /> }<br />}<br /></pre><br />In this test case, we create the object under test with a mock object. The expected interaction and behavior is then configured. First, the method() method is called, which then returns a string value "hello". Other interactions, like calling the same method twice, will result in an error.<br /><br />As you can see, jMock is a very valuable extension to the jUnit framework, which makes writing test cases much easier.<br /><br /><span style="font-weight:bold;">Links:</span><br /><ul><br /><li><a href="http://www.jmock.org">http://www.jmock.org</a><br /><li><a href="http://www.jmock.org/expectations.html">http://www.jmock.org/expectations.html</a><br /></ul><br /><br /><b>Note:</b> when running jMock in Eclipse, the following error can occur when running test cases:<br /><pre><br />java.lang.SecurityException:<br /> class "org.hamcrest.TypeSafeMatcher"'s signer information<br /> does not match signer information of other classes in the<br /> same package<br /></pre><br />The solution is make sure the jMock libraries are included before the standard jUnit libraries in the build path.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0tag:blogger.com,1999:blog-8155967785119627415.post-77863438843021172902011-05-19T19:23:00.003+02:002011-05-19T20:33:10.672+02:00Free resources associated with web clientsImagine we have the following problem. Resources are kept open for web clients as long as the clients are using them. When they leave, the resources have to be closed.<br /><br />Technically, we can say as long as the HttpSession is alive in the web container, the resources are kept open. When the HttpSession is invalidated, we need to call a method that frees the resources.<br /><br />A solution is to use the <a href="http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpSessionBindingListener.html">HttpSessionBindingListener </a>to solve this problem.<br /><br />The idea is to create a class that implements this interface. The unbound method contains or refers to the clean-up code. Whenever resources are opened, an instance of this class is created and saved to the corresponding session. When the session invalidates, which can happen by timeout, the web container automatically calls the method of the object in order to free open resources.<br /><br />The class:<br /><pre name="code" class="java"><br />package com.javaeenotes;<br /><br />import javax.servlet.http.HttpSessionBindingEvent;<br />import javax.servlet.http.HttpSessionBindingListener;<br /><br />public class Janitor implements HttpSessionBindingListener {<br /><br /> public void valueBound(HttpSessionBindingEvent arg0) {<br /> ;<br /> }<br /><br /> public void valueUnbound(HttpSessionBindingEvent arg0) {<br /> // Start some cleaning here.<br /> }<br />}<br /></pre><br /><br />Use the <a href="http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.6/api/javax/servlet/http/HttpSession.html#setAttribute%28java.lang.String,%20java.lang.Object%29">HttpSession.setAttribute()</a> method to save an instance of this class to the session.Anonymoushttp://www.blogger.com/profile/04721126777112597217noreply@blogger.com0