Skip to content

Instantly share code, notes, and snippets.

@DaHoC
Last active February 15, 2018 12:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaHoC/f6aff7b767f31d96bc16bdde81504f22 to your computer and use it in GitHub Desktop.
Save DaHoC/f6aff7b767f31d96bc16bdde81504f22 to your computer and use it in GitHub Desktop.
Primefaces Picklist converter
import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import java.util.List;
import java.util.Objects;
/**
* Generic converter for primefaces picklist.
* Without it, the setter of DualListModel<Object> sets its DualListModel<Object> source and target lists
* as lists with type String (DualListModel<String>) instead of lists with the correct Object values.
*
* NOTE: The converter is relying on object.hashCode() - mind the implications of a hash collision,
* you can override the corresponding object's hashCode() to account for that.
*
* @author dahoc
*/
public class PicklistGenericConverter implements Converter
{
@Override
public String getAsString(FacesContext context, UIComponent component, Object entity)
{
if (entity == null)
return "";
return String.valueOf(entity.hashCode());
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid)
{
Object ret = null;
if (uuid == null || uuid.equals(""))
return null;
if (component instanceof PickList)
{
final Object dualList = ((PickList) component).getValue();
final DualListModel dl = (DualListModel) dualList;
ret = retrieveObject(dl.getSource(), uuid);
if (ret == null)
ret = retrieveObject(dl.getTarget(), uuid);
}
return ret;
}
/**
* Function retrieves the object by its hashCode.
* Because this has to be generic, typing is raw - and therefore disable IDE warning.
*
* @param objects list of arbitrary objects
* @param uuid hashCode of the object to retrieve
* @return correct object with corresponding hashCode or null, if none found
*/
@SuppressWarnings("unchecked")
private Object retrieveObject(final List objects, final String uuid)
{
return objects
.stream()
.filter(Objects::nonNull)
.filter(obj -> uuid.equals(String.valueOf(obj.hashCode())))
.findFirst()
.orElse(null);
}
}
@ernest0994
Copy link

dude u saved my life

@samsonsouley
Copy link

Hi,
Is this work with POJO?
I try to put this class as a converter in the Picklist using my POJO. It do not work. Can you please help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment