javax.faces.convert.Converter Java Examples

The following examples show how to use javax.faces.convert.Converter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConverterWrapper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
protected Converter resolveInstanceForClass(FacesContext facesContext, Class<?> wrappedClass)
{
    FacesConverter facesConverter = wrappedClass.getAnnotation(FacesConverter.class);

    if (facesConverter == null)
    {
        return null;
    }

    if (!"".equals(facesConverter.value()))
    {
        return facesContext.getApplication().createConverter(facesConverter.value());
    }

    return facesContext.getApplication().createConverter(facesConverter.forClass());
}
 
Example #2
Source File: SelectOneMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
private boolean isSelected(FacesContext context, SelectOneMenu menu, Object value, Object itemValue,
		Converter converter) {
	if (itemValue == null && value == null) {
		return true;
	}

	if (value != null) {
		Object compareValue;
		if (converter == null) {
			compareValue = coerceToModelType(context, itemValue, value.getClass());
		} else {
			compareValue = itemValue;

			if (compareValue instanceof String && !(value instanceof String)) {
				compareValue = converter.getAsObject(context, menu, (String) compareValue);
			}
		}

		if (value.equals(compareValue)) {
			return true;
		}

	}
	return false;
}
 
Example #3
Source File: SelectOneMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
private String getOptionAsString(FacesContext context, SelectOneMenu menu, Object value, Converter converter)
		throws ConverterException {

	if (converter == null) {
		if (value == null) {
			return "";
		} else if (value instanceof String) {
			return (String) value;
		} else {
			Converter implicitConverter = findImplicitConverter(context, menu);

			return implicitConverter == null ? value.toString()
					: implicitConverter.getAsString(context, menu, value);
		}
	} else {
		return converter.getAsString(context, menu, value);
	}
}
 
Example #4
Source File: RadiobuttonRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
private List<String> collectLegalValues(FacesContext context, List<UIComponent> radioButtonGroup) {
	List<String> legalValues = new ArrayList<String>();
	for (UIComponent b: radioButtonGroup) {
		Radiobutton r = (Radiobutton)b;
		Converter converter = r.getConverter();
		List<SelectItemAndComponent> options = SelectItemUtils.collectOptions(context, r, converter);
		if (options.size()>0) {
			// traditional JSF approach using f:selectItem[s]
			for (SelectItemAndComponent option:options) {
				String o = null;
				if (null != option.getSelectItem().getValue()) {
					o = String.valueOf(option.getSelectItem().getValue());
				}
				legalValues.add(o);
			}

		} else {
			// BootsFaces approach using b:radioButtons for each radiobutton item
			legalValues.add(r.getItemValue());
		}
	}
	return legalValues;
}
 
Example #5
Source File: CoreRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
protected Converter resolveConverter(FacesContext context, UIComponent c, Object value) {
	if (!(c instanceof ValueHolder)) {
		return null;
	}

	Converter cnv = ((ValueHolder) c).getConverter();

	if (cnv != null) {
		return cnv;
	} else {
		ValueExpression ve = c.getValueExpression("value");

		if (ve != null) {
			Class<?> valType = ve.getType(context.getELContext());
			

			if (valType != null && (!valType.isPrimitive())) { // workaround for a Mojarra bug (#966)
				return context.getApplication().createConverter(valType);
			} else if (valType != null && (value instanceof String)) { // workaround for the workaround of the Mojarra bug (#977)
				return context.getApplication().createConverter(valType);
			}
		}

		return null;
	}
}
 
Example #6
Source File: CoreRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the appropriate converter for a given value holder
 *
 * @param fc
 *            FacesContext instance
 * @param vh
 *            ValueHolder instance to look converter for
 * @return Converter
 */
public static Converter getConverter(FacesContext fc, ValueHolder vh) {
	// explicit converter
	Converter converter = vh.getConverter();

	// try to find implicit converter
	if (converter == null) {
		ValueExpression expr = ((UIComponent) vh).getValueExpression("value");
		if (expr != null) {
			Class<?> valueType = expr.getType(fc.getELContext());
			if (valueType != null) {
				converter = fc.getApplication().createConverter(valueType);
			}
		}
	}

	return converter;
}
 
Example #7
Source File: SelectMultiMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
/**
 * Algorithm works as follows; - If it's an input component, submitted value
 * is checked first since it'd be the value to be used in case validation
 * errors terminates jsf lifecycle - Finally the value of the component is
 * retrieved from backing bean and if there's a converter, converted value
 * is returned
 *
 * @param context
 *            FacesContext instance
 * @return End text
 */
public Object getValue2Render(FacesContext context, SelectMultiMenu menu) {
	Object sv = menu.getSubmittedValue();
	if (sv != null) {
		return sv;
	}

	Object val = menu.getValue();
	if (val != null) {
		Converter converter = menu.getConverter();

		if (converter != null)
			return converter.getAsString(context, menu, val);
		else
			return val;

	} else {
		// component is a value holder but has no value
		return null;
	}
}
 
Example #8
Source File: SelectOneMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 6 votes vote down vote up
/**
 * Parts of this class are an adapted version of InputRenderer#getSelectItems()
 * of PrimeFaces 5.1.
 *
 * @param rw
 * @throws IOException
 */
protected void renderOptions(FacesContext context, ResponseWriter rw, SelectOneMenu menu) throws IOException {
	Converter converter = menu.getConverter();
	List<SelectItemAndComponent> items = SelectItemUtils.collectOptions(context, menu, converter);
	
	SelectItemAndComponent selection = determineSelectedItem(context, menu, items, converter);

	for (int index = 0; index < items.size(); index++) {
		SelectItemAndComponent option = items.get(index);

		if (option.getSelectItem().isNoSelectionOption() && 
				menu.isHideNoSelectionOption() && selection != null)
			continue;
		
		renderOption(context, menu, rw, (option.getSelectItem()), index, option.getComponent(), 
				option == selection || (selection == null && option.getSelectItem().isNoSelectionOption()));
	}
}
 
Example #9
Source File: DataSourceIteratorRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
protected Converter findConverter(FacesContext context, UIDataSourceIterator c, ViewDefinition viewDef, ValueColumn vc, Object value) {
    // Explicit converter
    Converter converter = vc.getConverter();
    if(converter!=null) {
        return converter;
    }

    Class<?> converterType = value.getClass();
    if (converterType == null || converterType == String.class || converterType == Object.class) {
        return null;
    }
    
    // Acquire an appropriate converter instance.
    try {
        Application application = context.getApplication();
        return application.createConverter(converterType);
    } catch (Exception e) {
    }
    
    return null;
}
 
Example #10
Source File: DojoComboBoxRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
protected void renderOption(FacesContext context, ResponseWriter writer, UIDojoComboBox component, Converter converter, SelectItem curItem, String currentValue) throws IOException {
    writer.writeText(" ", null);
    writer.startElement("option", component); // $NON-NLS-1$

    String value = convertValue(context,component, converter, curItem.getValue());
    writer.writeAttribute("value", value, "value"); // $NON-NLS-1$ $NON-NLS-2$

    // Get the value to compare to
    boolean isSelected = isSelected(curItem, currentValue);

    if (isSelected) {
        writer.writeAttribute("selected", "selected", "selected"); // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
    }
    if (curItem.isDisabled()) {
        writer.writeAttribute("disabled", "disabled", "disabled"); // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
    }

    writer.writeText(curItem.getLabel(), "label"); // $NON-NLS-1$
    writer.endElement("option"); // $NON-NLS-1$
    writer.writeText("\n", null); // $NON-NLS-1$

}
 
Example #11
Source File: ValueColumn.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
@Override
public void restoreState(FacesContext context, Object state) {
	Object values[] = (Object[]) state;
	super.restoreState(context, values[0]);
       columnTitle = (String)values[1];
       columnName = (String)values[2];
	value = StateHolderUtil.restoreObjectState(context,getComponent(),values[3]);
       converter = (Converter)StateHolderUtil.restoreObjectState(context, getComponent(), values[4]);
       style = (String)values[5];
       styleClass = (String)values[6];
       href = (String)values[7];
       contentType = (String)values[8];
       headerStyle = (String)values[9];
       headerStyleClass = (String)values[10];
       linkTitle = (String)values[11];
       headerLinkTitle = (String)values[12];
}
 
Example #12
Source File: ConverterAndValidatorProxyExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected <T> Bean<T> createBean(Class<T> beanClass, BeanManager beanManager)
{
    Class<? extends InvocationHandler> invocationHandlerClass =
            Converter.class.isAssignableFrom(beanClass) ?
                    ConverterInvocationHandler.class : ValidatorInvocationHandler.class;

    AnnotatedType<T> annotatedType = new AnnotatedTypeBuilder<T>().readFromType(beanClass).create();

    DeltaSpikeProxyContextualLifecycle lifecycle = new DeltaSpikeProxyContextualLifecycle(beanClass,
            invocationHandlerClass, ConverterAndValidatorProxyFactory.getInstance(), beanManager);

    BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager)
            .readFromType(annotatedType)
            .passivationCapable(true)
            .beanLifecycle(lifecycle);

    return beanBuilder.create();
}
 
Example #13
Source File: SelectOneMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
/**
 * Compare current selection with items, if there is any element selected
 * 
 * @param context
 * @param items
 * @param converter
 * @return
 */
private SelectItemAndComponent determineSelectedItem(FacesContext context, SelectOneMenu menu, List<SelectItemAndComponent> items, Converter converter) {
	Object submittedValue = menu.getSubmittedValue();
	Object selectedOption;
	if (submittedValue != null) {
		selectedOption = submittedValue;
	} else {
		selectedOption = menu.getValue();
	}

	for (int index = 0; index < items.size(); index++) {
		SelectItemAndComponent option = items.get(index);
		if (option.getSelectItem().isNoSelectionOption()) continue;
		
		Object itemValue = option.getSelectItem().getValue();
		String itemValueAsString = getOptionAsString(context, menu, itemValue, converter);

		Object optionValue;
		if (submittedValue != null) {
			optionValue = itemValueAsString;
		} else {
			optionValue = itemValue;
		}

		if (itemValue != null) {
			if (isSelected(context, menu, selectedOption, optionValue, converter)) {
				return option;
			}
		} 
	}
	return null;
}
 
Example #14
Source File: CriterionConverterList.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Converter get(int index) {
	CriterionPropertyVO propertyVO = getPropertyVO(index);
	if (propertyVO != null && converterMap.containsKey(propertyVO.getId())) {
		return converterMap.get(propertyVO.getId());
	} else {
		return DUMMY_ID_CONVERTER;
	}
}
 
Example #15
Source File: SketchPadRenderer.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Converter getConverter(FacesContext context, UIComponent component) {
	Converter converter = ((UIInput) component).getConverter();
	if (converter != null) {
		return converter;
	}
	ValueExpression exp = component.getValueExpression("value");
	if (exp == null) {
		return null;
	}
	Class valueType = exp.getType(context.getELContext());
	if (valueType == null) {
		return null;
	}
	return context.getApplication().createConverter(valueType);
}
 
Example #16
Source File: SketchPadRenderer.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Object getValue(FacesContext context, SketchPad sketchPad) {
	Object submittedValue = sketchPad.getSubmittedValue();
	if (submittedValue != null) {
		return submittedValue;
	}
	Object value = sketchPad.getValue();
	Converter converter = getConverter(context, sketchPad);
	if (converter != null) {
		return converter.getAsString(context, sketchPad, value);
	} else if (value != null) {
		return value.toString();
	} else {
		return "";
	}
}
 
Example #17
Source File: SelectOneMenuRenderer.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
private Converter findImplicitConverter(FacesContext context, UIComponent component) {
	ValueExpression ve = component.getValueExpression("value");

	if (ve != null) {
		Class<?> valueType = ve.getType(context.getELContext());

		if (valueType != null)
			return context.getApplication().createConverter(valueType);
	}

	return null;
}
 
Example #18
Source File: Datepicker.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getConvertedValue(FacesContext fc, Object sval) throws ConverterException {
	if (sval == null) {
		return null;
	}

	String val = (String) sval;
	// If the Trimmed submitted value is empty, return null
	if (val.trim().length() == 0) {
		return null;
	}

	Converter converter = getConverter();

	// If the user supplied a converter, use it
	if (converter != null) {
		return converter.getAsObject(fc, this, val);
	}
	// Else we use our own converter
	sloc = selectLocale(fc.getViewRoot().getLocale(), A.asString(getAttributes().get(JQ.LOCALE)));
	sdf = selectDateFormat(sloc, A.asString(getAttributes().get(JQ.DTFORMAT)));

	Calendar cal = Calendar.getInstance(sloc);
	SimpleDateFormat format = new SimpleDateFormat(sdf, sloc);
	format.setTimeZone(cal.getTimeZone());

	try {
		cal.setTime(format.parse(val));
		cal.set(Calendar.HOUR_OF_DAY, 12);

		return cal.getTime();
	} catch (ParseException e) {
		this.setValid(false);
		throw new ConverterException(
				BsfUtils.getMessage("javax.faces.converter.DateTimeConverter.DATE", val, sdf, getLabel(fc)));
	}
}
 
Example #19
Source File: DateTimePickerRenderer.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
/**
 * Get date in string format
 * @param fc The FacesContext
 * @param dtp the DateTimePicker component
 * @param value The date to display
 * @param javaFormatString The format string as defined by the SimpleDateFormat syntax
 * @param locale The locale
 * @return null if the value is null.
 */
public static String getDateAsString(FacesContext fc, DateTimePicker dtp, Object value, String javaFormatString, Locale locale) {
	if (value == null) {
		return null;
	}

	Converter converter = dtp.getConverter();
	return  converter == null ?
			getInternalDateAsString(value, javaFormatString, locale)
			:
			converter.getAsString(fc, dtp, value);

}
 
Example #20
Source File: CoreRenderer.java    From BootsFaces-OSP with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called by the JSF framework to get the type-safe value of the
 * attribute. Do not delete this method.
 */
@Override
public Object getConvertedValue(FacesContext fc, UIComponent c, Object sval) throws ConverterException {
	Converter cnv = resolveConverter(fc, c, sval);

	if (cnv != null) {
		if (sval == null || sval instanceof String) {
			return cnv.getAsObject(fc, c, (String) sval);
		} else {
			return cnv.getAsObject(fc, c, String.valueOf(sval));
		}
	} else {
		return sval;
	}
}
 
Example #21
Source File: DojoExtImageSelectRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
@Override
protected void initDojoAttributes(FacesContext context, FacesDojoComponent dojoComponent, Map<String,String> attrs) throws IOException {
    super.initDojoAttributes(context, dojoComponent, attrs);
    if(dojoComponent instanceof AbstractDojoExtImageSelect) {
        AbstractDojoExtImageSelect c = (AbstractDojoExtImageSelect)dojoComponent;

        // Add the different styles/classes
        DojoRendererUtil.addDojoHtmlAttributes(attrs,"listStyle",combineStyle(PROP_LISTSTYLE, c.getStyle())); // $NON-NLS-1$
        DojoRendererUtil.addDojoHtmlAttributes(attrs,"listClass",combineStyleClass(PROP_LISTCLASS, c.getStyleClass())); // $NON-NLS-1$
        DojoRendererUtil.addDojoHtmlAttributes(attrs,"itemStyle",(String)getProperty(PROP_ITEMSTYLE)); // $NON-NLS-1$
        DojoRendererUtil.addDojoHtmlAttributes(attrs,"itemClass",(String)getProperty(PROP_ITEMCLASS)); // $NON-NLS-1$
        
        // Generate the list of options as JSON
        StringBuilder b = new StringBuilder();
        JsonBuilder w = new JsonBuilder(b,true);
        w.startArray();

        Converter converter = c.getConverter();
        
        int count = c.getImageCount();
        for(int i=0; i<count; i++) {
            ISelectImage img = c.getImage(i);
            String value = convertValue(context,c, converter, img.getSelectedValue());
            if(value!=null) {
                addJsonEntry(context,w,img,value);
            }
            
        }
        
        w.endArray();
        DojoRendererUtil.addDojoHtmlAttributes(attrs,"valueList",b.toString()); // $NON-NLS-1$
    }
}
 
Example #22
Source File: DojoExtImageSelectRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public String convertValue(FacesContext context, UIComponent component, Converter converter, Object value) throws ConverterException {
    if(value!=null) {
        if(converter==null) {
            Application application = context.getApplication();
            converter = application.createConverter(value.getClass());
        }
        // Format it using the converter if necessary, or just converter it to a simple string
        String strValue = converter!=null ? converter.getAsString(context, component, value) 
                                          : value.toString(); 
        return strValue;
    }

    return "";
}
 
Example #23
Source File: DojoExtLinkSelectRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public String convertValue(FacesContext context, UIComponent component, Converter converter, Object value) throws ConverterException {
    if(value!=null) {
        if(converter==null) {
            Application application = context.getApplication();
            converter = application.createConverter(value.getClass());
        }
        // Format it using the converter if necessary, or just converter it to a simple string
        String strValue = converter!=null ? converter.getAsString(context, component, value) 
                                          : value.toString(); 
        return strValue;
    }

    return "";
}
 
Example #24
Source File: DataSourceIteratorRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
protected String formatColumnValue(FacesContext context, UIDataSourceIterator c, ViewDefinition viewDef, ValueColumn vc) throws IOException {
    Object value = getColumnValue(context, c, viewDef, vc);
    if(value!=null) {
        Converter cv = findConverter(context, c, viewDef, vc, value);
        String v = cv!=null ? cv.getAsString(context, c, value) : value.toString();
        return v;
    }
    return null;
}
 
Example #25
Source File: DojoComboBoxRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
void renderOptions(FacesContext context, UIDojoComboBox component, ResponseWriter writer, String currentValue) throws IOException {
    // Find the converter
    Converter converter = component.getConverter();
    
    for( SelectItem curItem: FacesUtil.getSelectItems(component)) {
        // Dojo does not support optgroup - just ignore them
        // http://trac.dojotoolkit.org/ticket/1887
        if (!(curItem instanceof SelectItemGroup)) {
            renderOption(context, writer, component, converter, curItem, currentValue);
        }
    }
}
 
Example #26
Source File: DojoComboBoxRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public String convertValue(FacesContext context, UIComponent component, Converter converter, Object value) throws ConverterException {
    if(value!=null) {
        if(converter==null) {
            Application application = context.getApplication();
            converter = application.createConverter(value.getClass());
        }
        // Format it using the converter if necessary, or just converter it to a simple string
        String strValue = converter!=null ? converter.getAsString(context, component, value) 
                                          : value.toString(); 
        return strValue;
    }

    return "";
}
 
Example #27
Source File: UIDojoTextBox.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
@Override
public void initBeforeContents(FacesContext context) throws FacesException {
   	// Force the converter
	Converter converter = getDefaultConverter();
	if(converter instanceof ComponentBindingObject) {
		((ComponentBindingObject)converter).setComponent(this);
	}
	super.setConverter(converter);
	
	super.initBeforeContents(context);
   }
 
Example #28
Source File: MobileTypeAheadInputRenderer.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
private void validateNoSeparator(FacesContext context, UIInput input, XspTypeAhead typeAhead) {
    boolean separatorDetected = false;
    String separatorType = null;
    if( null != typeAhead.getTokens() ){
        separatorDetected = true;
        separatorType = "xp:typeAhead tokens"; //$NON-NLS-1$
    }
    if( ! separatorDetected ){
        if( input instanceof UIInputEx){
            UIInputEx inputEx = (UIInputEx) input;
            String separator = inputEx.getMultipleSeparator();
            if( null != separator ){
                separatorDetected = true;
                separatorType = "xp:inputText multipleSeparator"; //$NON-NLS-1$
            }
        }
    }
    if( ! separatorDetected ){
        Converter converter = input.getConverter();
        if( converter instanceof ListConverter ){
            separatorDetected = true;
            separatorType = "xp:convertList"; //$NON-NLS-1$
        }
    }
    if( separatorDetected ){
        // String left untagged - hoping to support multiple before begin translating strings for next product release
        String msg = "The mobile xp:typeAhead control does not support entering multiple values in the edit box. A multiple value separator has been detected: {0}"; // $NLS-MobileTypeAheadInputRenderer.ThemobilexptypeAheadcontroldoesno-1$
        msg = StringUtil.format(msg, separatorType);
        throw new FacesExceptionEx(msg);
    }
}
 
Example #29
Source File: ManagedArtifactResolver.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public static Converter resolveManagedConverter(Class<? extends Converter> converterClass)
{
    if (JAVAX_FACES_CONVERT_PACKAGE_NAME.equals(converterClass.getPackage().getName()))
    {
        return null;
    }

    return getContextualReference(BeanManagerProvider.getInstance().getBeanManager(), converterClass);
}
 
Example #30
Source File: InjectionAwareApplicationWrapper.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private Converter managedOrDefaultConverter(Converter defaultResult)
{
    if (!this.containerManagedConvertersEnabled)
    {
        return defaultResult;
    }
    if (defaultResult == null)
    {
        return null;
    }

    Converter result = ManagedArtifactResolver.resolveManagedConverter(defaultResult.getClass());

    if (result == null)
    {
        return defaultResult;
    }

    if (result instanceof DeltaSpikeProxy || ProxyUtils.isProxiedClass(result.getClass()))
    {
        return result;
    }
    else
    {
        return new ConverterWrapper(result, this.fullStateSavingFallbackEnabled);
    }
}