Thursday, February 17, 2011

JUnit & Spring – What You Don’t Know

 Gordon Dickens, Chariot architect and one of our education trainers, recently wrote this blog post on JUnit and Spring.


When using JUnit in Spring there are several features added that many developers are not aware of.
First, if you are including the Spring Context in your tests, it becomes an Integration Test, no longer a Unit Test.

1. Default Searching of Context File(s)

To instruct Spring to load beans for the tests in the class, we annotate the class with @ContextConfiguration

1a. No File Specified

@ContextConfiguration – with no parameters, (by Default) looks for the config file as the same name as the class with the suffix “-context.xml“. For example,
Using
?
1
2
3
4
5
6
7
package com.gordondickens.sample;
@ContextConfiguration
public class UtilsTest {
  ...
}
...
Is equivalent to
?
1
2
3
  ...
@ContextConfiguration("classpath:/com/gordondickens/sample/UtilsTest-context.xml")
  ...


 Read more...

Thursday, February 10, 2011

What's Coming in Spring 3.1

Spring 3.1.0 M1 is expected to be released on Feb 10, 2011. There are many exciting new features expected for the final release which is scheduled for June 2011.

Environment Profiles

Many times we want separate configuration for different environments such as development, qa, production. Also, we may want to provide different bean configuration for traditional or cloud environments as well.
  • Beans can be configured in XML with the additional "profile" attribute
  • Activate 1..n profiles in code or with java arg -Dspring.profiles.active="dev,qa"
  • ParamName for DispatcherServlet "spring.profiles.active"
  • Integration Tests Class GenericXmlApplicationContext
  • Nested "beans" in other words, <beans/> tag can have other <beans/> tags within allowing multiple bean sets for different profiles in the same config file
  • The variable “environment” is already registered for SpEL

@Profile(“development”)
public class MyClass() { ... }

<beans profile=“development” … />

#{environment[‘prop.key’]}
public String myProp;


The "c" Namespace

Much like the existing "p" namespace, the "c" namespace supports constructor arguments. This has the additional benefit of allowing us to reference the constructor arguments by name.

<bean class=“…” c:age=“35” c:amount=“50000”/>

Cache Abstractions

  • Cache Abstractions will be available – not just EHCache, also for Gemfire, Coherence
  • Package: org.springframework.cache
  • Annotation Package: org.springframework.cache.annotation
  • <cache: &/gt; namespace

<cache:annotation-driven> //referencing "cacheManager"

@Cacheable //field or method

@Cacheable(condition=“name.length < 10”) //conditional

@CacheEvict // remove field from cache
public void clearMyField() { ... }

Servlet 3.0

  • ServletContainerInitializer – XML Free config (no web.xml)
  • package org.springframework.web.context.support.AnnotationConfigWebApplicationContext
  • Async request processing
  • Standard file upload support

HTTP Session Improvements

  • Share information across multiple browser instances
  • Uses Shared Cookie
  • package org.springframework.web.bind.support.SessionAttributeStore
  • Conversation "scope"
  • Useful for MVC & JSF, Web Flow

Groovy Support

  • Groovy/Grails BeanBuilder inclusion
  • <lang:groovy>
  • Groovy based template files (alternative to Velocity and Freemarker)

Feature Configuration

For Bean @Configuration - To support applications with Java based configuration.
  • package org.springframework.context.annotation
  • Picked up via AnnotationConfigApplicationContext // Standalone application context, accepting annotated classes as input
  • Allows scanning for @Configuration classes
  • @FeatureConfiguration // class level - specify the name of the Spring bean definition
  • @Feature // Method w/i @FeatureConfiguration Class

Customizable @MVC

  • Custom @ExceptionHandler support for @Controller methods
  • Custom @ExceptionHandler support for @RequestBody & @ResponseBody
  • You can write a BeanPostProcessor to change AnnotationMethodHandlerAdapter after construction
  • Auto-detection of custom HttpMessageConverters - for example custom MyMappingJacksonHttpMessageConverter
  • Support for custom message codes resolver with <mvc:annotation-driven/>

<mvc:annotation-driven>
<mvc:custom-web-argument-resolvers>
<bean class="org.example.MyWebArgumentResolver"/>
</mvc:custom-web-argument-resolvers>
</mvc:annotation-driven>

<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>

<mvc:annotation-driven message-codes-resolver="org.example.MyMessageCodesResolver"/>

REST Enhancements

  • Interceptors for RestTemplate
  • ClientHttpRequestInterceptor
  • bufferRequestBody property to the SimpleClientHttpRequestFactory to handle large payloads with RestTemplate
  • New WebRequest.checkNotModified(String) // only had long support previously
  • New @ResponseEntity
  • To support OAuth with ClientHttpRequestInterceptors

Summary

Many of the items included here are specific features for 3.1.0.M1, there are many more improvements coming for MVC customization and REST improvements in M2.

Monday, February 7, 2011

Sending Beans as XML with JmsTemplate

Introduction

We often want to send XML via web services. We may already have the schema or annotated JAXB2 classes configured in our application. What if we want to send the same format via JMS? By default Spring JMS is configured to send & receive objects serialized. How can we switch to using JAXB2 (or any other OXM marshaling strategy)? The following example assumes we are going from annotations first instead of from XML Schema.

Quick Overview

  1. Annotate Bean with JAXB2
  2. Configure OXM Converter
  3. Integration Test
  4. Visualize Results
  5. Logging Configuration
  6. Maven Configuration

1. Annotate Bean with JAXB2

  • Use JAXB2 annotations for our bean
package com.gordondickens.jmswithoxm;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "account")
@XmlAccessorType(XmlAccessType.FIELD)
public class Account {
  @XmlElement(required = true)
  private String name;

  @XmlElement
  private String description;

  @XmlElement
  private BigDecimal balance;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public BigDecimal getBalance() {
    return balance;
  }

  public void setBalance(BigDecimal balance) {
    this.balance = balance;
  }

  @Override
  public String toString() {
    return "Account [name=" + name + ", description=" + description
        + ", balance=" + balance + "]";
  }

}

2. Configure OXM Converter

  • Define our Marshalers - We see <oxm:jaxb2-marshaller ...> defines JAXB2 as our marshaller for the Account class
  • Register our MarshallingMessageConverter - We register the MarshallingMessageConverter to use the JAXB2 marshaller for both inbound and outbound data
  • Register our Converter - In the JmsTemplate, we register our oxmMessageConverter as the messageConverter. This replaces the default SimpleMessageConverter which will relies on Serialization
  • Notice the ActiveMQ namespace?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<amq:broker persistent="false" useJmx="true">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:61616" />
</amq:transportConnectors>
</amq:broker>

<amq:connectionFactory brokerURL="vm://localhost" id="jmsFactory" />

<!-- Spring JMS Template -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsFactory" />
<property name="defaultDestination" ref="oxmTestQueue" />
<property name="messageConverter" ref="oxmMessageConverter" />
</bean>

<amq:queue id="oxmTestQueue" physicalName="oxm.test.queue" />

<bean id="oxmMessageConverter"
class="org.springframework.jms.support.converter.MarshallingMessageConverter">
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="marshaller" />
</bean>

<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="com.gordondickens.jmswithoxm.Account" />
</oxm:jaxb2-marshaller>
</beans>

3. Integration Test

  • Populate the Account bean
  • Calls convertAndSend on the JmsTemplate to marshal & send the Account
  • Includes a postProcessor callback to log the XML data
  • Calls receiveAndConvert on the JmsTemplate to get & unmarshal the Account
  • Asserts end state
package com.gordondickens.jmswithoxm;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.math.BigDecimal;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class JmsWithOxmTest {
  private static final Logger logger = LoggerFactory
    .getLogger(JmsWithOxmTest.class);
  private static final String TEST_DEST = "oxmTestQueue";

  @Autowired
  JmsTemplate jmsTemplate;

  @Test
  public void testSendingMessage() {
    Account account = generateTestMessage();
    jmsTemplate.convertAndSend(TEST_DEST, account,
      new MessagePostProcessor() {
      @Override
      public Message postProcessMessage(Message message)
        throws JMSException {
        if (message instanceof BytesMessage) {
          BytesMessage messageBody = (BytesMessage) message;
          messageBody.reset();

          Long length = messageBody.getBodyLength();
          logger.debug("***** MESSAGE LENGTH is {} bytes",
            length);
          byte[] byteMyMessage = new byte[length.intValue()];
          int red = messageBody.readBytes(byteMyMessage);
          logger.debug(
            "***** SENDING MESSAGE - \n" +
            "<!-- MSG START -->\n{}\n<!-- MSG END -->",
            new String(byteMyMessage));
        }
        return message;
      }
    });
    Account account2 = (Account) jmsTemplate.receiveAndConvert(TEST_DEST);
    assertNotNull("Account MUST return from JMS", account2);
    assertEquals("Name MUST match", account.getName(), account2.getName());
    assertEquals("Description MUST match", account.getDescription(),
      account2.getDescription());
    assertEquals("Balance MUST match", account.getBalance(),
      account2.getBalance());
  }

  private Account generateTestMessage() {
    Account account = new Account();
    account.setBalance(new BigDecimal(12345.67));
    account.setDescription("A no account varmint");
    account.setName("Waskally Wabbit - Gordon Test June 2011");
    logger.debug("Generated Test Message: " + account.toString());
    return account;
  }
}

4. Visualizing Results

  • Run: mvn clean test
  • See Account XML between the block <!-- MSG START --> & <!--MSG END -->
  • Output has been Formatted for clarity
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.gordondickens.jmswithoxm.JmsWithOxmTest

INFO  o.s.o.j.Jaxb2Marshaller - Creating JAXBContext 
with classes to be bound [class com.gordondickens.jmswithoxm.Account]

DEBUG c.g.j.JmsWithOxmTest - Generated Test Message: 
Account [name=Waskally Wabbit, description=A no account 
varmint, balance=12345.670000000000072759576141834259033203125]

DEBUG o.s.j.c.JmsTemplate - Executing callback on JMS Session: 
ActiveMQSession {id=ID:Technophiliac-61135-1296856347600-2:1:1,started=false}

DEBUG c.g.j.JmsWithOxmTest - ***** MESSAGE LENGTH is 213 bytes

DEBUG c.g.j.JmsWithOxmTest - ***** SENDING MESSAGE -
<!-- MSG START -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<account>
<name>Waskally Wabbit</name>
<description>A no account varmint</description>
<balance>12345.670000000000072759576141834259033203125</balance>
</account>
<!-- MSG END -->

DEBUG o.s.j.c.JmsTemplate - Sending created message:
ActiveMQBytesMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@b364dcb, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = true, droppable = false} ActiveMQBytesMessage{ bytesOut = null, dataOut = null, dataIn = java.io.DataInputStream@1a2d502d }

DEBUG o.s.j.c.JmsTemplate - Executing callback on JMS Session:
ActiveMQSession {id=ID:Technophiliac-61135-1296856347600-2:2:1,started=true}

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.276 sec

5. Logging Configuration

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scan="true" scanPeriod="30 seconds">
  <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
    <resetJUL>true</resetJUL>
  </contextListener>

  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%-5level|%logger{0}|%msg%n</pattern>
    </encoder>
  </appender>

  <logger name="com.gordondickens" level="debug"/>
  <logger name="org.springframework.jms" level="debug"/>
  <logger name="org.springframework.oxm" level="debug"/>

  <root level="warn">
    <appender-ref ref="console"/>
  </root>
</configuration>

6. Maven Configuration

  • Using Logback to support Log4J, SLF4J, Apache (JCL) & Java Util Logging
  • Included IDE builders for STS/Eclipse & IntelliJ IDEA
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gordondickens.jmswithoxm</groupId>
  <artifactId>spring-jms-oxm</artifactId>
  <version>1.1.0</version>
  <packaging>jar</packaging>
  <name>JMS to OXM Spring</name>
  <url>http://gordondickens.com</url>
  <description>Sample JMS with OXM Message Conversion</description>
  <developers>
    <developer>
      <id>gordon.dickens</id>
      <name>Gordon Dickens</name>
      <email>gordondickens@gmail.com</email>
      <roles>
        <role>Author</role>
      </roles>
      <organization>http://www.gordondickens.com</organization>
    </developer>
  </developers>

  <properties>
    <spring.version>3.1.0.RELEASE</spring.version>
    <java.version>1.6</java.version>
    <junit.version>4.10</junit.version>
    <jms.version>1.1.1</jms.version>
    <slf4j.version>1.6.4</slf4j.version>
    <activemq.version>5.5.1</activemq.version>
    <logback.version>1.0.0</logback.version>
    <xbean.version>3.9</xbean.version>
    <jaxb.version>2.2.4</jaxb.version>
    <commons.lang.version>3.1</commons.lang.version>
    <commons.net.version>3.0.1</commons.net.version>
    <maven.clean.plugin>2.4.1</maven.clean.plugin>
    <maven.compiler.plugin>2.3.2</maven.compiler.plugin>
    <maven.dependency.plugin>2.4</maven.dependency.plugin>
    <maven.eclipse.plugin>2.8</maven.eclipse.plugin>
    <maven.idea.plugin>2.2</maven.idea.plugin>
    <maven.resources.plugin>2.5</maven.resources.plugin>
    <maven.source.plugin>2.1.2</maven.source.plugin>
    <maven.surefire.plugin>2.11</maven.surefire.plugin>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.test.failure.ignore>false</maven.test.failure.ignore>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-jms_1.1_spec</artifactId>
      <version>${jms.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.xbean</groupId>
      <artifactId>xbean-spring</artifactId>
    </dependency>
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>${logback.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>${commons.lang.version}</version>
      </dependency>
      <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>${commons.net.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-core</artifactId>
        <version>${activemq.version}</version>
        <exclusions>
          <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
          </exclusion>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging-api</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>${spring.version}</version>
        <exclusions>
          <exclusion>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>${jaxb.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.xbean</groupId>
        <artifactId>xbean-spring</artifactId>
        <version>${xbean.version}</version>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin}</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>${maven.eclipse.plugin}</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <wtpversion>2.0</wtpversion>
          <additionalBuildcommands>
            <buildCommand>
              <name>org.springframework.ide.eclipse.core.springbuilder</name>
              <name>org.maven.ide.eclipse.maven2Builder</name>
            </buildCommand>
          </additionalBuildcommands>
          <additionalProjectnatures>
            <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
            <projectnature>org.maven.ide.eclipse.maven2Nature</projectnature>
          </additionalProjectnatures>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin}</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>${maven.source.plugin}</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-clean-plugin</artifactId>
        <version>${maven.clean.plugin}</version>
        <configuration>
          <filesets>
            <fileset>
              <directory>${project.basedir}</directory>
              <includes>
                <include>activemq-data</include>
                <include>amqstore</include>
                <include>surefire*</include>
              </includes>
              <followSymlinks>false</followSymlinks>
            </fileset>
          </filesets>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-idea-plugin</artifactId>
        <version>${maven.idea.plugin}</version>
        <configuration>
          <downloadSources>true</downloadSources>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>${maven.resources.plugin}</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>${maven.dependency.plugin}</version>
        <dependencies>
          <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
          </dependency>
        </dependencies>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>fast</id>
      <properties>
        <maven.test.skip>true</maven.test.skip>
      </properties>
    </profile>
  </profiles>
</project>

6. Getting the code


Conclusion

Using Spring, it is very easy to configure projects to send/receive data from XML formatted beans. This simplification allows us to focus on the message payload using Spring JMS. If our solution was to serialize the data, the default JMS message conversion would suffice. This implementation focussed on annotated JAXB2 beans without an XML schema. Many projects have existing XML schema, and with Spring JMS this is not difficult to configure. The example above focussed on JAXB2 as our marshaling strategy, we could have easily chosen other strategies such as JiBX, XMLBeans, XStream, Castor with relative ease.

Further Reading

Friday, February 4, 2011

Philly ETE 2011 mobile line up!


 This post is via Kevin Griffin, Chariot Architect and committee chair of the Mobile tract for ETE:

 Philly ETE 2011 mobile line up!

Just thought I would post an update on the current lineup for Philly ETE.
I've been involved in helping get the mobile track lineup sorted out and so far we have confirmed the following:
  • Josh Clark - my favorite 'Tapworthy' author.
  • Johnathon Stark - He literally wrote the books on making mobile apps with HTML, CSS and JavaScript.
  • Ted Neward - If you are lazy, and want to write Android apps, he has the talk for you!
  • Jay McGavren - If you want to write Android apps, in Ruby (Oh yeah!) This is the talk for you (personally, I can't wait for this one!).
  • Terry Ryan - Philly Evangelist from Adobe who will use Air, to build Playbook apps. Magic!
  • David Kaneda - Although technically on the Frameworks track. Go build your mobile apps in Sencha Touch, seriously go now! That way you can thank him at ETE!
With one super secret invite still pending :D

Tuesday, February 1, 2011

Web Application Security

The recent news that the popular dating site Plenty Of Fish was hacked and that passwords and other user information was stolen truly disheartened me.

It was just the latest in a seemingly endless list of such hacks over the years, recently including Gawker Media (Lifehacker, Gizmodo), McDonald's, Walgreen's and Pizza Hut.

Apparently, Little Bobby Tables is alive and well.

What is disheartening to me is not so much the security breaches themselves. No site is completely secure. The operators of these and other sites may have been able to do more than they did to prevent the breaches, or maybe they had really good (but not good enough) security. But security breaches will happen. I think that every site has to assume that it is possible that their site will be hacked and their database stolen.

I'm not suggesting that they just accept the inevitable, and give up. I'm suggesting that everyone that builds a website that collects information from their users (that's every site that has user accounts) should care enough to do their best to ensure that when the site is compromised, the damage is as minimal as possible. That's why the Plenty Of Fish hack was so disturbing. Passwords were apparently stored in the database in clear-text. Once the database was stolen, passwords were readily available, with no further work on the hacker's part.

I had thought that clear-text passwords were such a well-known evil that no-one was doing it any more, but apparently I was mistaken. Web developers who don't know any better apparently still store plain-text passwords so that they can implement the even less-secure feature of emailing it to you if you forget it (or even sometimes even if you don't).

So, what's the right thing to do? Obviously, the most important prerequisites are being aware of the problem, and caring enough about your users to do something about it. If you've read this far, I'll assume that you have those two covered.

The next thing is to not store passwords. Let me repeat that - do not store your user's passwords. By that, I do not mean that you should encrypt the passwords before you store them, though that would be a huge improvement over plaintext. The problem with storing encrypted passwords is twofold. The first, as previously mentioned, is that it may tempt you to decrypt it for some reason (like sending it to the user in an email). The second problem is that unless you are really careful with your encryption, the data thief may very well have the resources to decrypt the passwords.

Instead of storing a user's password, store a cryptographic hash of their password. A cryptographic hash is also known as a one-way hash, and cannot be "decrypted". For authentication, take the user-entered password, run it through the same hash function, and then compare the result to the hash stored in the database. Provide users with the means to securely re-set their password (choose a new one) in the event that they forget it, rather than attempting to send them the old one.

There are still some issues to be aware of when using cryptographic hashes. If there are collisions (two different passwords hash to the same value), and the thief possesses one of the clear-text passwords by some other means, then they can substitute the known password for the one in the other account. Of course, there's always the possibility that two or more users will pick the same password. For example, in the Gawker Media case, the password data was published on the web, and it was revealed that thousands of users had chosen the same few passwords, with '123456' and 'password' leading the list. If you use a simple hash function, then it seems likely that you will have lots of collisions. This makes several attack vectors, like a dictionary attack, or other brute-force attack much more likely to be successful.

The answer to collisions is random salt. By appending random bits to the password before hashing it, you can make the hashes much more likely to be unique. A common method is to generate a new, random salt value for each user, and to store the salt in an additional column in the password table. Making the salt available to a hacker does not make the hashes more susceptible to a brute-force attack if no two of the salt values are the same. One thing to be careful of is using the username for salt - unless you intend to never let a user change their username.

All hash functions are not created equal. As time goes on, and more and more computing power becomes available at relatively low cost, once-unbreakable hash functions become breakable. For instance, SHA-1, apparently still the most widely used cryptographic hash function, was broken in 2005, and the National Institute of Standards and Technology has recommended that federal agencies stop using it. SHA-2, the recommended replacement for SHA-1, while not yet broken, has already been recognized by NIST as potentially insecure, and there is already an effort under way to develop SHA-3.

One-way, randomly-salted SHA-2 (or eventually SHA-3) hashes should solve your password security issues, but what about other user data? What about email addresses, credit card numbers, and the like? I'd like to suggest that the first line of defense is collecting as little sensitive information as possible. Storing credit card information (where legal) is generally unnecessary and provides the potential attacker with substantial incentive. In short, unless you are a credit card company, you probably shouldn't store credit card information.

Other user information should be treated just as carefully - stored only if absolutely necessary, and stored with encryption as secure as possible if it must be stored. Assume from the start that your database will be compromised, and make it as difficult as possible for the data to be used.

There are many other security issues to be concerned about, and I encourage you to research them, but if you care about your users and your reputation, then the least you can do is stop storing sensitive user information in the clear.

Executing JavaScript from Objective-C in an iOS App

New blog post from Steve Smith, one of the Chariot architects working in our mobile practice.  Steve is currently working on updating the mobile app for our Emerging Technologies conference and will be posting articles from time to time as he finds challenges or discoveries.

Here is an excerpt:

The other day, I found the need to execute some JavaScript from a native iOS application.  After doing a little research, I discovered that the UIWebView has a stringByEvaluatingJavaScriptFromString method.  So I decided to create a quick little proof-of-concept to see how to invoke some JavaScript using this. I am not going to walk through all the details of creating a project, etc. and will cut right to the important aspects of making the JavaScript call from the objective-c code.
We are going to need a JavaScript function to call and a UIWebView to evaluate the JavaScript. It would be nice if the JavaScript function took a parameter as well, so we could also prove out the passing of values.  Here is the JavaScript function that I will use:
1var area = function(diameter) {
2     var radius = diameter/2,
3     area = Math.PI * radius * radius;
4     return Math.round(area*100)/100;
5};


Read more