public void applyAttachedObject(FacesContext context, UIComponent parent) { FaceletContext ctx = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY); // cast to a ValueHolder ValueHolder vh = (ValueHolder) parent; ValueExpression ve = null; Converter c = null; if (this.binding != null) { ve = this.binding.getValueExpression(ctx, Converter.class); c = (Converter) ve.getValue(ctx); } if (c == null) { c = this.createConverter(ctx); if (ve != null) { ve.setValue(ctx, c); } } if (c == null) { throw new TagException(this.tag, "No Converter was created"); } this.setAttributes(ctx, c); vh.setConverter(c); Object lv = vh.getLocalValue(); FacesContext faces = ctx.getFacesContext(); if (lv instanceof String) { vh.setValue(c.getAsObject(faces, parent, (String) lv)); } }
@Override public Object getConvertedValue(FacesContext context, UIComponent component, Object val) throws ConverterException { String s = (String) val; Converter converter = getConverterForValue(context, component); if (converter != null) { return converter.getAsObject(context, component, s); } else { return s; } }
@Override public Object getConvertedValue( FacesContext context, UIComponent component, Object submittedValue) throws ConverterException { UIInputListOfValues inputDate = (UIInputListOfValues) component; Converter converter = inputDate.getConverter(); if (converter != null) { return converter.getAsObject(context, component, String.valueOf(submittedValue)); } if (submittedValue != null && String.valueOf(submittedValue).trim().isEmpty()) return null; return submittedValue; }
public Object getAsObject(FacesContext context, UIComponent component, String value) { Converter delegate = getDelegate(context); if (delegate != null) { return delegate.getAsObject(context, component, value); } else { throw new ConverterException( MessageUtils.getExceptionMessage( MessageUtils.CANNOT_CONVERT_ID, converterId != null ? converterId.getExpressionString() : "", binding != null ? binding.getExpressionString() : "")); } }
public void setupCurrentRowVariables() { if (_evaluatingConverterInsideSetupCurrentRowVariables) { // Prevent endless recursion in the column.getGroupingValueConverter() call (see below). // The grouping-related variables are not required during calculation of // groupingValueConverter, // so we can just skip this method if _evaluatingConverterInsideSetupCurrentRowVariables == // true return; } DataTable dataTable = getDataTable(); Object rowData = dataTable.isRowAvailable() ? dataTable.getRowData() : null; if (!(rowData instanceof GroupHeaderOrFooter)) { Components.setRequestVariable(getColumnHeaderVar(), null); Components.setRequestVariable(getGroupingValueVar(), null); Components.setRequestVariable(getGroupingValueStringVar(), null); return; } GroupHeaderOrFooter row = (GroupHeaderOrFooter) rowData; RowGroup rowGroup = row.getRowGroup(); String columnId = rowGroup.getColumnId(); Column column = (Column) dataTable.getColumnById(columnId); String columnHeader = column.getColumnHeader(); Components.setRequestVariable(getColumnHeaderVar(), columnHeader); Object groupingValue = rowGroup.getGroupingValue(); Components.setRequestVariable(getGroupingValueVar(), groupingValue); Converter groupingValueConverter; _evaluatingConverterInsideSetupCurrentRowVariables = true; // The upcoming getGroupingValueConverter call can invoke table's setRowIndex, which will result // re-entering this setupCurrentRowVariables method, so we should prevent endless recursion // here. try { groupingValueConverter = column.getGroupingValueConverter(); } finally { _evaluatingConverterInsideSetupCurrentRowVariables = false; } FacesContext context = FacesContext.getCurrentInstance(); if (groupingValueConverter == null) { groupingValueConverter = groupingValue != null ? Rendering.getConverterForType(context, groupingValue.getClass()) : null; } String groupingValueStr = groupingValueConverter != null ? groupingValueConverter.getAsString(context, column, groupingValue) : groupingValue != null ? groupingValue.toString() : ""; Components.setRequestVariable(getGroupingValueStringVar(), groupingValueStr); }
private String encodeParentAndChildrenAsString(FacesContext fc, UIComponent uic) { StringBuffer str = new StringBuffer(); if (uic instanceof CommandSortHeader) { if (uic.getChildCount() > 0) { Iterator iter = uic.getChildren().iterator(); while (iter.hasNext()) { UIComponent child = (UIComponent) iter.next(); str.append(encodeParentAndChildrenAsString(fc, child)); } } } Object value = uic.getAttributes().get("value"); if (value == null) { ValueBinding vb = uic.getValueBinding("value"); if (vb != null) { value = vb.getValue(fc); } } if (value == null) { return str.toString(); } Converter converter = null; if (uic instanceof ValueHolder) { converter = ((ValueHolder) uic).getConverter(); } if (converter == null) { converter = FacesContext.getCurrentInstance().getApplication().createConverter(value.getClass()); } if (converter != null) { str.append(converter.getAsString(FacesContext.getCurrentInstance(), uic, value)); } else { str.append(value); } // don't process selectItems or f:param for uiCommand) if (uic instanceof UISelectBoolean || uic instanceof UISelectMany || uic instanceof UISelectOne || uic instanceof UICommand) { return str.toString(); } if (uic.getChildCount() > 0) { Iterator iter = uic.getChildren().iterator(); while (iter.hasNext()) { UIComponent child = (UIComponent) iter.next(); str.append(encodeParentAndChildrenAsString(fc, child)); } } return str.toString(); }
public static Object getConvertedUIOutputValue( final FacesContext context, final UIOutput output, final Object submittedValue) throws ConverterException { if (submittedValue == null) { return null; } final Converter converter = findConverter(context, output); if (converter == null) { return submittedValue; } return converter.getAsObject( context, output, (submittedValue instanceof String) ? (String) submittedValue : null); }
@Override public Object getConvertedValue( FacesContext context, UIComponent component, Object submittedValue) throws ConverterException { Converter converter = ComponentUtils.getConverter(context, component); if (converter != null) { String convertableValue = submittedValue == null ? null : submittedValue.toString(); return converter.getAsObject(context, component, convertableValue); } else { return submittedValue; } }
@Override public Object getConvertedValue( FacesContext context, UIComponent component, Object submittedValue) throws ConverterException { Editor editor = (Editor) component; String value = (String) submittedValue; Converter converter = ComponentUtils.getConverter(context, component); if (converter != null) { return converter.getAsObject(context, editor, value); } return value; }
public void testNumberConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Tesing NumberConverter"); UIInput text = new UIInput(); text.setId("my_input_number"); root.getChildren().add(text); Converter converter = application.createConverter("javax.faces.Number"); String stringToConvert = "99.9"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.lang.Number); String str = converter.getAsString(getFacesContext(), text, obj); assertTrue(str.equals(stringToConvert)); }
private NumberConverter getNumberConverter(Converter existingConverter) { if (existingConverter != null) { if (!(existingConverter instanceof NumberConverter)) { throw WidgetProcessorException.newException( "Unable to set number attributes on a " + existingConverter.getClass()); } return (NumberConverter) existingConverter; } // In case the application defines its own one FacesContext context = FacesContext.getCurrentInstance(); NumberConverter numberConverter = (NumberConverter) context.getApplication().createConverter(Number.class); if (numberConverter != null) { return numberConverter; } // The JSF default return new NumberConverter(); }
private DateTimeConverter getDateTimeConverter(Converter existingConverter) { if (existingConverter != null) { if (!(existingConverter instanceof DateTimeConverter)) { throw WidgetProcessorException.newException( "Unable to set date/time attributes on a " + existingConverter.getClass()); } return (DateTimeConverter) existingConverter; } // In case the application defines its own one FacesContext context = FacesContext.getCurrentInstance(); DateTimeConverter dateTimeConverter = (DateTimeConverter) context.getApplication().createConverter(Date.class); if (dateTimeConverter != null) { return dateTimeConverter; } // The JSF default return new DateTimeConverter(); }
@Before public void setupMocks() { SpringFacesContextSetter.setCurrentInstance(springFacesContext); given(springFacesContext.getFacesContext()).willReturn(facesContext); given(facesContext.getApplication()).willReturn(application); given(application.createConverter("example")).willReturn(facesConverter); given(application.createConverter(ClassWithConverter.class)).willReturn(facesConverter); given(facesConverter.getAsObject(facesContext, null, source)).willReturn(converted); }
/** * 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 * * <p>- If the component is not a value holder, toString of component is used to support Facelets * UIInstructions. * * @param facesContext FacesContext instance * @param component UIComponent instance whose value will be returned * @return End text */ public static String getStringValueToRender(FacesContext facesContext, UIComponent component) { if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { Object submittedValue = ((EditableValueHolder) component).getSubmittedValue(); if (submittedValue != null) { return submittedValue.toString(); } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); if (value == null) return ""; // first ask the converter if (valueHolder.getConverter() != null) { return valueHolder.getConverter().getAsString(facesContext, component, value); } // Try to guess else { ValueExpression expr = component.getValueExpression("value"); if (expr != null) { Class<?> valueType = expr.getType(facesContext.getELContext()); if (valueType != null) { Converter converterForType = facesContext.getApplication().createConverter(valueType); if (converterForType != null) return converterForType.getAsString(facesContext, component, value); } } } // No converter found just return the value as string return value.toString(); } else { // This would get the plain texts on UIInstructions when using Facelets String value = component.toString(); if (value != null) return value.trim(); else return ""; } }
public static Object getConvertedUIOutputValues( final FacesContext context, final UIOutput output, final Object submittedValue) { if (submittedValue == null) { return null; } final Converter converter = findConverter(context, output); if (converter == null) { return submittedValue; } final int length = Array.getLength(submittedValue); final Class valueType = getValueType(context, output); final Object ret = Array.newInstance(valueType, length); for (int i = 0; i < length; ++i) { final Object target = Array.get(submittedValue, i); final String value = (target instanceof String) ? (String) target : null; final Object o = converter.getAsObject(context, output, value); ArrayUtil.setArrayValue(ret, valueType, o, i); } return ret; }
/** * Resolves the end text to render by using a specified value * * @param facesContext FacesContext instance * @param component UIComponent instance whose value will be returned * @return End text */ public static String getStringValueToRender( FacesContext facesContext, UIComponent component, Object value) { if (value == null) return null; ValueHolder valueHolder = (ValueHolder) component; Converter converter = valueHolder.getConverter(); if (converter != null) { return converter.getAsString(facesContext, component, value); } else { ValueExpression expr = component.getValueExpression("value"); if (expr != null) { Class<?> valueType = expr.getType(facesContext.getELContext()); Converter converterForType = facesContext.getApplication().createConverter(valueType); if (converterForType != null) return converterForType.getAsString(facesContext, component, value); } } return value.toString(); }
/** * populate the argument component with values, being sensitive to the possible multi-nature of * the values, and to the type of the values. * * @param context the <code>FacesContext</code> for the current request * @param component the <code>UIComponent</code> to populate * @param componentType the component type * @param value the value * @param valueType the value type */ private void populateComponentWithValue( FacesContext context, UIComponent component, String componentType, String value, String valueType) { Application application = context.getApplication(); Converter converter = null; // if we need a converter, and can have a converter if (!"java.lang.String".equals(valueType) && component instanceof ValueHolder) { // if so create it, try { converter = application.createConverter(CarStore.loadClass(valueType, this)); // add it to our component, ((ValueHolder) component).setConverter(converter); } catch (ClassNotFoundException cne) { FacesMessage errMsg = MessageFactory.getMessage(CONVERTER_ERROR_MESSAGE_ID, valueType); throw new IllegalStateException(errMsg.getSummary()); } } // if this component is a SelectOne or SelectMany, take special action if (isMultiValue(componentType)) { // create a UISelectItems instance UISelectItems items = new UISelectItems(); items.setValue(parseStringIntoArrayList(value, converter)); // add it to the component component.getChildren().add(items); } else { // we have a single value if (null != converter) { component.getAttributes().put("value", converter.getAsObject(context, component, value)); } else { component.getAttributes().put("value", value); } } }
protected String getOptionAsString( FacesContext context, UIComponent component, Converter converter, Object value) throws ConverterException { if (!(component instanceof ValueHolder)) { return value == null ? null : value.toString(); } if (converter == null) { if (value == null) { return ""; } else if (value instanceof String) { return (String) value; } else { Converter implicitConverter = findImplicitConverter(context, component); return implicitConverter == null ? value.toString() : implicitConverter.getAsString(context, component, value); } } else { return converter.getAsString(context, component, value); } }
@Test public void testGetAsObject() { Converter converter = new AtomicIntegerConverter(); assertNull(converter.getAsObject(null, null, null)); assertNull(converter.getAsObject(null, null, "")); assertNull(converter.getAsObject(null, null, " ")); assertTrue(8 == ((AtomicInteger) converter.getAsObject(null, null, " 8")).intValue()); assertTrue(8 == ((AtomicInteger) converter.getAsObject(null, null, "8 ")).intValue()); assertTrue(8 == ((AtomicInteger) converter.getAsObject(null, null, "8")).intValue()); int over = Integer.MAX_VALUE + 1; assertTrue(over == ((AtomicInteger) converter.getAsObject(null, null, over + "")).intValue()); int under = Integer.MIN_VALUE - 1; assertTrue(under == ((AtomicInteger) converter.getAsObject(null, null, under + "")).intValue()); try { converter.getAsObject(null, null, "NaN"); fail("should only take numbers"); } catch (ConverterException c) { } }
/** * Overloads getFormattedValue to take a advantage of a previously obtained converter. * * @param context the FacesContext for the current request * @param component UIComponent of interest * @param currentValue the current value of <code>component</code> * @param converter the component's converter * @return the currentValue after any associated Converter has been applied * @throws ConverterException if the value cannot be converted */ protected String getFormattedValue( FacesContext context, UIComponent component, Object currentValue, Converter converter) throws ConverterException { // formatting is supported only for components that support // converting value attributes. if (!(component instanceof ValueHolder)) { if (currentValue != null) { return currentValue.toString(); } return null; } if (converter == null) { // If there is a converter attribute, use it to to ask application // instance for a converter with this identifer. converter = ((ValueHolder) component).getConverter(); } if (converter == null) { // if value is null and no converter attribute is specified, then // return a zero length String. if (currentValue == null) { return ""; } // Do not look for "by-type" converters for Strings if (currentValue instanceof String) { return (String) currentValue; } // if converter attribute set, try to acquire a converter // using its class type. Class converterType = currentValue.getClass(); converter = Util.getConverterForClass(converterType, context); // if there is no default converter available for this identifier, // assume the model type to be String. if (converter == null) { return currentValue.toString(); } } return converter.getAsString(context, component, currentValue); }
@Test public void testGetAsString() { Converter converter = new AtomicIntegerConverter(); assertEquals("", converter.getAsString(null, null, null)); assertEquals("", converter.getAsString(null, null, "")); assertEquals(" ", converter.getAsString(null, null, " ")); assertEquals("-1", converter.getAsString(null, null, new AtomicInteger(-1))); try { converter.getAsString(null, null, new Integer(0)); fail("should only take atomic ints"); } catch (ConverterException c) { } }
public static Object getObjectFromRequestParameter( String requestParameterName, Converter converter, UIComponent component) { String theId = JsfUtil.getRequestParameter(requestParameterName); return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId); }
public void testConverterUpdate() { FacesContext context = getFacesContext(); Application app = context.getApplication(); Converter intConverter = application.createConverter("javax.faces.Integer"); Converter intConverter2 = application.createConverter(Integer.TYPE); Converter intConverter3 = application.createConverter(Integer.class); assertTrue( IntegerConverter.class.equals(intConverter.getClass()) && IntegerConverter.class.equals(intConverter2.getClass()) && IntegerConverter.class.equals(intConverter3.getClass())); app.addConverter("javax.faces.Integer", CustomIntConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue( CustomIntConverter.class.equals(intConverter.getClass()) && CustomIntConverter.class.equals(intConverter2.getClass()) && CustomIntConverter.class.equals(intConverter3.getClass())); app.addConverter(Integer.TYPE, IntegerConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue( IntegerConverter.class.equals(intConverter.getClass()) && IntegerConverter.class.equals(intConverter2.getClass()) && IntegerConverter.class.equals(intConverter3.getClass())); app.addConverter(Integer.class, CustomIntConverter.class.getName()); intConverter = application.createConverter("javax.faces.Integer"); intConverter2 = application.createConverter(Integer.TYPE); intConverter3 = application.createConverter(Integer.class); assertTrue( CustomIntConverter.class.equals(intConverter.getClass()) && CustomIntConverter.class.equals(intConverter2.getClass()) && CustomIntConverter.class.equals(intConverter3.getClass())); // reset to the standard converter app.addConverter("javax.faces.Integer", IntegerConverter.class.getName()); }
private static String stringValue(UIComponent component, Long toConvert, FacesContext context) { Converter converter = context.getApplication().createConverter("javax.faces.Number"); return converter.getAsString(context, component, toConvert); }
public static Object getConvertedValue( FacesContext facesContext, UIComponent component, Object val) throws ConverterException { String[] values = (val == null) ? new String[0] : (String[]) val; Converter converter = SelectManyHelper.getItemConverter(facesContext, component); ValueExpression ve = component.getValueExpression("value"); Object targetForConvertedValues = null; if (ve != null) { // If the component has a ValueExpression for value, let modelType be the type of the value // expression Class<?> modelType = ve.getType(facesContext.getELContext()); if (modelType.isArray()) { // If the component has a ValueExpression for value and the type of the expression is an // array, let targetForConvertedValues be a new array of the expected type. Class<?> arrayComponentType = modelType.getComponentType(); targetForConvertedValues = Array.newInstance(arrayComponentType, values.length); } else if (Collection.class.isAssignableFrom(modelType) || Object.class.equals(modelType)) { // If modelType is a Collection, do the following to arrive at targetForConvertedValues: // Ask the component for its attribute under the key "collectionType" String collectionType = (String) component.getAttributes().get("collectionType"); if (collectionType != null) { // Let targetForConvertedValues be a new instance of Collection implemented by the // concrete class specified in collectionType Class<?> collectionClass = getCollectionClass(collectionType); try { targetForConvertedValues = collectionClass.newInstance(); } catch (Exception e) { throw new FacesException(e); } } else { // If there is no "collectionType" attribute, call getValue() on the component // The result will implement Collection. Collection value = (Collection) ((EditableValueHolder) component).getValue(); if (value instanceof Cloneable) { // If the result also implements Cloneable, let targetForConvertedValues be the result // of calling its clone() method, // then calling clear() on the cloned Collection. try { targetForConvertedValues = (Collection) value.getClass().getMethod("clone").invoke(value); ((Collection) targetForConvertedValues).clear(); } catch (Exception e) { // If unable to clone the value for any reason, log a message LOG.log(Logger.Level.WARNING, "Unable to clone collection"); } } if (targetForConvertedValues == null) { // and proceed to the next step Class<?> collectionClass = value == null ? modelType : value.getClass(); try { // If modelType is a concrete class, let targetForConvertedValues be a new instance of // that class. targetForConvertedValues = collectionClass.newInstance(); ((Collection) targetForConvertedValues).clear(); } catch (Exception e) { // Otherwise, the concrete type for targetForConvertedValues is taken from the // following table if (Collection.class.isAssignableFrom(modelType)) { if (SortedSet.class.isAssignableFrom(modelType)) { targetForConvertedValues = new TreeSet(); } else if (Queue.class.isAssignableFrom(modelType)) { targetForConvertedValues = new LinkedList(); } else if (Set.class.isAssignableFrom(modelType)) { targetForConvertedValues = new HashSet(values.length); } else { targetForConvertedValues = new ArrayList(values.length); } } } } } } else { throw new FacesException("ValueExpression must be either an Array, or a Collection"); } } else { // If the component does not have a ValueExpression for value, let targetForConvertedValues be // an array of type Object. targetForConvertedValues = new Object[values.length]; } for (int i = 0; i < values.length; i++) { Object value; if (converter == null) { value = values[i]; } else { value = converter.getAsObject(facesContext, component, values[i]); } if (targetForConvertedValues.getClass().isArray()) { Array.set(targetForConvertedValues, i, value); } else { ((Collection) targetForConvertedValues).add(value); } } return targetForConvertedValues; }
public void testDateConverter(UIViewRoot root) throws ConverterException, InstantiationException, IllegalAccessException, ClassNotFoundException { System.out.println("Testing DateConverter"); UIInput text = new UIInput(); text.setId("my_input_date"); root.getChildren().add(text); Converter converter = null; converter = application.createConverter("javax.faces.DateTime"); // date String stringToConvert = "Jan 1, 1967"; Object obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); String str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // time converter = application.createConverter("javax.faces.DateTime"); ((DateTimeConverter) converter).setType("time"); text = new UIInput(); text.setId("my_input_time"); stringToConvert = "10:10:10 AM"; obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // datetime converter = application.createConverter("javax.faces.DateTime"); ((DateTimeConverter) converter).setType("both"); text = new UIInput(); text.setId("my_input_datetime"); stringToConvert = "Jan 1, 1967 10:10:10 AM"; obj = converter.getAsObject(getFacesContext(), text, stringToConvert); assertTrue(obj instanceof java.util.Date); str = converter.getAsString(getFacesContext(), text, obj); // make sure we end up with the same string we started with.. assertTrue(str.equals(stringToConvert)); // test bogus type.... boolean exceptionThrown = false; try { ((DateTimeConverter) converter).setType("foobar"); obj = converter.getAsObject(getFacesContext(), text, stringToConvert); } catch (Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); // test NullPointerException (if either context or component arg is null) exceptionThrown = false; try { obj = converter.getAsObject(null, text, stringToConvert); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { obj = converter.getAsObject(getFacesContext(), null, stringToConvert); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { str = converter.getAsString(null, text, obj); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { str = converter.getAsString(getFacesContext(), null, obj); } catch (NullPointerException npe) { exceptionThrown = true; } assertTrue(exceptionThrown); }
public static String getAsConvertedString(Object object, Converter converter) { return converter.getAsString(FacesContext.getCurrentInstance(), null, object); }