All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.magicwerk.brownies.jdom.JdomConverter Maven / Gradle / Ivy

/*
 * Copyright 2010 by Thomas Mauch
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id: DomTools.java 2721 2015-01-30 01:16:53Z origo $
 */
package org.magicwerk.brownies.jdom;

import org.jdom2.Element;
import org.magicwerk.brownies.core.types.PropertyClass;
import org.magicwerk.brownies.core.types.Type;
import org.magicwerk.brownies.core.values.AbstractConverter;

/**
 * Class for converting objects into JDOM elements.
 *
 * @author Thomas Mauch
 */
public class JdomConverter extends AbstractConverter {

	public enum StorageMode {
		ELEMENT,
		ATTRIBUTE
	}

	StorageMode storageMode = StorageMode.ELEMENT;
	String elemName = null;
	String nullValue = "";

	//

	public JdomConverter() {
	}

	public JdomConverter(Class clazz) {
		super(clazz);
	}

	public JdomConverter(PropertyClass propClass) {
		super(propClass);
	}

	/** Setter for {@link #storageMode} */
	public JdomConverter setStorageMode(StorageMode storageMode) {
		this.storageMode = storageMode;
		return this;
	}

	@Override
	public Element createStore(PropertyClass propClass) {
		if (elemName == null) {
			elemName = propClass.getClassType().getName();
		}
		Element elem = new Element(elemName);
		return elem;
	}

	@Override
	public Object getProperty(Element elem, String name, Type type) {
		String str;
		if (storageMode == StorageMode.ELEMENT) {
			str = JdomTools.getChildText(elem, name);
		} else if (storageMode == StorageMode.ATTRIBUTE) {
			str = JdomTools.getAttributeValue(elem, name);
		} else {
			throw new AssertionError();
		}

		Object val = type.parse(str);
		return val;
	}

	@Override
	public void putProperty(Element elem, String name, Type type, Object val) {
		String str = type.format(val);

		if (storageMode == StorageMode.ELEMENT) {
			if (str == null) {
				JdomTools.setTextValue(elem, name, nullValue);
			} else {
				JdomTools.setTextValue(elem, name, str);
			}
		} else if (storageMode == StorageMode.ATTRIBUTE) {
			if (str == null) {
				JdomTools.setAttributeValue(elem, name, nullValue);
			} else {
				JdomTools.setAttributeValue(elem, name, str);
			}
		} else {
			throw new AssertionError();
		}
	}

}