Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public GeneratedMessage.Builder convertToProtobuf(Object obj) {
    GeneratedMessage.Builder builder;// w ww  . j  a v  a 2 s  . c  om

    if (obj.getClass().getName().equals(TUIO.TuioTime.class.getName())) {
        builder = TuioProtos.Time.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioCursor.class.getName())) {
        builder = TuioProtos.Cursor.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioObject.class.getName())) {
        builder = TuioProtos.Object.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioBlob.class.getName())) {
        builder = TuioProtos.Blob.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioPoint.class.getName())) {
        builder = TuioProtos.Point.newBuilder();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] objProps = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
        BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
        PropertyDescriptor[] builderProps = beanInfo.getPropertyDescriptors();
        Method[] methods = builder.getClass().getMethods();
        for (PropertyDescriptor prop1 : objProps) {
            for (PropertyDescriptor prop2 : builderProps) {
                if (prop1.getName().equals(prop2.getName())) {
                    Method readMethod = prop1.getReadMethod();
                    ArrayList<Method> methodsToTry = new ArrayList<>();
                    for (Method m : methods) {
                        if (m.getName().equals(readMethod.getName().replaceFirst("get", "set"))) {
                            methodsToTry.add(m);
                        }
                    }

                    for (Method setMethod : methodsToTry) {
                        try {
                            if (Iterable.class.isAssignableFrom(readMethod.getReturnType())) {
                                if (DeepCopy) {
                                    ArrayList<Method> methodsToTry2 = new ArrayList<>();
                                    for (Method m : methods) {
                                        if (m.getName()
                                                .equals(readMethod.getName().replaceFirst("get", "add"))) {
                                            methodsToTry2.add(m);
                                        }
                                    }

                                    boolean success = false;
                                    for (Method setMethod2 : methodsToTry2) {
                                        Iterable iter = (Iterable) readMethod.invoke(obj);
                                        Iterator it = iter.iterator();
                                        while (it.hasNext()) {
                                            Object o = it.next();
                                            //call set..
                                            for (ProtoConverter converter : services) {
                                                if (converter.supportsConversion(o)) {
                                                    try {
                                                        GeneratedMessage.Builder convertToProtobuf = converter
                                                                .convertToProtobuf(o);
                                                        setMethod2.invoke(builder, convertToProtobuf);
                                                        success = true;
                                                        break;
                                                    } catch (IllegalAccessException | IllegalArgumentException
                                                            | InvocationTargetException ex) {

                                                    }
                                                }
                                            }
                                        }
                                        if (success) {
                                            break;
                                        }
                                    }
                                }
                            } else {
                                boolean primitiveOrWrapper = ClassUtils
                                        .isPrimitiveOrWrapper(readMethod.getReturnType());

                                if (primitiveOrWrapper) {
                                    setMethod.invoke(builder, readMethod.invoke(obj));
                                } else {
                                    Object invoke = readMethod.invoke(obj);
                                    com.google.protobuf.GeneratedMessage.Builder val = convertToProtobuf(
                                            invoke);

                                    setMethod.invoke(builder, val);
                                    break;
                                }
                            }
                        } catch (IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException ex) {
                            //                            Logger.getLogger(TuioProtoConverter.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                }
            }
        }
    } catch (IntrospectionException ex) {
        logger.fatal(ex);
    }

    return builder;
}

From source file:org.ajax4jsf.templatecompiler.elements.vcp.FCallTemplateElement.java

public FCallTemplateElement(final Node element, final CompilationContext componentBean)
        throws CompilationException {
    super(element, componentBean);

    this.useOnlyEnumeratingParaments = false;

    NamedNodeMap nnm = element.getAttributes();
    Node functionNameNode = nnm.getNamedItem(FUNCTION_NAME_ATTRIBUTE_NAME);

    if (functionNameNode != null) {
        this.functionName = functionNameNode.getNodeValue();
    } else {// w ww. ja v a 2s .  co  m
        throw new CompilationException("function name is not set");
    }

    Node nodeUseOnlyThisParameters = nnm.getNamedItem(USE_ONLY_THIS_PARAMETERS);
    if (nodeUseOnlyThisParameters != null) {
        this.useOnlyEnumeratingParaments = Boolean.getBoolean(nodeUseOnlyThisParameters.getNodeValue());
    } // if

    // read name of variable if need
    Node variableName = nnm.getNamedItem(VAR_ATTRIBUTE_NAME);
    if (variableName != null) {
        this.variable = variableName.getNodeValue();
    } // if

    // read name of parameters if need
    ParameterProcessor parameterProcessor = new ParameterProcessor(element, componentBean);

    this.parameters = parameterProcessor.getParameters();
    log.debug(this.parameters);

    List decodeFunctionName = null;

    decodeFunctionName = Arrays.asList(this.functionName.split(FUNCTION_DELIMITER));
    if (null == decodeFunctionName) {
        decodeFunctionName = new ArrayList();
        decodeFunctionName.add(this.functionName);
    }

    ArrayList functionNames = new ArrayList();
    String lastClassName = componentBean.getFullBaseclass();

    for (Iterator iter = decodeFunctionName.iterator(); iter.hasNext();) {
        String elementFunction = (String) iter.next();

        try {
            log.debug("Try to load class : " + lastClassName);

            Class clazz = componentBean.loadClass(lastClassName);

            if (!iter.hasNext()) {
                String method = getMethod(clazz, elementFunction);
                if (method != null) {
                    log.debug(method);
                    functionNames.add(method);
                } else {
                    log.error("Method  " + elementFunction + " not found in class : " + lastClassName);
                    throw new CompilationException();
                }

            } else {
                //
                // Probing properties !!!!
                //

                PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, elementFunction);

                if (propertyDescriptor != null) {
                    functionNames.add(propertyDescriptor.getReadMethod().getName() + "()");
                    log.debug("Property " + elementFunction + " mapped to function  : "
                            + propertyDescriptor.getReadMethod().getName());
                    lastClassName = propertyDescriptor.getPropertyType().getName();
                } else {
                    log.error("Property " + elementFunction + " not found in class : " + lastClassName);
                    throw new CompilationException();
                }
            }

        } catch (Throwable e) {

            log.error("Error load class : " + lastClassName + ", " + e.getLocalizedMessage());
            e.printStackTrace();
            throw new CompilationException("Error load class : " + lastClassName, e);
        }

    }

    StringBuffer tmpbuf = new StringBuffer();
    for (Iterator iter = functionNames.iterator(); iter.hasNext();) {
        String tmpElement = (String) iter.next();
        if (tmpbuf.length() != 0) {
            tmpbuf.append(".");
        }
        tmpbuf.append(tmpElement);
    }
    this.fullFunctionName = tmpbuf.toString();

}

From source file:org.mule.modules.zuora.ZuoraModule.java

@MetaDataRetriever
public MetaData getMetadata(MetaDataKey key) throws Exception {

    Class<?> cls = getClassForType(key.getId());

    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(cls);

    Map<String, MetaDataModel> fieldMap = new HashMap<String, MetaDataModel>();
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
            fieldMap.put(pd.getName(), getFieldMetadata(pd.getPropertyType()));
        }//  w  w w.j a  v a  2  s.  com
    }

    DefaultDefinedMapMetaDataModel mapModel = new DefaultDefinedMapMetaDataModel(fieldMap, key.getId());

    return new DefaultMetaData(mapModel);
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.input.AbstractInputPresenter.java

@Override
public boolean isValid() {
    if (period != null) {

        try {//  w w w .j av  a2s .c o m
            ArrayList<String> wrongFields = new ArrayList<String>();
            boolean anyFalse = false;
            wrongFields.add(period.getYear() + "");
            for (PropertyDescriptor pdr : Introspector.getBeanInfo(period.getClass(), Object.class)
                    .getPropertyDescriptors()) {
                if (Arrays.asList(shownProperties)
                        .contains(pdr.getDisplayName().substring(0, pdr.getDisplayName().length() - 3))) {
                    if (!(boolean) pdr.getReadMethod().invoke(period)) {
                        wrongFields.add(pdr.getDisplayName().substring(0, pdr.getDisplayName().length() - 3));
                        anyFalse = true;
                    }
                }
            }
            if (anyFalse) {
                eventBus.fireEvent(new WrongFieldsEvent(wrongFields));
                return false;
            }
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    } else
        return false;
}

From source file:com.expressui.core.util.BeanPropertyType.java

private void initPropertyAnnotations() {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(containerType, id);
    if (descriptor != null) {
        Method method = descriptor.getReadMethod();
        if (method != null) {
            Annotation[] readMethodAnnotations = method.getAnnotations();
            Collections.addAll(annotations, readMethodAnnotations);
        }//from  ww  w . jav  a  2s  .com
    }
}

From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java

static List<ActionParameterType> findBeanInfo(final Class<?> beanType, final List<ActionParameterType> previous)
        throws IntrospectionException, NoSuchFieldException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

    // add input field for every setter
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String propertyName = propertyDescriptor.getName();

        if (isDefinedAlready(propertyName, previous)) {
            continue;
        }/*from   w ww  .j a  v a2 s. c  om*/
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        ActionParameterType type = null;
        if (writeMethod != null) {
            Field field = getFormAnnotated(propertyName, beanType);
            if (field != null) {
                type = new FieldParameterType(propertyName, field);
            } else {
                MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
                type = new MethodParameterType(propertyName, methodParameter,
                        propertyDescriptor.getReadMethod());
            }
        }
        if (type == null) {
            continue;
        }
        previous.add(type);
    }
    return previous;
}

From source file:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean/*  w  w  w .  jav a  2 s  . c o m*/
 * @param propertyName El nombre de la propiedad
 * @return El valor de la propiedad
 */
private Object getValueFromBean(Object obj, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
            }
        }

        if (readMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en " + obj.getClass().getName());
        }

        return readMethod.invoke(obj);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Add fields for each indexed/stored property.
 * /*from ww w. j  a v a 2 s . com*/
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param descriptor Property descriptor.
 * @param stack Stack containing parent field names.
 * @param inheritedBoost Inherited boost factor.
 * @return Document with additional fields.
 * @throws IndexingException
 */
private Document addBeanFields(final Document doc, final Searchable bean, final PropertyDescriptor descriptor,
        final Stack<String> stack, final float inheritedBoost) throws IndexingException {
    final Method readMethod = descriptor.getReadMethod();
    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        if (null != readMethod && AnnotationUtils.isAnnotationPresent(readMethod, annotationClass)) {

            // don't index elements marked as nested=false in a nested context
            if (!stack.isEmpty() && !isNested(descriptor)) {
                continue;
            }

            for (final String fieldname : SearchableUtils.getFieldnames(descriptor)) {
                log.debug("Indexing " + descriptor.getName() + " as " + getFieldname(fieldname, stack));

                try {
                    final Object prop = PropertyUtils.getProperty(bean, descriptor.getName());
                    if (null == prop)
                        continue;

                    addFields(doc, fieldname, prop, descriptor, stack, inheritedBoost);
                } catch (final IndexingException e) {
                    throw e;
                } catch (final Exception e) {
                    throw new IndexingException("Unable to index bean.", e);
                }
            }
        }
    }

    return doc;
}

From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java

private GraphQLFieldDefinition.Builder buildPrimitive(GraphQLFieldDefinition.Builder builder,
        PropertyDescriptor field, PhantasmProcessor processor) {
    builder.name(field.getName()).type((GraphQLOutputType) type(field, processor)).dataFetcher(env -> {
        Object record = env.getSource();
        try {// www .ja  va  2s  .  c o m
            return field.getReadMethod().invoke(record);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalStateException(
                    String.format("unable to invoke %s", field.getReadMethod().toGenericString()), e);
        }
    });
    return builder;
}

From source file:org.eclipse.wb.internal.core.xml.model.description.rules.CreatePropertiesPropertyDescriptorRule.java

private void addSingleProperty(ComponentDescription componentDescription, PropertyDescriptor propertyDescriptor)
        throws Exception {
    Method setMethod = propertyDescriptor.getWriteMethod();
    if (setMethod == null) {
        return;// ww w.j av a2s.  c o m
    }
    if (!ReflectionUtils.isPublic(setMethod)) {
        return;
    }
    // prepare description parts
    String title = propertyDescriptor.getName();
    String attribute = StringUtils.substringBeforeLast(StringUtils.uncapitalize(title), "(");
    Method getMethod = propertyDescriptor.getReadMethod();
    Class<?> propertyType = resolvePropertyType(componentDescription, setMethod);
    // prepare property parts
    String id = setMethod.getName() + "(" + ReflectionUtils.getFullyQualifiedName(propertyType, false) + ")";
    ExpressionAccessor accessor = new MethodExpressionAccessor(attribute, setMethod, getMethod);
    ExpressionConverter converter = DescriptionPropertiesHelper.getConverterForType(propertyType);
    PropertyEditor editor = DescriptionPropertiesHelper.getEditorForType(propertyType);
    // create property
    GenericPropertyDescription property = new GenericPropertyDescription(id, title, propertyType, accessor);
    property.setConverter(converter);
    property.setEditor(editor);
    // add property
    componentDescription.addProperty(property);
}