Example usage for java.beans PropertyDescriptor PropertyDescriptor

List of usage examples for java.beans PropertyDescriptor PropertyDescriptor

Introduction

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

Prototype

PropertyDescriptor(PropertyDescriptor x, PropertyDescriptor y) 

Source Link

Document

Package-private constructor.

Usage

From source file:org.apache.servicecomb.authentication.provider.AccessController.java

private boolean matchMicroserviceField(Microservice microservice, ConfigurationItem item) {
    Object fieldValue = null;/*from w  ww . j ava  2  s  .c o  m*/
    try {
        fieldValue = new PropertyDescriptor(item.propertyName, Microservice.class).getReadMethod()
                .invoke(microservice);
    } catch (Exception e) {
        LOG.warn("can't find propertyname: {} in microservice field, will search in microservice properties.",
                item.propertyName);
        return false;
    }
    if (fieldValue.getClass().getName().equals(String.class.getName()))
        return isPatternMatch((String) fieldValue, item.rule);
    return false;
}

From source file:com.webpagebytes.cms.engine.JSONToFromObjectConverter.java

public <T> T objectFromJSONString(String jsonString, Class<T> objClass) {
    try {/*from   ww w.j ava  2s.  co  m*/
        org.json.JSONObject json = new org.json.JSONObject(jsonString);
        T newObj = objClass.newInstance();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            Object storeAdn = field.getAnnotation(WPBAdminFieldStore.class);
            if (storeAdn == null) {
                storeAdn = field.getAnnotation(WPBAdminFieldKey.class);
                if (storeAdn == null) {
                    storeAdn = field.getAnnotation(WPBAdminFieldTextStore.class);
                    if (storeAdn == null) {
                        storeAdn = field.getAnnotation(WPBAdminField.class);
                    }
                }
            }

            if (storeAdn != null) {
                String fieldName = field.getName();
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(fieldName, objClass);
                    Object fieldValue = fieldFromJSON(json, fieldName, field.getType());
                    if (fieldValue != null) {
                        pd.getWriteMethod().invoke(newObj, fieldFromJSON(json, fieldName, field.getType()));
                    }
                } catch (Exception e) {
                    // do nothing, there is no write method for our field
                }
            }
        }

        return newObj;

    } catch (Exception e) {
        // do nothing
    }
    return null;

}

From source file:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void usePrimitivesArgumentCausesPrimitiveTypes() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("usePrimitives", true));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    assertThat(new PropertyDescriptor("a", generatedType).getReadMethod().getReturnType().getName(), is("int"));
    assertThat(new PropertyDescriptor("b", generatedType).getReadMethod().getReturnType().getName(),
            is("double"));
    assertThat(new PropertyDescriptor("c", generatedType).getReadMethod().getReturnType().getName(),
            is("boolean"));

}

From source file:org.openmrs.util.ReportingcompatibilityUtil.java

/**
 * Uses reflection to translate a PatientSearch into a PatientFilter
 *//*from  ww w.  ja v  a  2s .c  o  m*/
@SuppressWarnings("unchecked")
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
        EvaluationContext evalContext) {
    if (search.isSavedSearchReference()) {
        PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class)
                .getReportObject(search.getSavedSearchId())).getPatientSearch();
        return toPatientFilter(ps, history, evalContext);
    } else if (search.isSavedFilterReference()) {
        return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId());
    } else if (search.isSavedCohortReference()) {
        Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
        // to prevent lazy loading exceptions, cache the member ids here
        if (c != null) {
            c.getMemberIds().size();
        }
        return new CohortFilter(c);
    } else if (search.isComposition()) {
        if (history == null && search.requiresHistory()) {
            throw new IllegalArgumentException("You can't evaluate this search without a history");
        } else {
            return search.cloneCompositionAsFilter(history, evalContext);
        }
    } else {
        Class clz = search.getFilterClass();
        if (clz == null) {
            throw new IllegalArgumentException(
                    "search must be saved, composition, or must have a class specified");
        }
        log.debug("About to instantiate " + clz);
        PatientFilter pf = null;
        try {
            pf = (PatientFilter) clz.newInstance();
        } catch (Exception ex) {
            log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
            return null;
        }
        Class[] stringSingleton = { String.class };
        if (search.getArguments() != null) {
            for (SearchArgument sa : search.getArguments()) {
                if (log.isDebugEnabled()) {
                    log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> "
                            + sa.getValue());
                }
                PropertyDescriptor pd = null;
                try {
                    pd = new PropertyDescriptor(sa.getName(), clz);
                } catch (IntrospectionException ex) {
                    log.error("Error while examining property " + sa.getName(), ex);
                    continue;
                }
                Class<?> realPropertyType = pd.getPropertyType();

                // instantiate the value of the search argument
                String valueAsString = sa.getValue();
                String testForExpression = search.getArgumentValue(sa.getName());
                if (testForExpression != null) {
                    log.debug("Setting " + sa.getName() + " to: " + testForExpression);
                    if (evalContext != null && EvaluationContext.isExpression(testForExpression)) {
                        Object evaluated = evalContext.evaluateExpression(testForExpression);
                        if (evaluated != null) {
                            if (evaluated instanceof Date) {
                                valueAsString = Context.getDateFormat().format((Date) evaluated);
                            } else {
                                valueAsString = evaluated.toString();
                            }
                        }
                        log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
                    }
                }

                Object value = null;
                Class<?> valueClass = sa.getPropertyClass();
                try {
                    // If there's a valueOf(String) method, just use that
                    // (will cover at least String, Integer, Double,
                    // Boolean)
                    Method valueOfMethod = null;
                    try {
                        valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
                    } catch (NoSuchMethodException ex) {
                    }
                    if (valueOfMethod != null) {
                        Object[] holder = { valueAsString };
                        value = valueOfMethod.invoke(pf, holder);
                    } else if (realPropertyType.isEnum()) {
                        // Special-case for enum types
                        List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
                        for (Enum e : constants) {
                            if (e.toString().equals(valueAsString)) {
                                value = e;
                                break;
                            }
                        }
                    } else if (String.class.equals(valueClass)) {
                        value = valueAsString;
                    } else if (Location.class.equals(valueClass)) {
                        LocationEditor ed = new LocationEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Concept.class.equals(valueClass)) {
                        ConceptEditor ed = new ConceptEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Program.class.equals(valueClass)) {
                        ProgramEditor ed = new ProgramEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (ProgramWorkflowState.class.equals(valueClass)) {
                        ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (EncounterType.class.equals(valueClass)) {
                        EncounterTypeEditor ed = new EncounterTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Form.class.equals(valueClass)) {
                        FormEditor ed = new FormEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Drug.class.equals(valueClass)) {
                        DrugEditor ed = new DrugEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (PersonAttributeType.class.equals(valueClass)) {
                        PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Cohort.class.equals(valueClass)) {
                        CohortEditor ed = new CohortEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Date.class.equals(valueClass)) {
                        // TODO: this uses the date format from the current
                        // session, which could cause problems if the user
                        // changes it after searching.
                        DateFormat df = Context.getDateFormat(); // new
                        // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()),
                        // Context.getLocale());
                        CustomDateEditor ed = new CustomDateEditor(df, true, 10);
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (LogicCriteria.class.equals(valueClass)) {
                        value = Context.getLogicService().parseString(valueAsString);
                    } else {
                        // TODO: Decide whether this is a hack. Currently
                        // setting Object arguments with a String
                        value = valueAsString;
                    }
                } catch (Exception ex) {
                    log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
                    continue;
                }

                if (value != null) {

                    if (realPropertyType.isAssignableFrom(valueClass)) {
                        log.debug("setting value of " + sa.getName() + " to " + value);
                        try {
                            pd.getWriteMethod().invoke(pf, value);
                        } catch (Exception ex) {
                            log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> "
                                    + value, ex);
                            continue;
                        }
                    } else if (Collection.class.isAssignableFrom(realPropertyType)) {
                        log.debug(sa.getName() + " is a Collection property");
                        // if realPropertyType is a collection, add this
                        // value to it (possibly after instantiating)
                        try {
                            Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
                            if (collection == null) {
                                // we need to instantiate this collection.
                                // I'm going with the following rules, which
                                // should be rethought:
                                // SortedSet -> TreeSet
                                // Set -> HashSet
                                // Otherwise -> ArrayList
                                if (SortedSet.class.isAssignableFrom(realPropertyType)) {
                                    collection = new TreeSet();
                                    log.debug("instantiated a TreeSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else if (Set.class.isAssignableFrom(realPropertyType)) {
                                    collection = new HashSet();
                                    log.debug("instantiated a HashSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else {
                                    collection = new ArrayList();
                                    log.debug("instantiated an ArrayList");
                                    pd.getWriteMethod().invoke(pf, collection);
                                }
                            }
                            collection.add(value);
                        } catch (Exception ex) {
                            log.error("Error instantiating collection for property " + sa.getName()
                                    + " whose class is " + realPropertyType, ex);
                            continue;
                        }
                    } else {
                        log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
                                + " but is given as " + valueClass);
                    }
                }
            }
        }
        log.debug("Returning " + pf);
        return pf;
    }
}

From source file:org.ivan.service.ExcelExporter.java

public <T extends Object> List<String> getValuesRecursive(T obj) {

    List<String> fieldNames = getHeaders(obj.getClass());
    PropertyDescriptor propertyDescriptor;//Use for getters and setters from property
    Method currentGetMethod;//Current get method from current property
    List<String> values = new ArrayList<>();
    for (String fieldName : fieldNames) {
        try {/* w  ww .j a  v a2 s  .  co m*/
            propertyDescriptor = new PropertyDescriptor(fieldName, obj.getClass());//property (fieldName) from class (classDefinition)
            currentGetMethod = propertyDescriptor.getReadMethod();//gets the definition of the get method

            if (currentGetMethod.invoke(obj).toString().contains("=")) {//obj.get<Parameter>
                values.addAll(getValuesRecursive(currentGetMethod.invoke(obj)));//Gets all values from getters
            } else {
                values.add(currentGetMethod.invoke(obj).toString());//if its only 1 value
            }

        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            Logger.getLogger(ExcelExporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return values;
}

From source file:eu.planets_project.pp.plato.util.jsf.SelectableItemConverter.java

protected String getItemIdentifier(Object o, String property) {
    PropertyDescriptor desc;/*from   w  ww. j a v a2 s. c o m*/
    Object result;

    try {
        desc = new PropertyDescriptor(property, o.getClass());
        result = desc.getReadMethod().invoke(o);

        return result.toString();
    } catch (Throwable e) {
        log.error("Unable to get object identifier!", e);
    }

    return null;
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public Object getObjectProperty(Object object, String property) throws WPBSerializerException {
    try {//  w  ww  .j a  v  a 2s . c  o m
        PropertyDescriptor pd = new PropertyDescriptor(property, object.getClass());
        return pd.getReadMethod().invoke(object);
    } catch (Exception e) {
        throw new WPBSerializerException("Cannot set property for object", e);
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.FormatIT.java

@Test
public void valueCanBeSerializedAndDeserialized() throws NoSuchMethodException, IOException,
        IntrospectionException, IllegalAccessException, InvocationTargetException {

    ObjectMapper objectMapper = new ObjectMapper();

    ObjectNode node = objectMapper.createObjectNode();
    node.put(propertyName, jsonValue.toString());

    Object pojo = objectMapper.treeToValue(node, classWithFormattedProperties);

    Method getter = new PropertyDescriptor(propertyName, classWithFormattedProperties).getReadMethod();

    assertThat(getter.invoke(pojo).toString(), is(equalTo(javaValue.toString())));

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    assertThat(jsonVersion.get(propertyName).asText(), is(equalTo(jsonValue.toString())));

}

From source file:org.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void usePrimitivesArgumentCausesPrimitiveTypes() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("usePrimitives", true));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    assertThat(new PropertyDescriptor("a", generatedType).getReadMethod().getReturnType().getName(), is("int"));
    assertThat(new PropertyDescriptor("b", generatedType).getReadMethod().getReturnType().getName(),
            is("double"));
    assertThat(new PropertyDescriptor("c", generatedType).getReadMethod().getReturnType().getName(),
            is("boolean"));

}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public <T> boolean hasClassProperty(Class<T> kind, String property) throws WPBSerializerException {
    try {/*from  www.  ja  va2s. co m*/
        PropertyDescriptor pd = new PropertyDescriptor(property, kind);
        return pd.getReadMethod() != null;
    } catch (Exception e) {
        throw new WPBSerializerException("Cannot set property for object", e);
    }
}