Tuesday 19 November 2013

Java Keytool

I constantly forget how to use the keytool so here are some memory joggers!  The keytool app is part of the the standard Java distribution.

These will be added to over time.

List

List the contents of a jks file

    keytool -list -keystore <keystore.jks> -storepass <password>

Remote Keys

Print a certificate for a remote server


   keytool -printcert -rfc -sslserver my.company.com

Copy the output into a file .pem

Import Key

Import a key to a key store.  In this case it is imported into the java default Certificate Authority file (cacerts).  This will prompt for a password for the cacerts file which is 'changeit' by default.

    keytool -importcert -file ./certificate.pem -keystore $JRE_LIB/lib/security/cacerts

Thursday 14 November 2013

Spring WS Interceptor

Using the spring interceptor methods a SOAP message can be manipulated by adding or removing elements.

Create an interceptor and add it to the spring config
   
    <bean id="myInterceptor" class="com.me.MyInterceptor">
    </bean>
    
    <sws:interceptors>
    <ref bean="myInterceptor" />
    </sws:interceptors>

The interceptor class implements the EndpointInterceptor

    public class MyInterceptor implements EndpointInterceptor

This interface defines four methods,

    // Used to read and / or manipulate the request coming in the endpoint
    boolean handleRequest(MessageContext paramMessageContext, Object paramObject)

    // Used to read and / or manipulate the response coming out of the endpoint
    boolean handleResponse(MessageContext paramMessageContext, Object paramObject)

    // Used to read and / or manipulate any faults that have occurred
    boolean handleFault(MessageContext paramMessageContext, Object paramObject)

    // Called after the interceptor has finished.
    void afterCompletion(MessageContext paramMessageContext, Object paramObject, Exception paramException)

Java Soap Objects

The default java soap objects are from the java.xml.soap package,

    SOAPBody
    SOAPHeader
    SOAPMessage

These objects use the standard org.w3c.dom objects to manipulate the contents.  These objects can be obtained using the following,

    SaajSoapMessage message = (SaajSoapMessage) messageContext.getRequest();
    SOAPMessage soapMessage = message.getSaajMessage();
    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    SOAPBody soapBody = soapMessage.getSOAPBody();

Spring Soap Objects

The spring objects are in the package org.springframework.ws.soap,

    SoapBody
    SoapHeader
    SoapEnvelope
    SoapElement

and have only a few methods.  The Body and Header can be used to get a standard javax.xml.transform.Source or Result object.  These objects can be obtained using,

    SaajSoapMessage message = (SaajSoapMessage) messageContext.getRequest();
    SoapBody soapHeader = message.getSoapHeader();
    SoapBody soapBody = message.getSoapBody();

Reading using the Java Objects

Reading using the java objects is pretty easy. Using the java SOAPBody a node list can be obtained,

    SOAPBody soapBody = soapMessage.getSOAPBody();
    NodeList soapBodyNodeList = soapBody.getChildNodes();
    String soapBodyStr = null;
    for (int i = 0; i < soapBodyNodeList.getLength(); i++)
    {
        String localName = soapBodyNodeList.item(i).getLocalName();
    }

or other standard dom manipulation eg getElementByTagName("myTag").

Reading using the Spring Objects

Using the Spring soap header or body can really simply be read using a Transformer,

    SoapBody springSoapBody = message.getSoapBody();
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    StringWriter stringWriter = new StringWriter();
    transformer.transform(springSoapBody.getPayloadSource(), new StreamResult(stringWriter));

The contents can then be obtained from the stringWriter using the toString().  Alternatively a DOMResult can be used,

    DOMResult result = new DOMResult();
    transformer.transform(springSoapBody.getPayloadSource(), result);

Adding using the Spring Objects

Added an object in easy using the transformer defined above,

    SoapHeader soapHeader = message.getSoapHeader();
    StringSource stringSource = new StringSource("<xmlToAdd>Hello</xmlToAdd>");
    transformer.transform(stringSource , soapHeader.getResult());

The header will now include the xml.  At the point above the xml is just a string so could be generated using JAXB to create complicated additional nested xml tags if necessary.






Friday 27 September 2013

JD Eclipse Decompile

JD Eclipse is a brilliant java decompile which very usefully provides line numbers in the decompiled class file.  Unfortunately it is no longer supported or in the Eclipse MarketPlace. To get it running on eclipse copy the two jars

jd.ide.eclipse.win32.x86_64_0.1.3.jar
jd.ide.eclipse_0.1.3.jar

into the eclipse/plugins directory and restart Eclipse.

Once eclipse has restarted go to,

    Window - Preferences - General - Editors - File Associations

Click on 'Class' and then 'Add'.  There is a new option now available called 'Class File Editor'.  Add this and make it the default.  Do the same to the 'Class without Source'.

Once completed the JD-Eclipse class viewer will be used to open class files.

I'd be interested to know if there is anything else around that decompiles like JD Eclipse?  The ByteCode Visualiser in the MarketPlace is good but I want the actual code not the byte code.



Update
After posting this I have found this site with instructions and updates.

http://jd.benow.ca/

Tuesday 30 July 2013

Soap UI

SoapUI is a brilliant tool for testing web services.  It can be downloaded from http://www.soapui.org/.

Property Transfers

SoapUI allows testing individual calls to a service but also allows multiple requests to be put together to form test cases.  For example, a test case creating and deleting would require the id generated by the first request to be passed to the delete request.  Soap UI's mechanism for doing this is with a Property Transfer.

    Right Click on the Test Steps -> Add Step -> Property Transfer

The transfer is done using XPath by default.  An example of a property transfer is below using the xml

CreateRequest
    <CreateRequest>
        <name>Andy</name>
        <data>123456</data>
    </CreateRequest>

CreateResponse
    <CreateResponse>
        <id>159</id>
        <name>Andy</name>
        <data>123456</data>
    </CreateResponse>

DeleteRequest
    <DeleteResponse>
        <id>159</id>
    </DeleteResponse>

Here the property transfer is between the CreateResponse and the DeleteRequest.  In SoapUI this will look like,

    Source: Create      Property: Response
    declare namespace myns='http://www.me.com/example';
    //myns:CreateResponse/id

    Target: Delete      Property: Request
    declare namespace myns='http://www.me.com/example';
    //myns:DeleteRequest/id

It is possible to include the whole <id>159</id> or to just transfer the value you can check the

    Transfer text content

Transfering a whole block of xml can be really powerful but the 'Transfer text content' does keep things simple and allows the transfer of the 'value' only.



Friday 26 July 2013

SOAP WebService

SOAP is a common type of webservice.  Spring has a lot of support for creating SOAP webservices.  Below is an example configuration.

Maven Dependencies

There are a number of dependencies required for wiring up spring webservices.  The two spring ones here are obvious.  The org.apache.ws.xmlschema allows multiple schemas to be used and spring wraps some of the functionality of this dependency.  You may not need it as a compile dependency but certainly as a runtime.  The wsdl4j dependency allows a dynamic wsdl to be created.


        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws</artifactId>
            <version>${org.springframework.ws.version}</version>
            <scope>compile</scope>
            <classifier>all</classifier>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
            <scope>compile</scope>
        </dependency>
        
        <dependency>
            <groupId>org.apache.ws.xmlschema</groupId>
            <artifactId>xmlschema-core</artifactId>
            <version>2.0.1</version>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
            <version>1.6.3</version>
            <scope>compile</scope>
        </dependency>

server.xml Configuration

The server.xml configuration is very straightforward.  Firstly though a webservice in spring is usually wired with the org.springframework.ws.transport.http.MessageDispatcherServlet rather than the more common org.springframework.web.servlet.DispatcherServlet.  It means that the server.xml in WEB-INF is as follows,

    <display-name>My web service</display-name>

    <!-- This servlet is the actual web service -->
    <servlet>
<servlet-name>my-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
    <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
<servlet-name>my-ws</servlet-name>
<url-pattern>/ws/*</url-pattern>
    </servlet-mapping>


The transformWsdlLocations parameter means that spring will automatically adjust the location of the service, published in the wsdl.

Spring xml configuration

The spring configuration has a number of options.

Standard Spring 
There are a few standard tags for spring ws.  These are below

    <context:component-scan base-package="com.me.web.ws" />
    
    <!-- Enable @Required -->
    <context:annotation-config />
    
    <!-- Enable @Endpoint, @PayloadRoot, etc -->
    <sws:annotation-driven />


Defining the Schemas
The schemas can be defined using a schema collection.  The advantages are that multiple schemas can be used and the spring bean that holds them all can be reused.  The schemaCollection is the reason for the apache pom entry above.  The schemas can be defined using,

    <bean id="schemas" class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
        <property name="xsds">
            <list>
                <value>classpath:/schema_1.xsd</value>
                <value>classpath:/schema_2.xsd</value>
            </list>
        </property>
        <property name="inline" value="true" />
    </bean>


Defining the WSDL
The WSDL can be defined automatically by spring from the schemas.  If you want to create a static wsdl yourself then spring has plenty of support for publishing this too.  However, in most cases it is easier this way,

    <bean id="webservice" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
        <property name="schemaCollection" ref="schemas"/>
        <property name="portTypeName" value="MyWsPortType"/>
        <property name="locationUri" value="/ws/mywebservice"/>
    </bean>

Here the location defines the link to the wsdl.  In this case it would be

  http://<server>:<port>/<context><locationUri><id>.wsdl

  http://<server>:<port>/<context>/ws/mywebservice/webservice.wsdl

Defining the wsdl this way also allows us to reuse the schemaCollection that was defined above.  There is an optional property for 'requestSuffix' and 'responseSuffix'.  These are the suffixes to define the entry points for the webservice.  By default they are 'Request' and 'Response'.  If you have not objects in your schema which end with 'Request' or 'Response' then there will be no obvious entry points for your webservice.

There is a shorthand way of defining the wsdl with springs sws tags. However, the schemaCollection cannot be used for this.

     <sws:dynamic-wsdl  id="possession" portTypeName="PossessionPortType" locationUri="/ws/possession">
         <sws:xsd location="classpath:/schema_1.xsd"/>
         <sws:xsd location="classpath:/schema_2.xsd"/>
     </sws:dynamic-wsdl>
    

Interceptors
An interceptor is something which happens before the request is passed to the webservice or after the webservice has finished with the request.  There are two particular interceptors which are really useful.  The logging interceptor will log all the requests which are made of the service.  The validating interceptor will validate that the request and response payloads are legitimate against the defined schemas.   

    <bean id="validatingInterceptor" class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
        <property name="xsdSchemaCollection" ref="schemas" />
        <property name="validateRequest" value="true"/>
        <property name="validateResponse" value="true"/>
    </bean>

    <!-- Logging interceptor -->
    <bean id="loggingInterceptor" class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor">
        <description>
            This interceptor logs the message payload.
        </description>
    </bean>

    <sws:interceptors>
        <ref bean="validatingInterceptor" />
        <ref bean="loggingInterceptor" />
    </sws:interceptors>

Endpoint

The Endpoint is the class which actually receives the request.  It should be annotated with @Endpoint.  The actual method which is called is defined using the @PayloadRoot annotation.  The localPart is the name of the xml root element in the request.  The namespace is defined in the schema for that element. Note that if a reference to the namespace is used like this then the namespace value isn't quoted!


    public static final String WEBSERVICE_NAMESPACE = "http://www.me.com/my/webservice";

    @PayloadRoot(localPart = "ReadRequest", namespace = WEBSERVICE_NAMESPACE)                 
    @ResponsePayload
    public ReadResponse getPossessions(@RequestPayload final ReadRequest readRequest, final SoapHeader header) 
    {  
        ...
    }

If you don't want to use the @PayloadRoot annotation then an xml configuration is available

    <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
        <property name="mappings">
            <props>
                <prop key="{http://www.me.com/my/webservice}ReadRequest">readEndpoint</prop>
            </props>
        </property>
        <property name="interceptors">
            <bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
        </property>
    </bean>

where 'readEndpoint' is a bean defined in the context.



Wednesday 24 July 2013

JPA Entity Manager

Setting up an EntityManager for JPA can be done in a number of ways.  Below is a simple example to get something going.  It uses spring 3 and the packagesToScan option so that a persistence.xml file is not required.

persistence.xml

The persistence.xml file normally lives in the META-INF directory of src/main/java but if the packagesToScan option is going to be used in the EntityManagerFactory then this file should not be present at all.

DataSource

The DataSource defines the database that is used.  For simple development this can just be included as shown below however, two useful changes can be done.  Firstly, externalise the properties to a property file that can be changed without a recompile.  Secondly the datasource can be obtained by looking up a JNDI resource from the application server.

<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> 
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="awhite" />
<property name="password" value="passw0rd" />
</bean>

Whichever driver is used needs to be on the classpath of the application.  In this case oracle.jdbc.driver.OracleDriver.

EntityManagerFactory

Creating an EntityManagerFactory is shown below.  The 'databasePlatform' will change depending on the database that is being connected to.  The 'hibernate.show_sql' and 'format_sql' are useful for debugging purposes but could be configured in a property file to allow them to be changed later.

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="com.my.packages" />
        <property name="dataSource" ref="myDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
                <property name="generateDdl" value="false" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <!-- General settings -->
                <prop key="hibernate.archive.autodetection">class, hbm</prop>
                <prop key="hibernate.current_session_context_class">jta</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>
 

PersistenceAnnotationPostProcessor

The PersistenceAnnotationPostProcessor is included so that the EntityManager created by the JPA implementation (eg Hibernate) can still be wired into classes with spring even though it isn't spring that creates and manages that class.

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
 
This bean allows the @PersistenceContext annotation to be included in classes and the developer can assume that the EntityManager will be there at runtime. Here is an example of the annotation.

    /** JPA entity manager. */
    @PersistenceContext
    private EntityManager entityManager;










Tuesday 11 June 2013

Spring AOP Error

AOP can be used in spring to weave aspects.  This is commonly used for database transactions using the @Transactional annotation.  However, this means that spring has to make proxy objects for beans which use these annotations.  This can lead to the error,

    Error Cannot convert value of type [$Proxy...] to required type

Basically what is happening is that spring is creating the proxy objects from the corresponding interfaces but in the spring context an actual implementation of the interface is required as a property by a bean.  In this case spring can't guarantee that the proxy implementation will satisfy the beans requirement and this error is thrown.

Solution 1

The first and best solution is to correct the receiving bean to take an interface instead of an implementation.  Most beans should take interfaces so that the implementation can easily be swapped in the spring configuration.  Once the beans are wired purely with interfaces this problem with go away.

Solution 2

Where solution 1 above isn't an option it is possible to tell spring to proxy classes and not interfaces.  This is done with this spring command

    <aop:config proxy-target-class="true"/>

This requires the correct namespace definitions at the top of the spring context xml file such as 

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
          http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

Tuesday 4 June 2013

JMS, Spring & MQ

Here is a sample configuration for using MQ with JMS and Spring.

Firstly the MQ library is needed.  This can be found in a number of places but if you are using eclipse you can install the Websphere Liberty Profile (8.5.next) from the market place.  The required MQ library is available in

    <liberty_install_dir>/lib/com.ibm.ws.messaging.jms.wmq_1.0.jar

Maven Dependencies

The MQ jar can be used as a maven dependency using the System scope using the install directory above.

    <dependency>
        <groupId>com.ibm.ws.messaging.jms</groupId>
        <artifactId>wmq</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath><liberty_install_dir>/lib/com.ibm.ws.messaging.jms.wmq_1.0.jar</systemPath>
    </dependency>

The JMS interfaces are all that is necessary if installing into an application server / container.

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
        <scope>provided</scope>
    </dependency>

Note that this is a provided dependency because the implementation of these interfaces are provided by the container.  If the app is standalone and isn't deployed into a container then concrete implementations of the JMS spec needs to be provided.  One example is the geronimo library,

    <dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-jms_1.1_spec</artifactId>
        <version>1.1.1</version>
        <scope>compile</scope>
    </dependency>

And finally the spring jms jar is also required,

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>3.1.1.RELEASE</version>
        <scope>compile</scope>
    </dependency>

(Note: you'll need to add a spring property place holder for the properties or replace the ${...} values in the following examples)

JMS Connection Factory

The JMS connection factory is dependent on the queue / topic implementation that is being used.  In this case this is IBM MQ,

    <bean id="jmsConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
        <property name="hostName" value="${ip_address}" />
        <property name="port" value="${port_number}" />
        <property name="queueManager" value="${queue_manager_name}" />
        <property name="transportType" value="1" />
    </bean>
    <bean id="jmsDestination" class="com.ibm.mq.jms.MQQueue">
        <constructor-arg value="${queue_name}" />
    </bean>

This will configure a Queue based connection.  To create a topic based connection is just as simple.  Just replace the 'Queue' with 'Topic' in the configuration above.  This gives,

    <bean id="jmsConnectionFactory" class="com.ibm.mq.jms.MQTopicConnectionFactory">
        <property name="hostName" value="${ip_address}" />
        <property name="port" value="${port_number}" />
        <property name="queueManager" value="${queue_manager_name}" />
        <property name="transportType" value="1" />
    </bean>
    <bean id="jmsDestination" class="com.ibm.mq.jms.MQTopic">
        <constructor-arg value="${topic}" />
    </bean>

Spring Connection Factory

The spring connection factory wraps the JMS Connection Factory.  There are a number of connection factories available.  If this is a simple connection with no authentication then just use,

    <bean id="springConnectionFactory"
            class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory" ref="jmsConnectionFactory" />
    </bean>

otherwise if credentials are required use,

    <bean id="springConnectionFactory"
            class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
        <property name="targetConnectionFactory" ref="jmsConnectionFactory" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
    </bean>

Spring JMS Template

The JMS template does a lot of the boilerplate code required to open and close connections.  It is very like JdbcTemplate from that point of view.

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="springConnectionFactory" />
        <property name="defaultDestination" ref="jmsDestination" />
    </bean>

Message Driven Bean

A message driven bean is triggered when a message is received by the JMS system.  Spring maintains this relationship and in its simplest form it is exactly the same as the standard JMS setup,

    <!-- Message driven bean -->
    <bean id="sampleMessageDrivenBean" class="com.me.SampleMessageDrivenBean">
    </bean>

    <!-- and this is the message listener container -->
    <bean id="springJmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="springConnectionFactory" />
        <property name="destination" ref="jmsDestination" />
        <property name="messageListener" ref="sampleMessageDrivenBean" />
    </bean>

In this case the message driven bean just implements the standard MessageListener interface from JMS,

public class SampleMessageDrivenBean implements MessageListener
{
    @Override
    public void onMessage(Message message)
    {
        System.out.println("Message Driven Bean: New Message");
        System.out.println(message.toString());
    }
}

Spring also provides a session message listener which provides the session object in the onMessage() call.

Sending Messages

Creating a class to send a message is very easy too.  Using spring to inject the JmsTemplate and Destination leaves a class to send messages as,


public class MessageSender
{
    
    /**
     * JMSTemplate.
     */
    private JmsTemplate jmsTemplate;
    
    /**
     * JMSTemplate.
     */
    private Destination jmsDestination;

    /**
     * Send a message.
     */
    public void sendMessage()
    {
        jmsTemplate.send(jmsDestination, new MessageCreator()
        {
            @Override
            public Message createMessage(Session session) throws JMSException
            {
                System.out.println("Message Sent");
                final Calendar now = Calendar.getInstance();
                return session.createTextMessage(now.toString());
            }
        });
    }

    /**
     * Sets jmsTemplate to the given value.
     *
     * @param jmsTemplate the jmsTemplate to set
     */
    public void setJmsTemplate(JmsTemplate jmsTemplate)
    {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * Sets jmsDestination to the given value.
     *
     * @param jmsDestination the jmsDestination to set
     */
    public void setJmsDestination(Destination jmsDestination)
    {
        this.jmsDestination = jmsDestination;
    }
}



Thursday 16 May 2013

Motion JPG / MJPG

MJPG is a format which is used by some webcams.  This format is just a series of JPG images as bytes separated by a boundary and some headers.  For example

    --myboundary
    Content-Type: image/jpg
    Content-Length: 1234

    afhaoiughwer< 1234 bytes >
    --myboundary

    Content-Type: image/jpg
    Content-Length: 2345

    poipoijngiuh< 2345 bytes >

The blank line after the headers is also used in http requests to separate headers from content - this is pretty standard. This is pretty simple to parse and get the jpg files from.  Below is a sample java class which does this.  This allows a number of images to be skipped so that not every image has to be processed if that isn't required.  This currently just bins the headers but could easily be extended to return the header properties as well.


/**
 * Class to parse a MJPG stream and generate jpg files
 */
public class MjpgParser
{
    /**
     * The content length header.
     */
    private static final String CONTENT_LENGTH_HEADER = "Content-Length: ";
    
    /**
     * The size of the content length string.  Used to chop of the head name and calculate the integer.
     */
    private static final int CONTENT_LENGTH_HEADER_SIZE = CONTENT_LENGTH_HEADER.length();

    /**
     * The input stream.
     */
    private BufferedInputStream mjpgStream;
    
    /**
     * The number of images to skip.
     */
    private int imagesToSkip;

    /**
     * Constructs a new MjpgParser with the given parameters.
     *
     * @param urlResource The url mjpg resource
     * @throws IOException an exception from opening the url
     */
    public MjpgParser(final String urlResource) throws IOException
    {
        this(urlResource, 0);
    }

    /**
     * Constructs a new MjpgParser with the given parameters.
     *
     * @param urlResource The url mjpg resource
     * @param imagesToSkip The number of images to skip.
     * @throws IOException an exception from opening the url
     */
    public MjpgParser(final String urlResource, final int imagesToSkip) throws IOException
    {
        final URL url = new URL(urlResource);
        initialise(url.openStream(), imagesToSkip);
    }
    
    /**
     * Initialise.
     * 
     * @param inputStream The Input Stream
     * @param imagesToSkipNo The number of images to skip.
     */
    private void initialise(final InputStream inputStream, final int imagesToSkipNo)
    {
        this.mjpgStream = new BufferedInputStream(inputStream);
        this.imagesToSkip = imagesToSkipNo;
    }
    
    /**
     * Get the next jpg as a JavaFX Image.
     *
     * @return an Image object
     */
    public Image nextAsImage() throws IOException
    {
        return new Image(new ByteArrayInputStream(nextWithSkip()));
    }
    
    /**
     * Get the next jpg as an array of bytes.
     *
     * @return the bytes of the next jpg
     */
    public byte[] nextAsBytes() throws IOException
    {
        return nextWithSkip();
    }
    
    /**
     * Close the streams.
     */
    public void close() throws IOException
    {
        mjpgStream.close();
    }
    
    /**
     * This method calls next but takes account of the imagesToSkip value.
     * 
     * @return the jpg file after skipping the correct number
     * @throws IOException Thrown by reading from the stream
     */
    private byte[] nextWithSkip() throws IOException
    {
        for (int i = 0; i < imagesToSkip - 1; i++)
        {
            next();
        }
        return next();
    }
    
    /**
     * Get the next jpg as bytes.  This reads the headers and then reads the jpg from the 
     * stream using the Content-Length value to know when to stop.
     * 
     * @return the next jpg file
     * @throws IOException 
     */
    private byte[] next() throws IOException
    {
        // Find the boundary line
        String lineStr = readHeaderLine();
        while (!lineStr.startsWith("--"))
        {
            lineStr = readHeaderLine();
        }
        
        // Read the headers.
        int contentLength = 0;
        lineStr = readHeaderLine();
        while (!lineStr.isEmpty())
        {
            // If this is the content length then process it.
            if (lineStr.startsWith(CONTENT_LENGTH_HEADER))
            {
                contentLength = parseContentLength(lineStr);
            }

            lineStr = readHeaderLine();
        }
        
        return readJpgBytes(contentLength);
    }
    
    /**
     * Read a line from the input stream. This is a header line so it will be a readable string 
     * and can be trimmed to remove the end of line characters.
     * 
     * @return the line as bytes
     * @throws IOException 
     */
    private String readHeaderLine() throws IOException
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int entry = mjpgStream.read();
        while (entry != '\n')
        {
            baos.write(entry);
            entry = mjpgStream.read();
        }
        return new String(baos.toByteArray()).trim();
    }
    
    /**
     * Parse the content length line.
     *
     * @param contentLengthLine The line to parse
     * @return The content length
     */
    private int parseContentLength(final String contentLengthLine)
    {
        return Integer.parseInt(contentLengthLine.substring(CONTENT_LENGTH_HEADER_SIZE));
    }
    
    /**
     * Read the jpg.
     * 
     * @param contentLength the length of the jpg
     * @return the jpg as an {@link Image}
     * @throws IOException 
     */
    private byte[] readJpgBytes(final int contentLength) throws IOException
    {
        final byte [] jpgBytes = new byte[contentLength];
        for (int i = 0; i < contentLength; i++)
        {
            jpgBytes[i] = (byte) mjpgStream.read();
        }
        return jpgBytes;
    }
}






Maven Sources Plugin

This useful plugin will generate and install a jar of the sources of the project.  Most of the time a really simple configuration works.  However, there is one thing worth noting.  If this is used with the wrong goal the sources will be regenerated.  If this is used in conjunction with the Maven Replacer Plugin then the replacer will not run as the goal for this is usually prepare-package.

So, the configuration which will not frig with the sources is


    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <executions>
            <execution>
                <id>attach-sources</id>
                <phase>verify</phase>
                <goals>
                    <goal>jar-no-fork</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

The jar-no-fork will force this plugin to use the sources which already exist.  If this is only jar then the sources will be regenerated.