Java to XML, XML to Java (Marshalling and Unmarshalling)

Wednesday, July 13th, 2011

Introduction

JDK6 and JAXB2.x (which comes with JDK6) make marshalling Java to XML and unmarshalling XML to Java a snap, almost trivial.

Example

Java to XML

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class JavaToXML {
	public static void main(String[] args) throws Exception {
		JAXBContext context = JAXBContext.newInstance(Product.class);

		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		Product object = new Product();
		object.setCode("WI1");
		object.setName("Widget Number One");
		object.setPrice(BigDecimal.valueOf(300.00));

		m.marshal(object, System.out);
	}
}

XML to Java

package foo.bar;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XMLToJava {

	public static void main(String[] args) {
		try {
			JAXBContext jc = JAXBContext.newInstance(Product.class);
			Unmarshaller u = jc.createUnmarshaller();

			File f = new File("product.xml");
			Product product = (Product) u.unmarshal(f);

			System.out.println(product.getCode());
			System.out.println(product.getName());
			System.out.println(product.getPrice());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}

product.java

Note: the @XmlRootElement is vital here!

package foo.bar;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
	private String code;
	private String name;
	private BigDecimal price;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
}

product.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product>
    <code>WI1</code>
    <name>Widget Number One</name>
    <price>300.0</price>
</product>

Tags: , ,
Posted in Examples | 7 Comments »

The Processing Instruction Target Matching “[xX][mM][lL]” is Not Allowed

Friday, June 24th, 2011

Background

When parsing XML you receive the following error:

...The Processing Instruction Target Matching "[xX][mM][lL]" is Not Allowed...

Solution

The chances are you have some sort of whitespace (or control character) infront of your XML declaration:

..<?xml version="1.0" encoding="utf-8"?>

It may even be that you have more than one XML declaration in the document..!

Tags:
Posted in quick tips | No Comments »

Read a File as String with Java

Thursday, June 16th, 2011

Introduction

I’m always Googling for a way to do this. This seems to be the best “idiomatic” solution I’ve found. So without further ado…

Example

public String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try{
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
    }
    finally {
        stream.close();
    }
}

Tags:
Posted in Development, How to's, quick tips | No Comments »

View Source of Oracle Trigger

Wednesday, May 11th, 2011

select trigger_body from user_triggers where trigger_name = 'XXXXX'

Tags: ,
Posted in quick tips | No Comments »

Unit Test Private Java Methods using Reflection

Thursday, May 5th, 2011

Introduction

I realise that the thought of Unit Testing private methods in Java classes can be like a red rag to a bull for some people and I understand the arguments.

Therefore, I present the following as a “how to”, not a moral argument for or against!

Example

The class under test

public class Product() {
    private String privateMethod(String id) {
    //Do something private
    return "product_" + id;
  }
}

The (Reflection Based) Unit Test

import java.lang.reflect.Method;

import static org.junit.Assert.*;
import org.junit.Test;

public class ProductTest {
    private Product product; // the class under test
    private Method m;
    private static String METHOD_NAME = "privateMethod";
    private Class[] parameterTypes;
    private Object[] parameters;

    @Before
    public void setUp() throws Exception {
        product = new Product();
        parameterTypes = new Class[1];
        parameterTypes[0] = java.lang.String.class;
        m = product.getClass().getDeclaredMethod(METHOD_NAME, parameterTypes);
        m.setAccessible(true);
        parameters = new Object[1];
    }

    @Test
    public void testPrivateMethod() throws Exception {
        parameters[0] = "someIdentifier";
        String result = (String) m.invoke(product, parameters); 
  
        //Do your assertions
        assertNotNull(result);
    }
}

Update

I’ve since been told that if dp4j.jar is in the classpath at compile-time, it will inject the necessary reflection to make this work. I haven’t had time to try this yet so YMMV.

Tags: , ,
Posted in Development, How to's | No Comments »