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

com.github.adminfaces.persistence.converter.EntityConverter Maven / Gradle / Ivy

There is a newer version: 1.2.0
Show newest version
package com.github.adminfaces.persistence.converter;


import com.github.adminfaces.persistence.model.PersistenceEntity;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

@FacesConverter(forClass = PersistenceEntity.class, value = "entityConverter")
public class EntityConverter implements Converter {

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object entity) {
		if (entity == null || "".equals(entity)) {
			return null;
		}
		
		if (!getEntityMap(context).containsKey(entity)) {
			String uuid = UUID.randomUUID().toString();
			getEntityMap(context).put(entity, uuid);
			return uuid;
		} else {
			return getEntityMap(context).get(entity);
		}
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
		Set> entries = getEntityMap(context).entrySet();
		for (Entry entry : entries) {
			if (entry.getValue().equals(uuid)) {
				return entry.getKey();
			}
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private Map getEntityMap(FacesContext context) {
		Map viewMap = context.getViewRoot().getViewMap();
		Map entities = (Map) viewMap.get("entities");
		if (entities == null) {
			entities = new HashMap<>();
			viewMap.put("entities", entities);
		}
		return entities;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy