A.J.

Someday somehow someone is going to steal your carbon.

Apparently Chrome doesn’t like HTML files

with one comment

Screen shot 2009-11-11 at 11.14.37 AM

Advertisements

Written by AJ

November 11, 2009 at 12:20 pm

Posted in Uncategorized

Speaking at an SAO event Oct. 15th.

leave a comment »

all,

I will be speaking at the Software Association of Oregon’s “An Integrated Development Tools Stack: Soup-to-Nuts Implementation in Practice” event this coming thursday if anyone is intrested. More information can be found here:

Written by AJ

October 10, 2009 at 4:52 pm

Posted in Uncategorized

Uploadify and Stripes

with 2 comments

Uploadify is a pretty cool plugin for jquery that uses flash for a bulk uploader. The only sucky thing is the examples are for php.

So I wrote one for stripes:

git://github.com/ayax79/stripes-uploadify.git

Written by AJ

July 1, 2009 at 2:42 pm

Posted in java

Tagged with , , , ,

Driving Test Data with groovy + hibernate

leave a comment »

The appfuse guys have a pretty cool setup where they have the hibernate plugin and the dbunit plugin working together to reload your dev database with each build. While this rocks I would rather populate data using my existing hibernate model. Using gmaven I tied together a script to initialize everything.

In my pom I have the following two plugsin configured:

<plugin>

<groupId>org.codehaus.mojo</groupId>

<artifactId>hibernate3-maven-plugin</artifactId>

<version>2.2</version>

<configuration>

<components>

<component>

<name>hbm2ddl</name>

<implementation>annotationconfiguration</implementation>

<!--

Use 'jpaconfiguration' if you're using JPA.

<implementation>jpaconfiguration</implementation>

-->

</component>

</components>

<componentProperties>

<drop>true</drop>

<jdk5>true</jdk5>
<propertyfile>target/classes/jdbc.properties</propertyfile>

<skip>${maven.test.skip}</skip>

</componentProperties>

</configuration>

<executions>

<execution>
<phase>process-test-resources</phase>

<goals>

<goal>hbm2ddl</goal>

</goals>

</execution>

</executions>

<dependencies>

<dependency>

<groupId>${jdbc.groupId}</groupId>

<artifactId>${jdbc.artifactId}</artifactId>

<version>${jdbc.version}</version>

</dependency>

</dependencies>

</plugin>
<plugin>

                <groupId>org.codehaus.groovy.maven</groupId>

                <artifactId>gmaven-plugin</artifactId>

                <version>1.0-rc-5</version>

                <configuration>

                    <source>${pom.basedir}/src/test/resources/sampledata.groovy</source>

                </configuration>

                <executions>

                    <execution>

                        <id>populate-db</id>
<phase>test-compile</phase>

                        <goals>

                            <goal>execute</goal>

                        </goals>

                    </execution>

                </executions>

                <dependencies>

                    <dependency>

                        <groupId>${jdbc.groupId}</groupId>

                        <artifactId>${jdbc.artifactId}</artifactId>

                        <version>${jdbc.version}</version>

                    </dependency>

                </dependencies>

            </plugin>

Then I wrote the following script (that is referenced in the plugin above):


// initializes hibernate

this.sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory()

this.call = 0

class SaveDelegate {

  Session session

  DateTime now

  def save(o) {

    session.saveOrUpdate(o)

    session.flush()

    return o;

  }

// Used to save the objects.

def save(o) {

  def con = DriverManager.getConnection(project.properties['jdbc.url'], project.properties['jdbc.username'], project.properties['jdbc.password'])

  def session = this.sessionFactory.openSession(con)

  try {

    println call++

    if (o instanceof Closure) {

      return o.call(new SaveDelegate(session: session, now: this.now))

    }

    else {

      return new SaveDelegate(session: session, now: this.now).save(o)

    }

  } catch (e) {

    System.err.println e.message

    return null;

  } finally {

    session.close()

    con.close()

  }

}

try {

// The save function above lets me handle objects in different ways:

// just save an instance

save new Person(name: 'Issac Brock')

// save with a reference

def f = save(new Person(name:'Jimmy Paige'))

// and finally with a closure

def f = save { s ->

   def f = new Person(name: "Scott Weiland")

... do other stuff

  return s.save f

}

} finally {

//cleanup

this.sessionFactory.close()

}

}

Written by AJ

June 18, 2009 at 4:55 pm

Posted in Uncategorized

JMock Map Matcher Example

leave a comment »

Quick example of how to use jmock matchers with maps.

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;

// Static imports for the IsMapContaing matchers
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;

import org.hamcrest.collection.IsMapContaining;
import static org.hamcrest.core.AllOf.allOf;
import org.hamcrest.core.AllOf;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.HashMap;

@RunWith(JMock.class)
public class DefaultReportDaoUnitTest
{

    Mockery mockery = new JUnit4Mockery();

    @Test
    public void testFoo() {

        final MyStuff mine = mockery.mock(MyStuff.class, "mine");

        mockery.checking(new Expectations()
        {{

            // I usually seperate this from being inline
            // so that I can get the generic type right easier
            Matcher<Map<String, ?>> mapMatcher =
                AllOf.<Map<String, ?>>allOf(
                        hasEntry("foo", "one"),
                        hasEntry("bar", "two"),
                        hasKey("baz")
                );        

            // Use the map mapmatcher we defined
            // expect one call of 
            oneOf(mine).doSomething(with(mapMatcher));                                                        
        }};

        Map<String,String> map = new HashMap<String,String>(3);
        map.put("foo", "one");
        map.put("bar", "two");
        map.put("baz", "three");

        mine.doSometing(map);                

    }        

}        

Written by AJ

February 19, 2009 at 5:41 pm

Posted in java

Making Spring MVC and CXF play well together

with 4 comments

I have found the spring mvc and CXF really don’t play very well together. When using spring MVC is you are pretty much stuck using the spring DispatcherServlet which for some odd reason doesn’t well with the spring ContextLoaderListener and wants to initialize the config files itself.

The problem with this that if you use the DispatcherServlet to initialize the files then the CXFServlet isn’t able to find the context while it is initializing.

The only way I was able to get this to work out of the box was to list my config files in both places

<!-- inside the web.xml -->
<!-- don't do this, duplicates bean instances -->

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myconfig.xml</param-value>
</context-param>
	<listener>
	<listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <description>Spring Configuration Files</description>
<param-name>contextConfigLocation</param-name>
<param-value>
            /WEB-INF/myconfig.xml
        </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

The problem is that it will duplicate all your bean instances.

My solution is to just create a spring controller that handles the CXF requests. This was relatively easy to do using CXFServlet and AbstractCXFServlet as examples.

The benefit of doing this is that CXFController we create can be directly initialized with the ApplicationContext that it is created in.

package com.foo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.Bus;
import org.apache.cxf.BusException;
import org.apache.cxf.BusFactory;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.resource.ResourceManager;
import org.apache.cxf.transport.DestinationFactory;
import org.apache.cxf.transport.DestinationFactoryManager;
import org.apache.cxf.transport.servlet.ServletContextResourceResolver;
import org.apache.cxf.transport.servlet.ServletController;
import org.apache.cxf.transport.servlet.ServletTransportFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.util.Enumeration;

public class CXFController implements Controller, ApplicationContextAware
{

    private static final Log log = LogFactory.getLog(CXFController.class);

    protected Bus bus;
    protected ServletTransportFactory servletTransportFactory;
    protected ServletController controller;
    protected WebApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        this.applicationContext = (WebApplicationContext) applicationContext;
    }

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        try {
            BusFactory.setThreadDefaultBus(bus);
            controller.invoke(request, response);
        }
        catch (Exception e) {
            log.error(e.getMessage(),e);
            throw e;
        }
        finally {
            BusFactory.setThreadDefaultBus(null);
        }
        return null;
    }

    public void init()
    {
        bus = new SpringBusFactory(applicationContext).createBus();

        ResourceManager resourceManager = bus.getExtension(ResourceManager.class);
        resourceManager.addResourceResolver(new ServletContextResourceResolver(
                applicationContext.getServletContext()));

        replaceDestinationFactory();

        // Set up the ServletController
        controller = new ServletController(servletTransportFactory,
                SERVLET_CONFIG,
                applicationContext.getServletContext(),
                bus);
    }

    public void destroy() {
        bus.shutdown(true);
    }

    protected void replaceDestinationFactory()
    {

        DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class);
        try
        {
            DestinationFactory df = dfm
                    .getDestinationFactory("http://cxf.apache.org/transports/http/configuration");
            if (df instanceof ServletTransportFactory)
            {
                servletTransportFactory = (ServletTransportFactory) df;
                log.info("DESTIONFACTORY_ALREADY_REGISTERED");
                return;
            }
        }
        catch (BusException e)
        {
            // why are we throwing a busexception if the DF isn't found?
        }

        DestinationFactory factory = createServletTransportFactory();

        for (String s : factory.getTransportIds())
        {
            registerTransport(factory, s);
        }
        log.info("REPLACED_HTTP_DESTIONFACTORY");
    }

    private void registerTransport(DestinationFactory factory, String namespace) {
        bus.getExtension(DestinationFactoryManager.class).registerDestinationFactory(namespace, factory);
    }

    protected DestinationFactory createServletTransportFactory() {
        if (servletTransportFactory == null) {
            servletTransportFactory = new ServletTransportFactory(bus);
        }
        return servletTransportFactory;
    }

    /**
     * Annoying hack...
     *
     * The ServletController class uses the servlet config to get other init parameters. This
     * mostly just prevents ServletController from throwing NullPointerExceptions
     *
     * We don't care about any of them but here is teh list if we decide we do:
     * hide-service-list-page
     * disable-address-updates
     * base-address
     * service-list-stylesheet
     */
    public static ServletConfig SERVLET_CONFIG = new ServletConfig()
    {

        public String getServletName()
        {
            return null;
        }

        public ServletContext getServletContext()
        {
            return null;
        }

        public String getInitParameter(String name)
        {
            return null;
        }

        public Enumeration getInitParameterNames()
        {
            return null;
        }
    };

}

There are three caveats to the examples above:
1. In CXFServlet it uses the ServletConfig to find specific init parameters, this can be done still with a little bit of effort by passing them in through the spring config and then use the SERVLET_CONFIG instance of ServletConfig in the example above to provide the values to the ServletController instance.

2. I don’t need the multiple cxf bus support so I didn’t port it over.

3. I didn’t add reloading support to my controller.

Finally you just need to configure spring to use this new controller:

<bean name="cxfController" class="com.foo.CXFController"
          init-method="init"
          destroy-method="destroy"
          lazy-init="true"/>

    <bean id="beanMappings"
          class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"
          p:order="0" />

    <bean id="urlMappings"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
          p:order="1">
<property name="urlMap">
            <util:map>
                <entry key="/cxf*/**" value-ref="cxfController"/>
            </util:map>
        </property>
    </bean>

It is very important to note that the cxfController is lazy initialized. This allows all services to be loaded before the CXFController does. This could probably also be done by making the CXFController an application listener and waiting until the spring context was fully initialized before initializing, but it was quicker to just make it lazy initialized 🙂

Written by AJ

February 19, 2009 at 4:32 pm

Posted in java

Tagged with , , , ,

Intellij IDEA 8.1 is out!

leave a comment »

http://jetbrains.com

If you have trouble with it working, try removing your installed extra plugins.
(Under ~/Library/Application Support/IntelliJIDEA80 on the mac)

Written by AJ

February 12, 2009 at 3:07 pm

Posted in jive

Tagged with ,