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

com.podio.item.map.converter.StateConverter Maven / Gradle / Ivy

There is a newer version: 0.7.9
Show newest version
package com.podio.item.map.converter;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;

public class StateConverter implements FieldConverter {

	private final List states;

	public StateConverter(List states) {
		super();
		this.states = states;
	}

	@Override
	public Map fromModel(Object value) {
		if (value.getClass().isEnum()) {
			String stringValue = value.toString();
			stringValue = stringValue.replace(' ', '_');

			for (String state : states) {
				if (state.equalsIgnoreCase(stringValue)) {
					return Collections.singletonMap("value", state);
				}
			}

			throw new RuntimeException("No state with name " + stringValue
					+ " found");
		} else {
			String stringValue = (String) ConvertUtils.convert(value,
					String.class);

			return Collections.singletonMap("value", stringValue);
		}
	}

	@Override
	public Object toModel(Map map, Class modelClass) {
		String state = (String) map.get("value");

		if (modelClass.isEnum()) {
			return Enum.valueOf(modelClass, state.toUpperCase());
		} else {
			return ConvertUtils.convert(state, modelClass);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy