001: package ru.emdev.EmForge.web.converter;
002:
003: import javax.faces.application.Application;
004: import javax.faces.component.UIComponent;
005: import javax.faces.context.FacesContext;
006: import javax.faces.convert.Converter;
007: import javax.faces.convert.ConverterException;
008:
009: import org.apache.commons.lang.StringUtils;
010:
011: import ru.emdev.EmForge.security.UserFactory;
012: import ru.emdev.EmForge.security.dao.Role;
013:
014: /**
015: * This converter is used to represent role items by JSF select controls
016: *
017: * @author szakusov, 20.03.2008: Implemented for report parameter prefixes feature [^87841]
018: */
019: public class RoleIdConverter implements Converter {
020:
021: protected static final String CONVERT_ERROR = "The value cannot be converted to Role object: ";
022:
023: /**
024: * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext,
025: * javax.faces.component.UIComponent, java.lang.Object)
026: */
027: public String getAsString(FacesContext i_context,
028: UIComponent i_component, Object i_value)
029: throws ConverterException {
030:
031: if (i_context == null) {
032: throw new NullPointerException("facesContext");
033: }
034: if (i_component == null) {
035: throw new NullPointerException("uiComponent");
036: }
037:
038: String result = "";
039:
040: if (i_value != null) {
041: if (i_value instanceof String) {
042: result = (String) i_value;
043:
044: } else {
045: try {
046: Role role = (Role) i_value;
047: result = role.getId().toString();
048: } catch (Exception e) {
049: throw new ConverterException(CONVERT_ERROR
050: + i_value, e);
051: }
052: }
053: }
054:
055: return result;
056: }
057:
058: /**
059: * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext,
060: * javax.faces.component.UIComponent, java.lang.String)
061: */
062: public Object getAsObject(FacesContext i_context,
063: UIComponent i_component, String i_value)
064: throws ConverterException {
065:
066: if (i_context == null) {
067: throw new NullPointerException("facesContext");
068: }
069: if (i_component == null) {
070: throw new NullPointerException("uiComponent");
071: }
072:
073: Role result = null;
074:
075: if (!StringUtils.isEmpty(i_value)) {
076: try {
077: UserFactory userFactory = getUserFactory(i_context);
078: result = userFactory.getRole(i_value);
079: } catch (Exception e) {
080: throw new ConverterException(CONVERT_ERROR + i_value, e);
081: }
082: }
083:
084: return result;
085: }
086:
087: /**
088: * @param i_context
089: * @return
090: */
091: private UserFactory getUserFactory(FacesContext i_context) {
092:
093: Application app = i_context.getApplication();
094: UserFactory userFactory = (UserFactory) app
095: .getVariableResolver().resolveVariable(i_context,
096: "userFactory");
097:
098: assert userFactory != null;
099: return userFactory;
100: }
101: }
|