com.adobe.granite.workflow.metadata.SimpleMetaDataMap Maven / Gradle / Ivy
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* __________________
*
* Copyright 2012 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
package com.adobe.granite.workflow.metadata;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* A simple value map implementation, with limited conversion capabilities
*/
public class SimpleMetaDataMap extends HashMap implements MetaDataMap {
private static final long serialVersionUID = 1360764073724170383L;
/**
* Supports automatic meta data conversion based on the given type.
*
* @see com.adobe.granite.workflow.metadata.MetaDataMap#get(java.lang.String,
* java.lang.Class)
*/
public T get(String name, Class type) {
return convert(get(name), type);
}
/**
* Supports automatic meta data conversion, based on the type of the default
* value.
*
* @see com.adobe.granite.workflow.metadata.MetaDataMap#get(java.lang.String,
* java.lang.Object)
*/
@SuppressWarnings("unchecked")
public T get(String name, T defaultValue) {
if (defaultValue == null) {
return (T) get(name);
}
T value = get(name, (Class) defaultValue.getClass());
return value == null ? defaultValue : value;
}
@SuppressWarnings("unchecked")
private T convert(Object obj, Class type) {
try {
if (obj == null) {
return null;
} else if (type.isAssignableFrom(obj.getClass())) {
return (T) obj;
} else if (type.isArray()) {
return (T) convertToArray(obj, type.getComponentType());
} else if (type == String.class) {
return (T) String.valueOf(obj);
} else if (type == Integer.class) {
return (T) (Integer) Integer.parseInt(obj.toString());
} else if (type == Long.class) {
return (T) (Long) Long.parseLong(obj.toString());
} else if (type == Double.class) {
return (T) (Double) Double.parseDouble(obj.toString());
} else if (type == Boolean.class) {
return (T) (Boolean) Boolean.parseBoolean(obj.toString());
} else {
return null;
}
} catch (NumberFormatException e) {
return null;
}
}
private T[] convertToArray(Object obj, Class type) {
List values = new LinkedList();
if (obj.getClass().isArray()) {
for (Object o : (Object[]) obj) {
values.add(convert(o, type));
}
} else {
values.add(convert(obj, type));
}
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, values.size());
return values.toArray(result);
}
}