Skip to content

Instantly share code, notes, and snippets.

@fabiojb
Last active Jul 11, 2016
Embed
What would you like to do?
JSF Generic converter for Entities, Enums, etc.
package org.teste.model;
public interface Identifiable<T> {
public T getId();
}
package org.teste.view.converter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import javax.faces.component.PartialStateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.teste.model.Identifiable;
@SuppressWarnings("rawtypes")
public class IdentifiableConverter implements Converter, PartialStateHolder {
private Map<String, Identifiable> values;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null)
return null;
for (Map.Entry<String, Identifiable> entry : values.entrySet()) {
if (value.equals(entry.getKey())) {
return entry.getValue();
}
}
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Identifiable)) {
throw new IllegalArgumentException(
MessageFormat.format("The value {0} is not an instance of Identifiable", value));
}
if (values == null) {
values = new HashMap<>();
}
Identifiable identifiable = (Identifiable) value;
String string = identifiable.getId().toString();
values.put(string, identifiable);
return string;
}
@Override
public Object saveState(FacesContext context) {
return values;
}
@SuppressWarnings("unchecked")
@Override
public void restoreState(FacesContext context, Object state) {
values = (Map<String, Identifiable>) state;
}
private boolean isTransient;
@Override
public boolean isTransient() {
return isTransient;
}
@Override
public void setTransient(boolean b) {
isTransient = b;
}
private boolean initialState;
@Override
public void markInitialState() {
initialState = true;
}
@Override
public boolean initialStateMarked() {
return initialState;
}
@Override
public void clearInitialState() {
initialState = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment