Skip to content

Instantly share code, notes, and snippets.

@DaHoC
Last active February 1, 2017 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaHoC/e046b9947a88f5a08608aed0d65a5406 to your computer and use it in GitHub Desktop.
Save DaHoC/e046b9947a88f5a08608aed0d65a5406 to your computer and use it in GitHub Desktop.
import org.primefaces.component.orderlist.OrderList;
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 component (orderList).
* Fixes setting of lists with the correct Object values instead of Strings.
* Without it, the setter of List<Object> sets as List<String> instead.
*
* 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 PfOrderListConverter 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 OrderList)
{
final OrderList orderList = (OrderList)component;
if (orderList.getValue() == null)
return null;
final List componentEntries = (List)orderList.getValue();
ret = retrieveObject(componentEntries, 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 collection 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment