Example usage for java.beans PropertyEditor setAsText

List of usage examples for java.beans PropertyEditor setAsText

Introduction

In this page you can find the example usage for java.beans PropertyEditor setAsText.

Prototype

void setAsText(String text) throws java.lang.IllegalArgumentException;

Source Link

Document

Set the property value by parsing a given String.

Usage

From source file:org.helios.redis.ts.controller.conn.RedisConnectionManager.java

/**
 * Initializes the pool config from the pool properties
 * @param configProps the pool properties
 *//*  w w  w.j av  a 2s. c om*/
protected void initPoolConfig(Properties configProps) {
    String fName = null;
    try {
        for (String s : configProps.stringPropertyNames()) {
            if (s.startsWith("redis.pool.")) {
                fName = s.replace("redis.pool.", "");
                Field f = poolConfigFieldNames.get(fName);
                if (f != null) {
                    String value = configProps.getProperty(s);
                    if (value == null || value.trim().isEmpty())
                        continue;
                    value = value.trim();
                    PropertyEditor pe = PropertyEditorManager.findEditor(f.getType());
                    pe.setAsText(value);
                    f.set(poolConfig, pe.getValue());
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to configure Jedis Pool Item [" + fName + "]", e);
    }
}

From source file:org.grails.plugins.elasticsearch.conversion.unmarshall.DomainClassUnmarshaller.java

private Object unmarshallProperty(GrailsDomainClass domainClass, String propertyName, Object propertyValue,
        DefaultUnmarshallingContext unmarshallingContext) {
    // TODO : adapt behavior if the mapping option "component" or "reference" are set
    // below is considering the "component" behavior
    SearchableClassPropertyMapping scpm = elasticSearchContextHolder.getMappingContext(domainClass)
            .getPropertyMapping(propertyName);
    Object parseResult = null;/*from  w  ww.  j  a v a 2  s.  c o  m*/
    if (null == scpm) {
        // TODO: unhandled property exists in index
    }
    if (null != scpm && propertyValue instanceof Map) {

        @SuppressWarnings({ "unchecked" })
        Map<String, Object> data = (Map<String, Object>) propertyValue;

        // Handle cycle reference
        if (data.containsKey("ref")) {
            unmarshallingContext.addCycleRef(propertyValue);
            return null;
        }

        // Searchable reference.
        if (scpm.getReference() != null) {
            Class<?> refClass = scpm.getBestGuessReferenceType();
            GrailsDomainClass refDomainClass = null;
            for (GrailsClass dClazz : grailsApplication.getArtefacts(DomainClassArtefactHandler.TYPE)) {
                if (dClazz.getClazz().equals(refClass)) {
                    refDomainClass = (GrailsDomainClass) dClazz;
                    break;
                }
            }
            if (refDomainClass == null) {
                throw new IllegalStateException("Found reference to non-domain class: " + refClass);
            }
            return unmarshallReference(refDomainClass, data, unmarshallingContext);
        }

        if (data.containsKey("class")) {
            // Embedded instance.
            if (!scpm.isComponent()) {
                // maybe ignore?
                throw new IllegalStateException("Property " + domainClass.getName() + "." + propertyName
                        + " is not mapped as [component], but broken search hit found.");
            }
            GrailsDomainClass nestedDomainClass = (GrailsDomainClass) grailsApplication
                    .getArtefact(DomainClassArtefactHandler.TYPE, (String) data.get("class"));
            if (domainClass != null) {
                // Unmarshall 'component' instance.
                if (!scpm.isComponent()) {
                    throw new IllegalStateException("Object " + data.get("class") + " found in index, but ["
                            + propertyName + "] is not mapped as component.");
                }
                parseResult = unmarshallDomain(nestedDomainClass, data.get("id"), data, unmarshallingContext);
            }
        }
    } else if (propertyValue instanceof Collection) {
        List<Object> results = new ArrayList<Object>();
        int index = 0;
        for (Object innerValue : (Collection) propertyValue) {
            unmarshallingContext.getUnmarshallingStack().push(String.valueOf(index));
            Object parseItem = unmarshallProperty(domainClass, propertyName, innerValue, unmarshallingContext);
            if (parseItem != null) {
                results.add(parseItem);
            }
            index++;
            unmarshallingContext.getUnmarshallingStack().pop();
        }
        parseResult = results;
    } else {
        // consider any custom property editors here.
        if (scpm.getConverter() != null) {
            if (scpm.getConverter() instanceof Class) {
                try {
                    PropertyEditor propertyEditor = (PropertyEditor) ((Class) scpm.getConverter())
                            .newInstance();
                    propertyEditor.setAsText((String) propertyValue);
                    parseResult = propertyEditor.getValue();
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                            "Unable to unmarshall " + propertyName + " using " + scpm.getConverter(), e);
                }
            }
        } else if (scpm.getReference() != null) {

            // This is a reference and it MUST be null because it's not a Map.
            if (propertyValue != null) {
                throw new IllegalStateException("Found searchable reference which is not a Map: " + domainClass
                        + "." + propertyName + " = " + propertyValue);
            }

            parseResult = null;
        }
    }
    if (parseResult != null) {
        return parseResult;
    } else {
        return propertyValue;
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.bundle.layout.elements.AbstractElementReadHandler.java

private void setAttributeValue(final ReportElement element, final String namespace, final String name,
        final String attributeValue, final ReportAttributeMap attributes) throws ParseException {
    final AttributeMetaData attributeMetaData = metaData.getAttributeDescription(namespace, name);
    if (attributeMetaData == null || attributeValue == null) {
        element.setAttribute(namespace, name, attributeValue);
        return;//from   ww w . j  a v  a2s . c o m
    }

    if (attributeMetaData.isTransient()) {
        return;
    }

    if (isFiltered(attributeMetaData)) {
        return;
    }

    if (ElementMetaData.VALUEROLE_RESOURCE.equals(attributeMetaData.getValueRole())) {
        try {
            final Object type = attributes.getAttribute(AttributeNames.Core.NAMESPACE, "resource-type");
            if ("url".equals(type)) {
                element.setAttribute(namespace, name, new URL(attributeValue));
                return;
            }
            if ("file".equals(type)) {
                element.setAttribute(namespace, name, new File(attributeValue));
                return;
            }
            if ("local-ref".equals(type)) {
                element.setAttribute(namespace, name, attributeValue);
                return;
            }
            if ("resource-key".equals(type)) {
                final ResourceManager resourceManager = getRootHandler().getResourceManager();
                final ResourceKey key = getRootHandler().getContext();
                final ResourceKey parent = key.getParent();
                final ResourceKey valueKey = resourceManager.deserialize(parent, attributeValue);

                // make local ..
                final ResourceKey resourceKey = localizeKey(resourceManager, valueKey);
                element.setAttribute(namespace, name, resourceKey);
                return;
            }
            element.setAttribute(namespace, name, attributeValue);
            return;
        } catch (MalformedURLException e) {
            throw new ParseException("Failed to parse URL value", e);
        } catch (ResourceKeyCreationException e) {
            throw new ParseException("Failed to parse resource-key value", e);
        }
    }

    final Class type = attributeMetaData.getTargetType();
    if (String.class.equals(type)) {
        element.setAttribute(namespace, name, attributeValue);
    } else {
        try {
            final PropertyEditor propertyEditor = attributeMetaData.getEditor();
            if (propertyEditor != null) {
                propertyEditor.setAsText(attributeValue);
                element.setAttribute(namespace, name, propertyEditor.getValue());
            } else {
                final ConverterRegistry instance = ConverterRegistry.getInstance();
                final ValueConverter valueConverter = instance.getValueConverter(type);
                if (valueConverter != null) {
                    final Object o = ConverterRegistry.toPropertyValue(attributeValue, type);
                    element.setAttribute(namespace, name, o);
                } else if (String.class.isAssignableFrom(type)) {
                    // the attribute would allow raw-string values, so copy the element ..
                    element.setAttribute(namespace, name, attributeValue);
                }
            }

        } catch (BeanException e) {
            // ignore.
            AbstractElementReadHandler.logger.warn("Attribute '" + namespace + '|' + name
                    + "' is not convertible with the bean-methods " + getLocator());
        }
    }
}

From source file:com.sun.faces.el.impl.Coercions.java

/**
 * Coerces a value to the specified Class that is not covered by any
 * of the above cases/*w w w .j  a  va 2s  .  c om*/
 */
public static Object coerceToObject(Object pValue, Class pClass) throws ElException {
    if (pValue == null) {
        return null;
    } else if (pClass.isAssignableFrom(pValue.getClass())) {
        return pValue;
    } else if (pValue instanceof String) {
        String str = (String) pValue;
        PropertyEditor pe = PropertyEditorManager.findEditor(pClass);
        if (pe == null) {
            if ("".equals(str)) {
                return null;
            } else {
                if (log.isErrorEnabled()) {
                    String message = MessageUtil.getMessageWithArgs(Constants.NO_PROPERTY_EDITOR, str,
                            pClass.getName());
                    log.error(message);
                    throw new ElException(message);
                }
                return null;
            }
        }
        try {
            pe.setAsText(str);
            return pe.getValue();
        } catch (IllegalArgumentException exc) {
            if ("".equals(str)) {
                return null;
            } else {
                if (log.isErrorEnabled()) {
                    String message = MessageUtil.getMessageWithArgs(Constants.PROPERTY_EDITOR_ERROR, pValue,
                            pClass.getName());
                    log.error(message, exc);
                    throw new ElException(message, exc);
                }
                return null;
            }
        }
    } else {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.COERCE_TO_OBJECT,
                    pValue.getClass().getName(), pClass.getName());
            log.error(message);
            throw new ElException(message);
        }
        return null;
    }
}

From source file:it.cilea.osd.jdyna.util.AnagraficaUtils.java

/**
 * Importa sull'oggetto anagraficaObject passato come parametro i dati
 * contenuti nell'importBean./*from w  ww .  j a v a 2s .  c  o  m*/
 * 
 * @param anagraficaObject
 *            - l'oggetto su cui importare i dati e metadati contenuti nel
 *            importBean passato come parametro
 * @param importBean
 *            {@see ImportPropertyAnagraficaUtil}
 * @return
 */
public <P extends Property<TP>, TP extends PropertiesDefinition, AV extends AValue> void importProprieta(
        AnagraficaSupport<P, TP> anagraficaObject, ImportPropertyAnagraficaUtil importBean) {

    String shortName = importBean.getShortname();
    Object oggetto = importBean.getValore();

    // recupero da db la tipologia di proprieta
    TP tipologiaDaImportare = (TP) applicationService
            .findPropertiesDefinitionByShortName(anagraficaObject.getClassPropertiesDefinition(), shortName);

    if (tipologiaDaImportare == null) {
        throw new IllegalArgumentException(
                "Lo shortname indicato: " + shortName + " non corrisponde a nessuna TP della classe "
                        + anagraficaObject.getClassPropertiesDefinition().getCanonicalName());
    }
    // recupero dal widget il property editor per l'import
    PropertyEditor pe = tipologiaDaImportare.getRendering().getImportPropertyEditor(applicationService);

    P proprieta = null;

    if (oggetto instanceof String) {
        pe.setAsText((String) oggetto);
        proprieta = anagraficaObject.createProprieta(tipologiaDaImportare);
        AV valore = (AV) proprieta.getValue();
        valore.setOggetto(pe.getValue());
        proprieta.setValue(valore);
    }

    if (oggetto instanceof List) {
        List lista = (List) oggetto;

        for (int w = 0; w < lista.size(); w++) {
            Object elementList = lista.get(w);

            if (elementList instanceof String) {
                proprieta = anagraficaObject.createProprieta(tipologiaDaImportare);
                pe.setAsText((String) elementList);
                AV valore = (AV) proprieta.getValue();
                valore.setOggetto(pe.getValue());
                // proprieta.setValore(valore);
            } else {
                // e' una combo...
                proprieta = anagraficaObject.createProprieta(tipologiaDaImportare);
                importSottoProprieta((AnagraficaObjectDTO) proprieta.getValue().getObject(),
                        (ImportPropertyAnagraficaUtil) elementList,
                        anagraficaObject.getClassPropertiesDefinition());
            }
        }

    }

}

From source file:it.cilea.osd.jdyna.util.AnagraficaUtils.java

/**
 * Metodo interno che importa i dati delle combo.
 * /*from  w  w  w  .j  a v  a 2s  . com*/
 * @param proprietaParent
 *            - la proprieta parent della combo
 * @param anagraficaObject
 * @param importBean
 */
private <P extends Property<TP>, TP extends PropertiesDefinition> void importSottoProprieta(
        AnagraficaObjectDTO anagraficaObject, ImportPropertyAnagraficaUtil importBean, Class<TP> clazzTP) {

    String shortName = importBean.getShortname();
    Object oggetto = importBean.getValore();

    TP tipologiaDaImportareInCombo = (TP) applicationService.findPropertiesDefinitionByShortName(clazzTP,
            shortName);
    PropertyEditor pe = tipologiaDaImportareInCombo.getRendering().getImportPropertyEditor(applicationService);

    P proprieta = null;

    // caso base
    if (oggetto instanceof String) {
        pe.setAsText((String) oggetto);
        ArrayList<ValoreDTO> arraylist;
        if (anagraficaObject.getAnagraficaProperties().get(tipologiaDaImportareInCombo).isEmpty()) {
            arraylist = new ArrayList<ValoreDTO>();
            arraylist.add(new ValoreDTO(pe.getValue()));
            anagraficaObject.getAnagraficaProperties().put(tipologiaDaImportareInCombo.getShortName(),
                    arraylist);
        } else {
            anagraficaObject.getAnagraficaProperties().get(tipologiaDaImportareInCombo)
                    .add(new ValoreDTO(pe.getValue()));
        }

        // proprieta.setValore(valore);
    }
    if (oggetto instanceof List) {
        List lista = (List) oggetto;

        for (int w = 0; w < lista.size(); w++) {

            pe.setAsText((String) oggetto);
            ArrayList<ValoreDTO> arraylist;
            if (anagraficaObject.getAnagraficaProperties().get(tipologiaDaImportareInCombo).isEmpty()) {
                arraylist = new ArrayList<ValoreDTO>();
                arraylist.add(new ValoreDTO(pe.getValue()));
                anagraficaObject.getAnagraficaProperties().put(tipologiaDaImportareInCombo.getShortName(),
                        arraylist);
            } else {
                anagraficaObject.getAnagraficaProperties().get(tipologiaDaImportareInCombo)
                        .add(new ValoreDTO(pe.getValue()));
            }
        }

    }
}

From source file:org.springmodules.cache.interceptor.flush.AbstractFlushingInterceptor.java

/**
 * @throws FatalCacheException/* w w w  . ja  v  a  2s . co m*/
 *           if the cache provider facade is <code>null</code>.
 * 
 * @see InitializingBean#afterPropertiesSet()
 * @see #onAfterPropertiesSet()
 */
public final void afterPropertiesSet() throws FatalCacheException {
    if (cacheProviderFacade == null) {
        throw new FatalCacheException("The cache provider facade should not be null");
    }

    if (flushingModels == null || flushingModels.isEmpty()) {
        return;
    }

    CacheModelValidator validator = cacheProviderFacade.modelValidator();

    if (flushingModels instanceof Properties) {
        PropertyEditor editor = cacheProviderFacade.getFlushingModelEditor();
        Properties properties = (Properties) flushingModels;
        Map newFlushingModels = new HashMap();

        String id = null;

        try {
            for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
                id = (String) i.next();

                String property = properties.getProperty(id);
                editor.setAsText(property);
                Object flushingModel = editor.getValue();
                validator.validateFlushingModel(flushingModel);

                newFlushingModels.put(id, flushingModel);
            }
        } catch (Exception exception) {
            throw new FatalCacheException(
                    "Unable to create the flushing model with id " + StringUtils.quote(id), exception);
        }

        setFlushingModels(newFlushingModels);

    } else {
        String id = null;

        try {
            for (Iterator i = flushingModels.keySet().iterator(); i.hasNext();) {
                id = (String) i.next();
                Object flushingModel = flushingModels.get(id);
                validator.validateFlushingModel(flushingModel);
            }
        } catch (Exception exception) {
            throw new FatalCacheException("Unable to validate flushing model with id " + StringUtils.quote(id),
                    exception);
        }
    }

    onAfterPropertiesSet();
}

From source file:com.sworddance.beans.PropertyAdaptor.java

/** @since 1.1 */
private Object convertValueForAssignment(Object target, String value) {
    if (value == null || getReturnType().isInstance(value)) {
        return value;
    }/*  w ww  .j a va 2  s  .  c  o  m*/

    PropertyEditor e = PropertyEditorManager.findEditor(getReturnType());

    if (e == null) {
        Object convertedValue = instantiateViaStringConstructor(value);

        if (convertedValue != null) {
            return convertedValue;
        }

        throw new ApplicationGeneralException("noPropertyEditor(" + propertyName + "+)" + target.getClass());
    }

    try {
        e.setAsText(value);

        return e.getValue();
    } catch (Exception ex) {
        throw new ApplicationGeneralException(
                "unableToConvert(" + value + ", " + getReturnType() + ", " + propertyName + ", " + target, ex);
    }
}

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

/**
 * Convert the given text value using the given property editor.
 * @param oldValue the previous value, if available (may be <code>null</code>)
 * @param newTextValue the proposed text value
 * @param editor the PropertyEditor to use
 * @return the converted value/* www . ja  va 2 s  . co m*/
 */
protected Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
    try {
        editor.setValue(oldValue);
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
                    ex);
        }
        // Swallow and proceed.
    }
    editor.setAsText(newTextValue);
    return editor.getValue();
}

From source file:org.hdiv.web.servlet.tags.form.SelectedValueComparatorHDIV.java

private static boolean exhaustiveCompare(Object boundValue, Object candidate, PropertyEditor editor,
        Map<PropertyEditor, Object> convertedValueCache) {

    String candidateDisplayString = ValueFormatterHDIV.getDisplayString(candidate, editor, false);
    if (boundValue instanceof LabeledEnum) {
        LabeledEnum labeledEnum = (LabeledEnum) boundValue;
        String enumCodeAsString = ObjectUtils.getDisplayString(labeledEnum.getCode());
        if (enumCodeAsString.equals(candidateDisplayString)) {
            return true;
        }//from   ww  w  .  ja  v  a2 s. com
        String enumLabelAsString = ObjectUtils.getDisplayString(labeledEnum.getLabel());
        if (enumLabelAsString.equals(candidateDisplayString)) {
            return true;
        }
    } else if (boundValue.getClass().isEnum()) {
        Enum boundEnum = (Enum) boundValue;
        String enumCodeAsString = ObjectUtils.getDisplayString(boundEnum.name());
        if (enumCodeAsString.equals(candidateDisplayString)) {
            return true;
        }
        String enumLabelAsString = ObjectUtils.getDisplayString(boundEnum.toString());
        if (enumLabelAsString.equals(candidateDisplayString)) {
            return true;
        }
    } else if (ObjectUtils.getDisplayString(boundValue).equals(candidateDisplayString)) {
        return true;
    } else if (editor != null && candidate instanceof String) {
        // Try PE-based comparison (PE should *not* be allowed to escape creating thread)
        String candidateAsString = (String) candidate;
        Object candidateAsValue;
        if (convertedValueCache != null && convertedValueCache.containsKey(editor)) {
            candidateAsValue = convertedValueCache.get(editor);
        } else {
            editor.setAsText(candidateAsString);
            candidateAsValue = editor.getValue();
            if (convertedValueCache != null) {
                convertedValueCache.put(editor, candidateAsValue);
            }
        }
        if (ObjectUtils.nullSafeEquals(boundValue, candidateAsValue)) {
            return true;
        }
    }
    return false;
}