Posts Tagged ‘java’
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: java, jaxb, xml
Posted in Examples | 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: java
Posted in Development, How to's, 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: java, junit, testing
Posted in Development, How to's | No Comments »
Unit Testing Validation in Annotation Based Validating Spring Beans
Friday, April 22nd, 2011
Motivation
I added validation, via annotations, to a Spring “Model” bean. I needed someway to Unit Test this validation, without running the container and without initialising the Spring context.
The bean (simplified)
package foo.bar;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public final class ProductModel {
@NotNull
@Size(max=100)
@Pattern(regexp="[^\n^\t^\r]+", message="Long Name must not contain New Lines, Carriage Returns or Tabs")
private String longName;
@Size(max=20)
private String shortName;
// rest snipped for brevity
}
The Unit Test
package foo.bar;
import java.util.Set;
import javax.validation.ConstraintViolation;
import junit.framework.Assert;
import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
public class Temp {
private LocalValidatorFactoryBean localValidatorFactory;
@Before
public void setup() {
localValidatorFactory = new LocalValidatorFactoryBean();
localValidatorFactory.setProviderClass(HibernateValidator.class);
localValidatorFactory.afterPropertiesSet();
}
@Test
public void testLongNameWithInvalidCharCausesValidationError() {
final ProductModel productModel = new ProductModel();
productModel.setLongName("A long name with\t a Tab character");
Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel);
Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1);
}
}
More
It actually took me a few hours to work the above test out (simple as it is). If I hadn’t stumbled upon these Spring Unit Tests, I might never have got it.
Tags: annotations, java, junit, spring, testing
Posted in Spring | No Comments »
Spring MVC URI Template Example
Monday, April 18th, 2011
Background
So, I’m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration. As I was trawling through the source code I noticed “some wierd” syntax: “/{xxxx}” (which of course I had to look up!).
Most of the following is based upon the excellent Spring Documentation. I’ve lifted and rewritten the parts I require to serve as a condensed “aide-mémoire”.
Description
A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI.
(more...)
Tags: annotations, java, spring
Posted in Spring | No Comments »
