GHads mind

developers thoughts & finds

Posts Tagged ‘serialize

MongoDB and Java enums

leave a comment »

Well, there is no way in MongoDB/BSON to de-/serialize Java enums. At least I found none but to implement the Interface DBObject. Having no default implementation I started experimenting with implementing the Interface directly at the enum which would be a massive overhead when using multiple enums. So I decided to create a simple Wrapper like DBRef which does the work for you:

/**
 *
 * Use for put into document: document.put(key, DBEmum.of(SomeEnum.VALUE));
 * Use for get from document: DBEnum.to(SomeEnum.class, document.get(key));
 *
 */
public class DBEnum<T extends Enum<T>>
		implements DBObject
{

	private static final String KEY = "_enum";

	public static <U extends Enum<U>> DBEnum<U> of(U value)
	{
		return new DBEnum<U>(value);
	}

	public static <U extends Enum<U>> U to(Class<U> c, Object o)
	{
		if (o instanceof DBObject)
		{
			Object value = ((DBObject) o).get(KEY);
			if (value == null)
			{
				return null;
			}
			return Enum.valueOf(c, value.toString());
		}
		return null;
	}

	private final T value;

	private DBEnum(T value)
	{
		this.value = value;
	}

	public void markAsPartialObject() { }

	public boolean isPartialObject() { return false; }

	public Object put(String s, Object o) { return null; }

	public void putAll(BSONObject bsonObject) { }

	public void putAll(Map map) { }

	public Object get(String s)
	{
		return value.name();
	}

	public Map toMap()
	{
		return Collections.singletonMap(KEY, value.name());
	}

	public Object removeField(String s) { return null; }

	public boolean containsKey(String s)
	{
		return KEY.equals(s);
	}

	public boolean containsField(String s)
	{
		return KEY.equals(s);
	}

	public Set<String> keySet()
	{
		return Collections.singleton(KEY);
	}

	public String toString()
	{
		return "{ \"" + KEY + "\" : \"" + value.name() + "\" }";
	}
}

Using it this way (example main)…

		Mongo mongo = new Mongo();
		DB db = mongo.getDB("test");
		DBCollection collection = db.getCollection("enum");

		DBObject next = new BasicDBObject("key", DBEnum.of(SomeEnum.VALUE_1));
		collection.insert(next);

		next = collection.findOne(new BasicDBObject("key", DBEnum.of(SomeEnum.VALUE_1)));
		System.out.println(next);

		SomeEnum enumValue = DBEnum.to(SomeEnum.class, next.get("key"));
		System.out.println(enumValue);

… prints the expected results and creates the document:

{
	"_id" : ObjectId("4da421708db0535ebbd175c3"),
	"key" : {
		"_enum" : "VALUE_1"
	}
}

Only real downer is the type must be used explictly. And maybe someone wants to implement this directly into the MongoDB Java driver (and others) so the key could turn to “$enum” and become ‘official’…

Greetings,
GHad

Written by ghads

April 12, 2011 at 2:15 pm

Java to XML to Java

leave a comment »

Some simple methods using the integrated JRE-Classes (since Java 1.4) the de/serialize Objects to/from XML (must check out how to post code tonight… see below for an update):

public static Object importXML(File in) {
  try {
    FileInputStream fis = new FileInputStream(in);
    BufferedInputStream bis = new BufferedInputStream(fis);
    XMLDecoder decoder = new XMLDecoder(bis);
    Object result = decoder.readObject();
    decoder.close();
    bis.close();
    fis.close();
    return result;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
public static boolean exportXML(Object in, File out) {
  try {
    FileOutputStream fos = new FileOutputStream(out);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    XMLEncoder encoder = new XMLEncoder(bos);
    encoder.writeObject(in);
    encoder.close();
    bos.close();
    fos.close();
    return true;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return false;
}

Update: Thanks to StackOverflow.com I got the answer to how to blog here in seconds! That’s really really cute!

Written by ghads

September 16, 2008 at 2:49 pm

Posted in Java development

Tagged with , , ,