This code checks value's type and cast it into appropriate type, then puts it into a javax.jcr.Node
.
The checking looks long and boring. Is there a way to refactor it? I'm using Java 7.
/**
* Set node's property.
*/
public static void setProperty(Node node, String propertyName, Object propertyValue) throws RepositoryException {
if (node == null) {
throw new IllegalArgumentException("Something wrong");
}
if (propertyName == null) {
throw new IllegalArgumentException("Property name is invalid");
}
if (propertyValue == null) {
node.setProperty(propertyName, (Value) null);
} else if (propertyValue instanceof Value) {
node.setProperty(propertyName, (Value) propertyValue);
} else if (propertyValue instanceof Node) {
node.setProperty(propertyName, (Node) propertyValue);
} else if (propertyValue instanceof Binary) {
node.setProperty(propertyName, (Binary) propertyValue);
} else if (propertyValue instanceof Calendar) {
node.setProperty(propertyName, (Calendar) propertyValue);
} else if (propertyValue instanceof Date) {
Calendar cal = Calendar.getInstance();
cal.setTime((Date) propertyValue);
node.setProperty(propertyName, cal);
} else if (propertyValue instanceof BigDecimal) {
node.setProperty(propertyName, (BigDecimal) propertyValue);
} else if (propertyValue instanceof String) {
node.setProperty(propertyName, (String) propertyValue);
} else if (propertyValue instanceof Long) {
node.setProperty(propertyName, ((Long) propertyValue).longValue());
} else if (propertyValue instanceof Double) {
node.setProperty(propertyName, (Double) propertyValue);
} else if (propertyValue instanceof Boolean) {
node.setProperty(propertyName, (Boolean) propertyValue);
} else if (propertyValue instanceof InputStream) {
node.setProperty(propertyName, inputStreamToBinary((InputStream) propertyValue));
} else if (propertyValue instanceof Collection) {
CollectionFactory factory = CollectionFactoryImpl.getInstance();
ArrayList<Value> values = new ArrayList<Value>();
for (Object value : (Collection<Object>) propertyValue) {
values.add(createValue(value, factory));
}
node.setProperty(propertyName, values.toArray(new Value[values.size()]));
} else {
throw new IllegalArgumentException("Something wrong");
}
}
@Test
public void test() {
Node node = createNode("test");
setProperty(node, "name", "name");
}