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:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java

@Override
public PageResults<E> queryPage(PageParams<E> pageParams) {
    if (pageParams == null) {
        throw new IllegalArgumentException("?null");
    }/*from w w  w  . j a v  a 2  s.  c o  m*/
    LOGGER.trace("...");

    // ??
    int pageNum = pageParams.getPageIndex();
    int pageSize = pageParams.getPageSize();
    if (pageSize > 100) {
        LOGGER.warn(", ?[{}] ?, ? 100 ?", pageSize);
        pageSize = 100;
    }

    // ?
    PageHelper.startPage(pageNum, pageSize);

    Example example = new Example(entityClass);
    // ??
    E params = pageParams.getParamEntity();
    if (params != null) {
        Example.Criteria criteria = example.createCriteria();
        PropertyDescriptor[] propArray = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor pd : propArray) {
            if (pd.getPropertyType().equals(Class.class)) {
                continue;
            }
            try {
                Object value = pd.getReadMethod().invoke(params);
                if (value != null) {
                    if (pd.getPropertyType() == String.class) {
                        String strValue = (String) value;
                        if (strValue.startsWith("%") || strValue.endsWith("%")) {
                            criteria.andLike(pd.getName(), strValue);
                            continue;
                        }
                    }
                    criteria.andEqualTo(pd.getName(), value);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOGGER.error("example: {}", e.getMessage(), e);
            }
        }
    }
    // ??
    String orderBy = pageParams.getOrderBy();
    if (StringUtils.hasText(orderBy)) {
        processOrder(example, orderBy, pageParams.isAsc());
    }
    List<E> results = baseMapper.selectByExample(example);

    // 
    if (results == null || !(results instanceof Page)) {
        return new PageResults<>(0, new ArrayList<E>(0), pageParams);
    }
    Page page = (Page) results;
    Long totalCount = page.getTotal();
    return new PageResults<>(totalCount.intValue(), Collections.unmodifiableList(results), pageParams);
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * Java 8 uses "MethodRef" that uses {@link SoftReference} to a {@link Method}. But this means
 * that when it looses a reference to a <em>protected</em> {@link Method}, it cannot restore it. I
 * wish we had done it differently, not by using {@link PropertyDescriptor}.
 *///from  w w w . ja  v  a 2  s. com
public static Method getReadMethod(PropertyDescriptor propertyDescriptor) {
    try {
        return propertyDescriptor.getReadMethod();
    } catch (Throwable e) {
        return null;
    }
}

From source file:com.turbospaces.model.BO.java

/**
 * create business object over actual basic persistent entity
 * //w  w  w  .j a va 2s  .co  m
 * @param delegate
 *            the actual persistent entity meta-data provider
 * @throws NoSuchMethodException
 *             re-throw cglib exception
 * @throws SecurityException
 *             re-throw cglib exception
 * @throws IntrospectionException
 *             re-throw exceptions
 */
public BO(final BasicPersistentEntity delegate)
        throws SecurityException, NoSuchMethodException, IntrospectionException {
    this.delegate = delegate;
    this.fastConstructor = FastClass.create(delegate.getType())
            .getConstructor(delegate.getType().getConstructor());

    // find optimistic lock version/routing fields
    {
        final Collection<PersistentProperty> versionCandidates = Lists.newLinkedList();
        final Collection<PersistentProperty> routingCandidates = Lists.newLinkedList();
        delegate.doWithProperties(new PropertyHandler() {
            @Override
            public void doWithPersistentProperty(final PersistentProperty persistentProperty) {
                PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor();
                Field field = persistentProperty.getField();

                if (hasAnnotation(propertyDescriptor, field, Version.class))
                    versionCandidates.add(persistentProperty);
                if (hasAnnotation(propertyDescriptor, field, Routing.class))
                    routingCandidates.add(persistentProperty);
            }

            private boolean hasAnnotation(final PropertyDescriptor descriptor, final Field field,
                    final Class annotation) {
                if (descriptor != null && descriptor.getReadMethod() != null
                        && descriptor.getReadMethod().getAnnotation(annotation) != null)
                    return true;
                if (field != null && field.getAnnotation(annotation) != null)
                    return true;
                return false;
            }
        });
        Preconditions.checkArgument(versionCandidates.size() <= 1,
                "too many fields marked with @Version annotation, candidates = "
                        + versionCandidates.toString());
        Preconditions.checkArgument(routingCandidates.size() <= 1,
                "too many fields marked with @Routing annotation, candidates = "
                        + routingCandidates.toString());

        if (!versionCandidates.isEmpty())
            optimisticLockVersionProperty = versionCandidates.iterator().next();
        if (!routingCandidates.isEmpty())
            routingProperty = routingCandidates.iterator().next();
    }

    {
        // Java Beans convention marker
        AtomicBoolean propertyAccess = new AtomicBoolean(true);

        List<String> setters = Lists.newLinkedList();
        List<String> getters = Lists.newLinkedList();
        List<Class<?>> types = Lists.newLinkedList();

        for (PersistentProperty<?> persistentProperty : getOrderedProperties()) {
            PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor();
            if (propertyDescriptor != null) {
                if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
                    setters.add(propertyDescriptor.getWriteMethod().getName());
                    getters.add(propertyDescriptor.getReadMethod().getName());
                    types.add(persistentProperty.getType());
                }
            } else {
                propertyAccess.set(false);
                brokenProperties.add(persistentProperty);
            }
        }

        if (propertyAccess.get())
            // create properties extract for all persistent properties
            bulkBean = BulkBean.create(delegate.getType(), getters.toArray(new String[getters.size()]),
                    setters.toArray(new String[setters.size()]), types.toArray(new Class[types.size()]));
        else
            Log.warn(String.format(
                    "PropetiesSerializer-%s unable to use getters-setters access optimization. Suspected/Corrupted properties = %s",
                    delegate.getType().getSimpleName(), getBrokenProperties()));

        boolean canOptimizeIdProperty = hasReadWriteMethods(delegate.getIdProperty());
        boolean canOptimizeVersionProperty = hasReadWriteMethods(getOptimisticLockVersionProperty());
        boolean canOptimizeRoutingProperty = hasReadWriteMethods(getRoutingProperty());

        // create id/version/routing bulk fields extractor
        if (canOptimizeIdProperty && canOptimizeVersionProperty && canOptimizeRoutingProperty) {
            String[] g = new String[] {
                    delegate.getIdProperty().getPropertyDescriptor().getReadMethod().getName(),
                    getOptimisticLockVersionProperty().getPropertyDescriptor().getReadMethod().getName(),
                    getRoutingProperty().getPropertyDescriptor().getReadMethod().getName() };
            String[] s = new String[] {
                    delegate.getIdProperty().getPropertyDescriptor().getWriteMethod().getName(),
                    getOptimisticLockVersionProperty().getPropertyDescriptor().getWriteMethod().getName(),
                    getRoutingProperty().getPropertyDescriptor().getWriteMethod().getName() };
            Class<?>[] c = new Class[] { delegate.getIdProperty().getType(),
                    getOptimisticLockVersionProperty().getType(), getRoutingProperty().getType() };

            idVersionRoutingBulkBean = BulkBean.create(delegate.getType(), g, s, c);
        }
    }
}

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 {/*from  ww w  .  j av a  2s  .  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:org.getobjects.foundation.kvc.KVCWrapper.java

/**
 *  Uses JavaBeans introspection to find all the properties of the
 *  bean class.  This method sets the {@link #accessors} variable (it will
 *  have been null), and adds all the well-defined JavaBeans properties.
 *
 *  <p>Subclasses may invoke this method before adding thier own accessors.
 *
 *  <p>This method is invoked from within a synchronized block.  Subclasses
 *  do not have to worry about synchronization.
 **//* w  w  w . j a  v  a 2s. co m*/

protected void buildPropertyAccessors() {
    /*
     * Acquire all usable field accessors first.
     */

    if (this.accessors != null)
        return;

    /**
     * Construct field accessors for names which aren't occupied
     * by properties, yet. Imagine this as a "last resort".
     */

    final Map<String, FieldAccessor> propertyFieldAccessorMap = new HashMap<String, FieldAccessor>();
    final Field fields[] = this.clazz.getFields();

    for (Field field : fields) {
        final int mods = field.getModifiers();

        // Skip static variables and non-public instance variables.
        if ((Modifier.isPublic(mods) == false) || (Modifier.isStatic(mods)))
            continue;

        propertyFieldAccessorMap.put(field.getName(), new FieldAccessor(field));
    }

    /**
     * Retrieve all property descriptors now
     */
    PropertyDescriptor[] props;

    try {
        props = this.getPropertyDescriptors(this.clazz);
    } catch (Exception e) {
        logger.error("Error during getPropertyDescriptors()", e);
        throw new DynamicInvocationException(e);
    }

    // TBD: instead build the table locally, and then apply to an
    //      atomic reference?!
    this.accessors = new ConcurrentHashMap<String, IPropertyAccessor>(16);

    if (logger.isDebugEnabled())
        logger.debug("Recording properties for \"" + this.clazz.getName() + "\"");

    for (PropertyDescriptor pd : props) {
        final String name = pd.getName();

        if (logger.isDebugEnabled())
            logger.debug("Recording property \"" + name + "\"");

        final Method getter = pd.getReadMethod();
        final Method setter = pd.getWriteMethod();
        final FieldAccessor fa = propertyFieldAccessorMap.get(name);
        final Class type = pd.getPropertyType();

        final PropertyAccessor pa = PropertyAccessor.getPropertyAccessor(name, type, getter, setter, fa);
        this.accessors.put(name, pa);
    }

    /**
     * Use field accessors for names which are not occupied, yet.
     * This is the default fallback.
     */
    for (String name : propertyFieldAccessorMap.keySet()) {
        if (!this.accessors.containsKey(name))
            this.accessors.put(name, propertyFieldAccessorMap.get(name));
    }
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

/**
 *  Checks to see that that class either doesn't provide the property, or does
 *  but the accessor(s) are abstract.  Returns the name of the read accessor,
 *  or null if there is no such accessor (this is helpful if the beanClass
 *  defines a boolean property, where the name of the accessor may be isXXX or
 *  getXXX).//from  www.ja  v a  2s  .  c o m
 * 
 **/

protected String checkAccessors(String propertyName, Class propertyType, ILocation location) {
    PropertyDescriptor d = getPropertyDescriptor(propertyName);

    if (d == null)
        return null;

    checkPropertyType(d, propertyType, location);

    Method write = d.getWriteMethod();
    Method read = d.getReadMethod();

    if (isImplemented(write))
        throw new ApplicationRuntimeException(Tapestry.format("ComponentClassFactory.non-abstract-write",
                write.getDeclaringClass().getName(), propertyName), location, null);

    if (isImplemented(read))
        throw new ApplicationRuntimeException(Tapestry.format("ComponentClassFactory.non-abstract-read",
                read.getDeclaringClass().getName(), propertyName), location, null);

    return read == null ? null : read.getName();
}

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

protected GraphQLFieldDefinition.Builder buildReference(GraphQLFieldDefinition.Builder builder,
        PropertyDescriptor field, PhantasmProcessor processor, Class<?> reference) {
    GraphQLOutputType type = (GraphQLOutputType) processor.typeFor(Existential.class);
    builder.name(field.getName()).type(type).dataFetcher(env -> {
        Object record = env.getSource();
        UUID fk;/*from   www  . j  a v a2  s . c o m*/
        try {
            fk = (UUID) field.getReadMethod().invoke(record);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalStateException(
                    String.format("unable to invoke %s", field.getReadMethod().toGenericString()), e);
        }
        return Existential.wrap(Existential.resolve(env, fk));
    });
    return builder;
}

From source file:org.obiba.onyx.jade.instrument.gemac800.CardiosoftInstrumentRunner.java

/**
 * Place the results and xml file into a map object to send them to the server for persistence
 *
 * @param resultParser/*from   w w w. j a v  a 2s .c om*/
 * @throws Exception
 */
public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) {
    Map<String, Data> outputToSend = new HashMap<String, Data>();

    try {
        for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class)
                .getPropertyDescriptors()) {
            if (instrumentExecutionService.hasOutputParameter(pd.getName())) {
                Object value = pd.getReadMethod().invoke(resultParser);
                if (value != null) {
                    if (value instanceof Long) {

                        // We need to subtract one to the birthday month since the month of January is represented by "0" in
                        // java.util.Calendar (January is represented by "1" in Cardiosoft).
                        if (pd.getName().equals("participantBirthMonth")) {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1));
                        } else {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value));
                        }

                    } else if (value instanceof Double) {
                        outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value));
                    } else {
                        outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString()));
                    }
                } else { // send null values as well (ONYX-585)
                    log.info("Output parameter " + pd.getName() + " was null; will send null to server");

                    if (pd.getPropertyType().isAssignableFrom(Long.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type INTEGER");
                        outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null));
                    } else if (pd.getPropertyType().isAssignableFrom(Double.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type DECIMAL");
                        outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null));
                    } else {
                        log.info("Output parameter " + pd.getName() + " is of type TEXT");
                        outputToSend.put(pd.getName(), new Data(DataType.TEXT, null));
                    }
                }
            }
        }

        // Save the xml and pdf files
        File xmlFile = new File(getExportPath(), getXmlFileName());
        outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile));

        instrumentExecutionService.addOutputParameterValues(outputToSend);

    } catch (Exception e) {
        log.debug("Sending data to server failed.", e);
        throw new RuntimeException(e);
    }
}

From source file:net.solarnetwork.web.support.SimpleCsvView.java

private List<String> getCSVFields(Object row, final Collection<String> fieldOrder) {
    assert row != null;
    List<String> result = new ArrayList<String>();
    if (row instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) row;
        if (fieldOrder != null) {
            for (String key : fieldOrder) {
                result.add(key);/* w  w w.j ava2  s. com*/
            }
        } else {
            for (Object key : map.keySet()) {
                result.add(key.toString());
            }
        }
    } else {
        // use bean properties
        if (getPropertySerializerRegistrar() != null) {
            // try whole-bean serialization first
            Object o = getPropertySerializerRegistrar().serializeProperty("row", row.getClass(), row, row);
            if (o != row) {
                if (o != null) {
                    result = getCSVFields(o, fieldOrder);
                    return result;
                }
            }
        }
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
        PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
        Set<String> resultSet = new LinkedHashSet<String>();
        for (PropertyDescriptor prop : props) {
            String name = prop.getName();
            if (getJavaBeanIgnoreProperties() != null && getJavaBeanIgnoreProperties().contains(name)) {
                continue;
            }
            if (wrapper.isReadableProperty(name)) {
                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }
                resultSet.add(name);
            }
        }
        if (fieldOrder != null && fieldOrder.size() > 0) {
            for (String key : fieldOrder) {
                if (resultSet.contains(key)) {
                    result.add(key);
                }
            }
        } else {
            result.addAll(resultSet);
        }

    }
    return result;
}

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler.//from  w  w w.j  a  va 2s .  c o  m
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}