<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Benjamin McCann - Development Blog &#187; Java</title>
	<atom:link href="http://www.benmccann.com/dev-blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.benmccann.com/dev-blog</link>
	<description>The software development weblog of Benjamin McCann.</description>
	<lastBuildDate>Fri, 27 Jan 2012 01:34:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Embedded Tomcat</title>
		<link>http://www.benmccann.com/dev-blog/embedded-tomcat/</link>
		<comments>http://www.benmccann.com/dev-blog/embedded-tomcat/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 09:08:41 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=518</guid>
		<description><![CDATA[Earlier in the year, I posted a quick writeup on how to run an embedded Jetty instance. Today, I&#8217;m posting basically the same code showing how to run an embedded Tomcat instance. The embedded Tomcat API is much nicer since it matches closely the web.xml syntax. However, the embedded Tomcat instance takes much longer to [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier in the year, I posted a quick <a href="http://www.benmccann.com/dev-blog/embedded-jetty/">writeup on how to run an embedded Jetty instance</a>.  Today, I&#8217;m posting basically the same code showing how to run an embedded Tomcat instance.  The embedded Tomcat API is much nicer since it matches closely the web.xml syntax.  However, the embedded Tomcat instance takes much longer to startup.</p>
<pre><code>package com.benmccann.webtemplate.frontend.server;

import java.net.URL;

import org.apache.catalina.Context;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.deploy.FilterDef;
import org.apache.catalina.deploy.FilterMap;
import org.apache.catalina.startup.Tomcat;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import com.beust.jcommander.JCommander;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;

/**
 * @author Ben McCann (benmccann.com)
 */
public class WebServer {

  private final FrontendSettings webServerSettings;
  private final GuiceListener guiceListener;
  private final Tomcat tomcat;

  @Inject
  public WebServer(
      FrontendSettings webServerSettings,
      GuiceListener guiceListener) {
    this.webServerSettings = webServerSettings;
    this.guiceListener = guiceListener;
    this.tomcat = new Tomcat();
  }

  private FilterDef createFilterDef(String filterName, String filterClass) {
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(filterName);
    filterDef.setFilterClass(filterClass);
    return filterDef;
  }

  private FilterMap createFilterMap(String filterName, String urlPattern) {
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(filterName);
    filterMap.addURLPattern(urlPattern);
    return filterMap;
  }

  public void run() throws Exception {
    String appBase = ".";
    tomcat.setPort(webServerSettings.getPort());

    tomcat.setBaseDir("webapp");
    tomcat.getHost().setAppBase(appBase);

    String contextPath = "/";

    // Add AprLifecycleListener to give native speed boost
    // sudo apt-get install libtcnative-1
    StandardServer server = (StandardServer)tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context context = tomcat.addWebapp(contextPath, appBase);
    context.addFilterDef(createFilterDef("guice", GuiceFilter.class.getName()));
    FilterDef struts2FilterDef = createFilterDef("struts2",
        StrutsPrepareAndExecuteFilter.class.getName());
    struts2FilterDef.addInitParameter("struts.devMode",
        Boolean.toString(webServerSettings.isDevModeEnabled()));
    context.addFilterDef(struts2FilterDef);
    context.addFilterMap(createFilterMap("guice", "/*"));
    context.addFilterMap(createFilterMap("struts2", "/*"));

    tomcat.start();
    tomcat.getServer().await();
  }

  public static void main(String[] args) throws Exception {
    FrontendSettings webServerSettings = new FrontendSettings();
    new JCommander(webServerSettings, args);

    Guice.createInjector(new FrontendModule(webServerSettings));

    Injector injector = Guice.createInjector();

    WebServer server = injector.getInstance(WebServer.class);
    server.run();
  }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/embedded-tomcat/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Guice Struts 2 plugin</title>
		<link>http://www.benmccann.com/dev-blog/guice-3-struts-2-plugin/</link>
		<comments>http://www.benmccann.com/dev-blog/guice-3-struts-2-plugin/#comments</comments>
		<pubDate>Tue, 29 Mar 2011 22:43:25 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Struts 2]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=449</guid>
		<description><![CDATA[Guice 3.0 was released a few days ago!  One of the easiest ways to use it in your web server is to use Struts 2 with the Struts 2 plugin, which is available in the central Maven repository. This tutorial assumes familiarity with Guice and Struts 2. In order to use it the plugin, your [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/google-guice/">Guice</a> 3.0 was released a few days ago!  One of the easiest ways to use it in your web server is to use Struts 2 with the <a href="http://struts.apache.org/">Struts 2</a> plugin, which is <a href="http://repo2.maven.org/maven2/com/google/inject/extensions/guice-struts2/3.0/">available in the central Maven repository</a>.</p>
<p>This tutorial assumes familiarity with Guice and Struts 2.</p>
<p>In order to use it the plugin, your injector must be created with a Struts2GuicePluginModule:</p>
<pre><code>Injector injector = Guice.createInjector(
    new com.google.inject.servlet.ServletModule(),
    new com.google.inject.struts2.Struts2GuicePluginModule(),
    new MyModule());</code></pre>
<p>You must then define a GuiceServletContextListener to provide the injector to the Struts 2 plugin.  I injected the Injector because I&#8217;m using embedded Jetty.  However, if you&#8217;re using a standard servlet container, you&#8217;d probably just create the injector in the class itself.</p>
<pre><code>package com.benmccann.example;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

/**
 * @author benmccann.com
 */
public class GuiceListener extends GuiceServletContextListener {

  private final Injector injector;

  @Inject
  public GuiceListener(Injector injector) {
    this.injector = injector;
  }

  @Override
  public Injector getInjector() {
    return injector;
  }

}</code></pre>
<p>You must then wire it up in your web.xml:</p>
<pre><code>  &lt;listener&gt;
    &lt;listener-class&gt;com.benmccann.example.GuiceListener&lt;/listener-class&gt;
  &lt;/listener&gt;  

  &lt;filter&gt;
    &lt;filter-name&gt;guice&lt;/filter-name&gt;
    &lt;filter-class&gt;com.google.inject.servlet.GuiceFilter&lt;/filter-class&gt;
  &lt;/filter&gt;

  &lt;filter-mapping&gt;
    &lt;filter-name&gt;guice&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;</code></pre>
<p>There&#8217;s also an <a href="http://code.google.com/p/google-guice/source/browse/#svn%2Ftrunk%2Fextensions%2Fstruts2%2Fexample">example in the Guice source code repository</a>.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/guice-3-struts-2-plugin/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Remote Java debugging in Eclipse</title>
		<link>http://www.benmccann.com/dev-blog/remote-java-debugging-in-eclipse/</link>
		<comments>http://www.benmccann.com/dev-blog/remote-java-debugging-in-eclipse/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 06:20:30 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=434</guid>
		<description><![CDATA[To debug a Java program being run on the command line from Eclipse you can start the Java program in remote debugging mode: java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y -jar myProgram.jar The program will wait for you to attach the Eclipse debugger to it. Open Eclipse and choose: Run > Debug Configurations... > Remote Java Application > New [...]]]></description>
			<content:encoded><![CDATA[<p>To debug a Java program being run on the command line from Eclipse you can start the Java program in remote debugging mode:</p>
<pre><code>java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y -jar myProgram.jar</code></pre>
<p>The program will wait for you to attach the Eclipse debugger to it.  Open Eclipse and choose:</p>
<pre><code>Run > Debug Configurations... > Remote Java Application > New</code></pre>
<p>Make sure to enter the same port that you chose on the command line.  The default is port 8000.  Now hit &#8220;Debug&#8221; and you&#8217;re off!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/remote-java-debugging-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google GXP Struts 2 Plugin</title>
		<link>http://www.benmccann.com/dev-blog/google-gxp-struts-2-plugin/</link>
		<comments>http://www.benmccann.com/dev-blog/google-gxp-struts-2-plugin/#comments</comments>
		<pubDate>Thu, 03 Feb 2011 03:40:58 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[GXP]]></category>
		<category><![CDATA[Struts 2]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=392</guid>
		<description><![CDATA[Google GXP is a replacement for JSP that provides compile-time type safety.  This article is a quick introduction on how to use GXP with Struts 2. &#160; 1. Download the jar.  It&#8217;s not in Maven yet because it&#8217;s still unreleased. &#160; 2. Install the jar in Maven or otherwise put it on your classpath.  You&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<div><a href="http://code.google.com/p/gxp/">Google GXP</a> is a replacement for JSP that provides compile-time type safety.  This article is a quick introduction on how to use GXP with Struts 2.</div>
<div>&nbsp;</div>
<div>1. Download <a href="https://hudson.apache.org/hudson/job/Struts2/lastBuild/org.apache.struts$struts2-gxp-plugin/artifact/org.apache.struts/struts2-gxp-plugin/2.2.2-SNAPSHOT/struts2-gxp-plugin-2.2.2-SNAPSHOT.jar">the jar</a>.  It&#8217;s not in Maven yet because it&#8217;s still unreleased.</div>
<div>&nbsp;</div>
<div>2. Install the jar in Maven or otherwise put it on your classpath.  You&#8217;ll also need the Google GXP jar and the Google Collections jar:</div>
<pre><code>  &lt;dependency&gt;
    &lt;groupId&gt;com.google.gxp&lt;/groupId&gt;
    &lt;artifactId&gt;gxp-plugin&lt;/artifactId&gt;
    &lt;version&gt;2.2.2-SNAPSHOT&lt;/version&gt;
    &lt;scope&gt;system&lt;/scope&gt;
    &lt;systemPath&gt;${basedir}/lib/struts2-gxp-plugin-2.2.2-SNAPSHOT.jar&lt;/systemPath&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;com.google.gxp&lt;/groupId&gt;
    &lt;artifactId&gt;google-gxp&lt;/artifactId&gt;
    &lt;version&gt;0.2.4-beta&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;com.google.collections&lt;/groupId&gt;
    &lt;artifactId&gt;google-collections&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
  &lt;/dependency&gt;</code></pre>
<p>3. Call the GXP compiler.  E.g.</p>
<pre><code>java -cp lib/gxp-0.2.4-beta.jar com.google.gxp.compiler.cli.Gxpc --output_language java com/benmccann/example/web/gxp/*.gxp</code></pre>
<p>4. Add a result type of <em>gxp</em> to your struts.xml:</p>
<pre><code>  &lt;package name="test" extends="gxp-default"&gt;
    &lt;action name="TestAction" class="com.benmccann.example.web.action.TestAction"&gt;
      &lt;result type="gxp"&gt;com/benmccann/example/web/gxp/Index.gxp&lt;/result&gt;
    &lt;/action&gt;
  &lt;/package&gt;</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/google-gxp-struts-2-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Commons Math vs. ojAlgo</title>
		<link>http://www.benmccann.com/dev-blog/commons-math-vs-ojalgo/</link>
		<comments>http://www.benmccann.com/dev-blog/commons-math-vs-ojalgo/#comments</comments>
		<pubDate>Sun, 23 Jan 2011 23:00:13 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=373</guid>
		<description><![CDATA[There are numerous math libraries for Java.   This is frustrating as a user because it&#8217;s hard to decide which to use.   Sometimes an algorithm is implemented in one library, but not another, which means you must marshal your data between proprietary formats.  I was working on solving systems of linear equations and there [...]]]></description>
			<content:encoded><![CDATA[<p>There are numerous math libraries for Java.   This is frustrating as a user because it&#8217;s hard to decide which to use.   Sometimes an algorithm is implemented in one library, but not another, which means you must marshal your data between proprietary formats.  I was working on solving systems of linear equations and there was no good Java-only solution available, so I had to write my own.  I decided to contribute the <a href="http://commons.apache.org/math/apidocs/org/apache/commons/math/optimization/linear/SimplexSolver.html">SimplexSolver</a> to <a href="http://commons.apache.org/math/">Commons Math</a> because it used a friendly license and because it already had significant mindshare.  After doing so, I was informed that ojAlgo has a LinearSolver as well.  Today I decided to test it out to see whether I&#8217;d wasted my time by writing my own implementation.  It turns out that the ojAlgo implementation is buggy as shown by the unit test below which I created.</p>
<pre><code>package com.benmccann.test;

import static org.ojalgo.constant.BigMath.EIGHT;
import static org.ojalgo.constant.BigMath.FIVE;
import static org.ojalgo.constant.BigMath.FOUR;
import static org.ojalgo.constant.BigMath.ONE;
import static org.ojalgo.constant.BigMath.SEVEN;
import static org.ojalgo.constant.BigMath.SIX;
import static org.ojalgo.constant.BigMath.TEN;
import static org.ojalgo.constant.BigMath.TENTH;
import static org.ojalgo.constant.BigMath.THREE;
import static org.ojalgo.constant.BigMath.TWO;
import static org.ojalgo.constant.BigMath.ZERO;

import java.math.BigDecimal;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.ojalgo.matrix.BasicMatrix;
import org.ojalgo.matrix.store.PhysicalStore;
import org.ojalgo.matrix.store.PrimitiveDenseStore;
import org.ojalgo.optimisation.OptimisationSolver;
import org.ojalgo.optimisation.Variable;
import org.ojalgo.optimisation.OptimisationSolver.Result;
import org.ojalgo.optimisation.linear.LinearExpressionsModel;

public class SolverTest {

  @Test
  public void testMath286() {

    Variable[] objective = new Variable[] {
        new Variable("X1").weight(TENTH.multiply(EIGHT)),
        new Variable("X2").weight(TENTH.multiply(TWO)),
        new Variable("X3").weight(TENTH.multiply(SEVEN)),
        new Variable("X4").weight(TENTH.multiply(THREE)),
        new Variable("X5").weight(TENTH.multiply(SIX)),
        new Variable("X6").weight(TENTH.multiply(FOUR))};

    LinearExpressionsModel model = new LinearExpressionsModel(objective);
    model.setMaximisation(true);

    model.addWeightExpression("C1",
            new BigDecimal[] { ONE, ZERO, ONE, ZERO, ONE, ZERO }
        ).level(new BigDecimal(23));
    model.addWeightExpression("C2",
            new BigDecimal[] { ZERO, ONE, ZERO, ONE, ZERO, ONE }
        ).level(new BigDecimal(23));
    model.addWeightExpression("C3",
            new BigDecimal[] { ONE, ZERO, ZERO, ZERO, ZERO, ZERO }
        ).lower(TEN);
    model.addWeightExpression("C4",
            new BigDecimal[] { ZERO, ZERO, ONE, ZERO, ZERO, ZERO }
        ).lower(EIGHT);
    model.addWeightExpression("C5",
            new BigDecimal[] { ZERO, ZERO, ZERO, ZERO, ONE, ZERO }
        ).lower(FIVE);

    Result result = model.getDefaultSolver().solve();
    List solution = result.getSolution()
        .getRows(new int[] { 0, 1, 2, 3, 4, 5 })
        .toPrimitiveStore().asList();

    // A valid solution of 25.8 can be produced with:
    //     X1=10, X2=0, X3=8, X4=0, X5=5, X6=23
    // However, ojAlgo returns 21.7
    Assert.assertEquals(25.8, solution.get(0) * .8 + solution.get(1) * .2
        + solution.get(2) * .7 + solution.get(3) * .3
        + solution.get(4) * .6 + solution.get(5) * .4, .1);
  }

}</code></pre>
<p>After releasing the Common Math SimplexSolver, I received numerous bug reports, which has been the main benefit of open sourcing it.  The code is now more robust as a result.  The test above was just one of many cases that Commons Math initially had trouble with, so I don&#8217;t fault the ojAlgo developers for getting it wrong the first time around &#8211; I did too.  However, I&#8217;m glad I chose to contribute to a well-recognized project because it led to flushing out many of these problems.  A lesser known project such as ojAlgo doesn&#8217;t have that advantage.  I&#8217;m not sure why so many people are still writing their own smaller libraries instead of contributing to make the larger players better.  Hopefully ojAlgo will consider recommitting its efforts towards Commons Math or another of the larger projects at some point.  It would be good for the community to see some consolidation.  At one point, <a href="http://mail-archives.apache.org/mod_mbox/incubator-hama-dev/200905.mbox/%3Ceb4706e0905221017n75bbf14bwe3ef6aec42adb7e2@mail.gmail.com%3E">matrix-toolkits-java was talking about combining with Commons Math</a>, which would be a great move towards consolidated APIs.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/commons-math-vs-ojalgo/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Embedded Jetty</title>
		<link>http://www.benmccann.com/dev-blog/embedded-jetty/</link>
		<comments>http://www.benmccann.com/dev-blog/embedded-jetty/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 08:01:16 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Embedded Jetty]]></category>
		<category><![CDATA[JCommander]]></category>
		<category><![CDATA[Jetty]]></category>
		<category><![CDATA[Struts 2]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=362</guid>
		<description><![CDATA[One of the coolest things about Jetty is the ability to run it in embedded mode.  This means that you can write a Java app with a main method that will launch a Jetty server.  This has some really nice benefits.  For example, it makes it really easy to deploy a server to EC2 because [...]]]></description>
			<content:encoded><![CDATA[<p>One of the coolest things about Jetty is the ability to run it in <a href="http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jettay">embedded mode</a>.  This means that you can write a Java app with a main method that will launch a Jetty server.  This has some really nice benefits.  For example, it makes it really easy to deploy a server to <a href="http://aws.amazon.com/ec2/">EC2</a> because all you need to do is transfer your jar file there and hit run &#8211; no need to setup a servlet container, etc.  Also, it makes it possible to dynamically set servlet parameters such as <a href="http://struts.apache.org/2.2.1.1/docs/devmode.html">Struts 2 devMode</a>.  You can set a flag on the command line, parse it using a library such as <a href="http://jcommander.org/">JCommander</a>, and then run in development mode depending upon what was requested by the flag passed in.</p>
<p>You first need to get the relevant jars included in your project as dependencies.  All of the dependencies are available in Maven repositories.  I use <a href="http://gradle.org/">Gradle</a>, so you may not be familiar with the syntax below, but you can take the parts between the colons and enter them as the groupId, artifactId, and version if you&#8217;re using Maven.</p>
<p><code>  compile 'org.eclipse.jetty:jetty-io:8.0.0.M3'<br />
  compile 'org.eclipse.jetty:jetty-server:8.0.0.M3'<br />
  compile 'org.eclipse.jetty:jetty-servlet:8.0.0.M3'<br />
  compile 'org.eclipse.jetty:jetty-util:8.0.0.M3'<br />
  compile 'org.eclipse.jetty:jetty-webapp:8.0.0.M3'<br />
  compile 'org.mortbay.jetty:jsp-2.1-glassfish:2.1.v20100127'</code></p>
<p>Here&#8217;s an example of running a web app in Jetty&#8217;s embedded mode:</p>
<pre><code>package com.benmccann.example.server;

import java.net.URL;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.webapp.WebAppContext;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;

/**
 * @author benmccann.com
 */
public class WebServer {

  private final Server server;

  public WebServer() {
    this.server = createNewServer();
  }

  private Server createNewServer() {
    Server server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8080);
    server.addConnector(connector);

    WebAppContext webApp = new WebAppContext(getBaseUrl(), "/");
    webApp.addEventListener(new GuiceListener());

    ServletHandler handler = createServletHandler();
    webApp.setServletHandler(handler);
    webApp.setErrorHandler(createErrorHandler());
    server.setHandler(webApp);

    return server;
  }

  private ErrorHandler createErrorHandler() {
    ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
    errorHandler.addErrorPage(500, "/error.html");
    return errorHandler;
  }

  private ServletHandler createServletHandler() {
    ServletHandler servletHandler = new ServletHandler();

    FilterHolder guiceFilterHolder = createGuiceFilterHolder();
    servletHandler.addFilter(guiceFilterHolder,
        createFilterMapping("/*", guiceFilterHolder));

    FilterHolder strutsFilterHolder = createStrutsFilterHolder();
    servletHandler.addFilter(strutsFilterHolder,
        createFilterMapping("/*", strutsFilterHolder));    

    return servletHandler;
  }

  private FilterHolder createGuiceFilterHolder() {
    FilterHolder filterHolder = new FilterHolder(GuiceFilter.class);
    filterHolder.setName("guice");
    return filterHolder;
  }

  private FilterHolder createStrutsFilterHolder() {
    FilterHolder filterHolder
        = new FilterHolder(StrutsPrepareAndExecuteFilter.class);
    filterHolder.setName("struts2");
    filterHolder.setInitParameter("struts.devMode", "true");
    return filterHolder;
  }

  private FilterMapping createFilterMapping(
      String pathSpec, FilterHolder filterHolder) {
    FilterMapping filterMapping = new FilterMapping();
    filterMapping.setPathSpec(pathSpec);
    filterMapping.setFilterName(filterHolder.getName());
    return filterMapping;
  }

  public void run() throws Exception {
    server.start();
    server.join();
  }

  private String getBaseUrl() {
    URL webInfUrl = WebServer.class.getClassLoader().getResource("WEB-INF");
    String webInfUrlString = webInfUrl.toExternalForm();
    return webInfUrlString.substring(0, webInfUrlString.lastIndexOf('/') + 1);
  }

  public static void main(String[] args) throws Exception {
    WebServer server = new WebServer();
    server.run();
  }

}
</code></pre>
<p>This web app used the <a href="http://struts.apache.org/2.x/index.html">Struts 2</a> filter and the <a href="http://code.google.com/p/google-guice/">Guice</a> filter.  However, we specified them in code instead of in the web.xml.  We hardcoded struts.devMode to true, but you can easily see how we could make it true or false at runtime whereas that is impossible using a web.xml file.</p>
<p>You can also <a href="http://www.benmccann.com/dev-blog/embedded-tomcat/">run Tomcat in embedded mode</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/embedded-jetty/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Hibernate with JPA Annotations and Guice</title>
		<link>http://www.benmccann.com/dev-blog/hibernate-with-jpa-annotations-and-guice/</link>
		<comments>http://www.benmccann.com/dev-blog/hibernate-with-jpa-annotations-and-guice/#comments</comments>
		<pubDate>Sun, 02 May 2010 05:49:20 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=260</guid>
		<description><![CDATA[In this tutorial, I use the H2 database, which you can utilize by downloading the jar or you can replace with your own DB. First off, you need to create a persistence.xml in a folder named META-INF at the root of your classpath. For example, if you&#8217;re using Maven you can create src/main/java/META-INF/persistence.xml. It lists [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, I use the <a href="http://www.h2database.com">H2 database</a>, which you can utilize by downloading the jar or you can replace with your own DB.</p>
<p>First off, you need to create a persistence.xml in a folder named META-INF at the root of your classpath.  For example, if you&#8217;re using <a href="http://maven.apache.org/">Maven</a> you can create src/main/java/META-INF/persistence.xml.  It lists all the classes you want <a href="http://www.hibernate.org/">Hibernate</a> to persist and any other Hibernate properties you might want to specify.  I also define Hibernate properties later on in the tutorial when creating the <a href="http://java.sun.com/javaee/6/docs/api/index.html?javax/persistence/EntityManagerFactory.html">EntityManagerFactory</a>.</p>
<pre><code>&lt;persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0"&gt;
  &lt;persistence-unit name="db-manager"&gt;
    &lt;class&gt;com.benmccann.db.ExamplePersistedClass&lt;/class&gt;
    &lt;properties&gt;
      &lt;!-- Disable the second-level cache  --&gt;
      &lt;property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/&gt;

      &lt;!-- Default is false for backwards compatibility.  Should be used on all new projects --&gt;
      &lt;property name="hibernate.id.new_generator_mappings" value="true"/&gt;
    &lt;/properties&gt;
  &lt;/persistence-unit&gt;
&lt;/persistence></code></pre>
<p>We listed the class com.benmccann.db.ExamplePersistedClass as being the only persisted class, so now we&#8217;ll go ahead and create it.  Note that you need a no-argument constructor.  Fields in your bean will be persisted unless annotated with @Transient.  <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/persistent-classes.html">More info about persisted classes is available in the Hibernate documentation</a>.</p>
<pre><code>package com.benmccann.db;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class ExamplePersistedClass {

  @Id
  @GeneratedValue
  private Long id;

  private String otherField;

  public ExamplePersistedClass() {}

  public void setId(Long id) {
    this.id = id;
  }

  public Long getId() {
    return id;
  }

  public void setOtherField(String otherField) {
    this.otherField = otherField;
  }

  public String getOtherField() {
    return otherField;
  }

}</code></pre>
<p>And we&#8217;ll create a DAO for it:</p>
<pre><code>package com.benmccann.db;

import javax.persistence.EntityManager;

public class ExamplePersistedClassDao {

  protected EntityManager entityManager;

  @Inject
  public ExamplePersistedClassDao(EntityManager entityManager) {
    this.entityManager = entityManager;
  }

  public void saveInNewTransaction(ExamplePersistedClass object) {
    entityManager.getTransaction().begin();
    save(object);
    entityManager.getTransaction().commit();
  }

  public void save(ExamplePersistedClass object) {
    entityManager.persist(object);
  }

  public ExamplePersistedClass getByOtherField(String otherField) {
    return (ExamplePersistedClass) entityManager
        .createQuery("select e from ExamplePersistedClass e where e.otherField=:otherField")
        .setParameter("otherField", otherField)
        .getSingleResult();
  }

}
</code></pre>
<p>And finally, we&#8217;ll create a <a href="http://code.google.com/p/google-guice/wiki/GettingStarted">Guice module</a> to define the injection.  Note that EntityManagerFactory is thread-safe while <a href="http://java.sun.com/javaee/6/docs/api/index.html?javax/persistence/EntityManager.html">EntityManager</a> is not.  I use <a href="http://java.sun.com/javase/6/docs/api/index.html?java/lang/ThreadLocal.html">ThreadLocal</a> storage here in order to have one entity manager per thread.  When creating the EntityManagerFactory notice that I use the same &#8220;db-manager&#8221; string that is defined in the persistence.xml file.  Also, I defined most of my Hibernate properties here rather than in the persistence.xml file to demonstrate how you can alter the values of these properties.  For example, when writing tests it could be very helpful to override the connection string to point to a local test database.</p>
<pre><code>package com.benmccann.db;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;

/**
 * @author Ben McCann (benmccann.com)
 */
public class DbModule extends AbstractModule {

  private static final ThreadLocal&lt;EntityManager&gt; ENTITY_MANAGER_CACHE
      = new ThreadLocal&lt;EntityManager&gt;();

  public void configure() {
  }

  @Provides @Singleton
  public EntityManagerFactory provideEntityManagerFactory() {
    Map&lt;String, String&gt; properties = new HashMap&lt;String, String&gt;();
    properties.put("hibernate.connection.driver_class", "org.h2.Driver");
    properties.put("hibernate.connection.url", "jdbc:h2:test");
    properties.put("hibernate.connection.username", "sa");
    properties.put("hibernate.connection.password", "");
    properties.put("hibernate.connection.pool_size", "1");
    properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.put("hibernate.hbm2ddl.auto", "create");
    return Persistence.createEntityManagerFactory("db-manager", properties);
  }

  @Provides
  public EntityManager provideEntityManager(EntityManagerFactory entityManagerFactory) {
    EntityManager entityManager = ENTITY_MANAGER_CACHE.get();
    if (entityManager == null) {
      ENTITY_MANAGER_CACHE.set(entityManager = entityManagerFactory.createEntityManager());
    }
    return entityManager;
  }

}</code></pre>
<p>Now we can run our code:</p>
<pre><code>package com.benmccann.db;

import java.sql.SQLException;
import java.util.Date;

import org.junit.Assert;
import org.junit.Test;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.benmccann.db.DbModule;
import com.benmccann.db.ExamplePersistedClass;
import com.benmccann.db.ExamplePersistedClassDao;

public class H2DBTest {

  @Test
  public void testDb() throws SQLException {
    Injector injector = Guice.createInjector(new DbModule());
    ExamplePersistedClassDao examplePersistedClassDao = injector.getInstance(ExamplePersistedClassDao.class);   

    ExamplePersistedClass example = new ExamplePersistedClass();
    example.setOtherField("hello world");
    examplePersistedClassDao .saveInNewTransaction(quote);

    ExamplePersistedClass retrieved = examplePersistedClassDao.getByOtherField("hello world");

    Assert.assertEquals(example.getId(), retrieved.getId());
    Assert.assertEquals(example.getOtherField(), retrieved.getOtherField());
  }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/hibernate-with-jpa-annotations-and-guice/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Using Struts 2 on Google App Engine</title>
		<link>http://www.benmccann.com/dev-blog/using-struts-2-on-google-app-engine/</link>
		<comments>http://www.benmccann.com/dev-blog/using-struts-2-on-google-app-engine/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 07:50:15 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Struts 2]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=240</guid>
		<description><![CDATA[Google App Engine (GAE) has some great benefits such as scalability and the fact that it&#8217;s free to start.  When using Struts 2 with Google App Engine there a few things to keep in mind. The first is that it runs inside a security sandbox that is more restrictive than your typical Java environment.  This [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/appengine/">Google App Engine (GAE)</a> has some great benefits such as scalability and the fact that it&#8217;s free to start.  When using <a href="http://struts.apache.org/2.x/index.html">Struts 2</a> with Google App Engine there a few things to keep in mind.</p>
<p>The first is that it runs inside a security sandbox that is more restrictive than your typical Java environment.  This means that <a href="http://www.opensymphony.com/ognl/">OGNL</a>, the expression language that Struts 2 uses, will not work correctly out of the box.  You can fix this by adding a listener as described in <a href="http://programmingpanda.blogspot.com/2009/07/struts-2-ongl-issue-on-google-app.html">this article</a>.  An example listener can be found <a href="http://code.google.com/p/usaopengov/source/browse/trunk/src/org/usaopengov/action/security/OgnlFixListener.java">here</a> and is used in <a href="http://code.google.com/p/usaopengov/source/browse/trunk/war/WEB-INF/web.xml">this web.xml file</a>.</p>
<p>The second problem is that Google App Engine has some special URLs that it uses.  If you try to visit them, Struts 2 will attempt to process the request as if it&#8217;s a Struts 2 Action and will bomb out when the Action can&#8217;t be found.  You can add an exclusion filter to your struts.xml to counteract this problem:</p>
<pre><code>&lt;constant name="struts.action.excludePattern" value="/_ah/.*"/&gt;</code></pre>
<p>﻿</p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/using-struts-2-on-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Case Study: Usable and Unusable APIs</title>
		<link>http://www.benmccann.com/dev-blog/case-study-good-and-bad-apis/</link>
		<comments>http://www.benmccann.com/dev-blog/case-study-good-and-bad-apis/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 00:13:50 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=210</guid>
		<description><![CDATA[It was the best of times, it was the worst of times&#8230; It was the age of wisdom, it was the season of light.  A great library called dom4j was written with its users in mind.  It included a quick start guide and a cookbook for people that actually wanted to get things done.  Converting [...]]]></description>
			<content:encoded><![CDATA[<p>It was the best of times, it was the worst of times&#8230;</p>
<p>It was the age of wisdom, it was the season of light.  A great library called <a href="http://www.dom4j.org/dom4j-1.6.1/guide.html">dom4j</a> was written with its users in mind.  It included a <a href="http://www.dom4j.org/dom4j-1.6.1/guide.html">quick start guide</a> and a <a href="http://www.dom4j.org/dom4j-1.6.1/cookbook.html">cookbook</a> for people that actually wanted to get things done.  Converting a document to a String took 15 characters: document.asXML().  But there were too many competing XML parsing implementations, so a <a href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/Document.html">standard</a> was created.  And sadly, dom4j has not been updated to adhere to that standard.</p>
<p>It was the age of foolishness, it was the epoch of incredulity.  15 characters to turn a document into a string?  That is far too few.  What will we tell our managers when they ask how many lines of code we have written?  We have a better way and it is called <a href="http://xerces.apache.org/xerces-j/">Xerces</a>:<br />
<code>
<pre>import java.io.StringWriter;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public final class XmlUtil {

  private static final TransformerFactory factory = TransformerFactory.newInstance();

  public static String toString(Node node) {
    if (node == null) {
      return null;
    }
    try {
      Source source = new DOMSource(node);
      StringWriter stringWriter = new StringWriter();
      Result result = new StreamResult(stringWriter);
      Transformer transformer = factory.newTransformer();
      transformer.transform(source, result);
      return stringWriter.getBuffer().toString();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
    return null;
  }

}</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/case-study-good-and-bad-apis/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Sample log4j.properties file</title>
		<link>http://www.benmccann.com/dev-blog/sample-log4j-properties-file/</link>
		<comments>http://www.benmccann.com/dev-blog/sample-log4j-properties-file/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 21:45:14 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[log4j]]></category>

		<guid isPermaLink="false">http://www.benmccann.com/dev-blog/?p=206</guid>
		<description><![CDATA[I always find the hardest part of getting started with log4j is creating a log4j.properties file. For that reason, I&#8217;ve posted an example below. This file configures log4j to log any messages of level info or higher to the console except for classes under the com.dappit.Dapper.parser or org.w3c.tidy packages. #------------------------------------------------------------------------------ # # The following properties [...]]]></description>
			<content:encoded><![CDATA[<p>I always find the hardest part of getting started with log4j is creating a log4j.properties file.  For that reason, I&#8217;ve posted an example below. This file configures log4j to log any messages of level info or higher to the console except for classes under the com.dappit.Dapper.parser or org.w3c.tidy packages.</p>
<pre><code>#------------------------------------------------------------------------------
#
#  The following properties set the logging levels and log appender.  The
#  log4j.rootCategory variable defines the default log level and one or more
#  appenders.  For the console, use 'S'.  For the daily rolling file, use 'R'.
#  For an HTML formatted log, use 'H'.
#
#  To override the default (rootCategory) log level, define a property of the
#  form (see below for available values):
#
#        log4j.logger. =
#
#    Available logger names:
#      TODO
#
#    Possible Log Levels:
#      FATAL, ERROR, WARN, INFO, DEBUG
#
#------------------------------------------------------------------------------
log4j.rootCategory=INFO, S

log4j.logger.com.dappit.Dapper.parser=ERROR
log4j.logger.org.w3c.tidy=FATAL

#------------------------------------------------------------------------------
#
#  The following properties configure the console (stdout) appender.
#  See http://logging.apache.org/log4j/docs/api/index.html for details.
#
#------------------------------------------------------------------------------
log4j.appender.S = org.apache.log4j.ConsoleAppender
log4j.appender.S.layout = org.apache.log4j.PatternLayout
log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

#------------------------------------------------------------------------------
#
#  The following properties configure the Daily Rolling File appender.
#  See http://logging.apache.org/log4j/docs/api/index.html for details.
#
#------------------------------------------------------------------------------
log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = logs/bensApps.log
log4j.appender.R.Append = true
log4j.appender.R.DatePattern = '.'yyy-MM-dd
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

#------------------------------------------------------------------------------
#
#  The following properties configure the Rolling File appender in HTML.
#  See http://logging.apache.org/log4j/docs/api/index.html for details.
#
#------------------------------------------------------------------------------
log4j.appender.H = org.apache.log4j.RollingFileAppender
log4j.appender.H.File = logs/bensApps.html
log4j.appender.H.MaxFileSize = 100KB
log4j.appender.H.Append = false
log4j.appender.H.layout = org.apache.log4j.HTMLLayout</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.benmccann.com/dev-blog/sample-log4j-properties-file/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>

