Search in sources :

Example 81 with BeanInfo

use of java.beans.BeanInfo in project fabric8 by fabric8io.

the class ProjectConfigs method configureProperties.

/**
 * Configures the given {@link ProjectConfig} with a map of key value pairs from
 * something like a JBoss Forge command
 */
public static void configureProperties(ProjectConfig config, Map map) {
    Class<? extends ProjectConfig> clazz = config.getClass();
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        LOG.warn("Could not introspect " + clazz.getName() + ". " + e, e);
    }
    if (beanInfo != null) {
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            Method writeMethod = descriptor.getWriteMethod();
            if (writeMethod != null) {
                String name = descriptor.getName();
                Object value = map.get(name);
                if (value != null) {
                    Object safeValue = null;
                    Class<?> propertyType = descriptor.getPropertyType();
                    if (propertyType.isInstance(value)) {
                        safeValue = value;
                    } else {
                        PropertyEditor editor = descriptor.createPropertyEditor(config);
                        if (editor == null) {
                            editor = PropertyEditorManager.findEditor(propertyType);
                        }
                        if (editor != null) {
                            String text = value.toString();
                            editor.setAsText(text);
                            safeValue = editor.getValue();
                        } else {
                            LOG.warn("Cannot update property " + name + " with value " + value + " of type " + propertyType.getName() + " on " + clazz.getName());
                        }
                    }
                    if (safeValue != null) {
                        try {
                            writeMethod.invoke(config, safeValue);
                        } catch (Exception e) {
                            LOG.warn("Failed to set property " + name + " with value " + value + " on " + clazz.getName() + " " + config + ". " + e, e);
                        }
                    }
                }
            }
        }
    }
    String flow = null;
    Object flowValue = map.get("pipeline");
    if (flowValue == null) {
        flowValue = map.get("flow");
    }
    if (flowValue != null) {
        flow = flowValue.toString();
    }
    config.setPipeline(flow);
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) PropertyEditor(java.beans.PropertyEditor) Method(java.lang.reflect.Method) MalformedURLException(java.net.MalformedURLException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) IntrospectionException(java.beans.IntrospectionException)

Example 82 with BeanInfo

use of java.beans.BeanInfo in project freemarker by apache.

the class BeansWrapperReadOnlyTest method checkAllPropertiesReadOnly.

private void checkAllPropertiesReadOnly(Object o) throws Exception {
    BeanInfo bi = Introspector.getBeanInfo(o.getClass());
    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        Method setter = pd.getWriteMethod();
        if (setter != null) {
            Class t = pd.getPropertyType();
            Object val;
            if (ClassUtil.isNumerical(t)) {
                val = Byte.valueOf((byte) 1);
            } else if (t == boolean.class) {
                val = Boolean.TRUE;
            } else if (t == char.class) {
                val = Character.valueOf('c');
            } else if (t.isAssignableFrom(String.class)) {
                val = "s";
            } else {
                val = null;
            }
            try {
                setter.invoke(o, val);
                fail("This setter should have failed as the property should be read-only now: " + setter);
            } catch (InvocationTargetException e) {
                Throwable target = e.getTargetException();
                if (!(target instanceof IllegalStateException && target.getMessage() != null && target.getMessage().contains(EXPECTED_MESSAGE_PART))) {
                    fail("Expected IllegalStateException with message containing \"" + EXPECTED_MESSAGE_PART + "\", got this instead: " + target);
                }
            }
        }
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 83 with BeanInfo

use of java.beans.BeanInfo in project freemarker by apache.

the class ClassIntrospector method addBeanInfoToClassIntrospectionData.

private void addBeanInfoToClassIntrospectionData(Map<Object, Object> introspData, Class<?> clazz, Map<MethodSignature, List<Method>> accessibleMethods) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    List<PropertyDescriptor> pdas = getPropertyDescriptors(beanInfo, clazz);
    int pdasLength = pdas.size();
    // Reverse order shouldn't mater, but we keep it to not risk backward incompatibility.
    for (int i = pdasLength - 1; i >= 0; --i) {
        addPropertyDescriptorToClassIntrospectionData(introspData, pdas.get(i), clazz, accessibleMethods);
    }
    if (exposureLevel < BeansWrapper.EXPOSE_PROPERTIES_ONLY) {
        final MethodAppearanceDecision decision = new MethodAppearanceDecision();
        MethodAppearanceDecisionInput decisionInput = null;
        List<MethodDescriptor> mds = getMethodDescriptors(beanInfo, clazz);
        sortMethodDescriptors(mds);
        int mdsSize = mds.size();
        IdentityHashMap<Method, Void> argTypesUsedByIndexerPropReaders = null;
        for (int i = mdsSize - 1; i >= 0; --i) {
            final Method method = getMatchingAccessibleMethod(mds.get(i).getMethod(), accessibleMethods);
            if (method != null && isAllowedToExpose(method)) {
                decision.setDefaults(method);
                if (methodAppearanceFineTuner != null) {
                    if (decisionInput == null) {
                        decisionInput = new MethodAppearanceDecisionInput();
                    }
                    decisionInput.setContainingClass(clazz);
                    decisionInput.setMethod(method);
                    methodAppearanceFineTuner.process(decisionInput, decision);
                }
                PropertyDescriptor propDesc = decision.getExposeAsProperty();
                if (propDesc != null && (decision.getReplaceExistingProperty() || !(introspData.get(propDesc.getName()) instanceof FastPropertyDescriptor))) {
                    addPropertyDescriptorToClassIntrospectionData(introspData, propDesc, clazz, accessibleMethods);
                }
                String methodKey = decision.getExposeMethodAs();
                if (methodKey != null) {
                    Object previous = introspData.get(methodKey);
                    if (previous instanceof Method) {
                        // Overloaded method - replace Method with a OverloadedMethods
                        OverloadedMethods overloadedMethods = new OverloadedMethods(bugfixed);
                        overloadedMethods.addMethod((Method) previous);
                        overloadedMethods.addMethod(method);
                        introspData.put(methodKey, overloadedMethods);
                        // Remove parameter type information (unless an indexed property reader needs it):
                        if (argTypesUsedByIndexerPropReaders == null || !argTypesUsedByIndexerPropReaders.containsKey(previous)) {
                            getArgTypesByMethod(introspData).remove(previous);
                        }
                    } else if (previous instanceof OverloadedMethods) {
                        // Already overloaded method - add new overload
                        ((OverloadedMethods) previous).addMethod(method);
                    } else if (decision.getMethodShadowsProperty() || !(previous instanceof FastPropertyDescriptor)) {
                        // Simple method (this far)
                        introspData.put(methodKey, method);
                        Class<?>[] replaced = getArgTypesByMethod(introspData).put(method, method.getParameterTypes());
                        if (replaced != null) {
                            if (argTypesUsedByIndexerPropReaders == null) {
                                argTypesUsedByIndexerPropReaders = new IdentityHashMap<Method, Void>();
                            }
                            argTypesUsedByIndexerPropReaders.put(method, null);
                        }
                    }
                }
            }
        }
    // for each in mds
    }
// end if (exposureLevel < EXPOSE_PROPERTIES_ONLY)
}
Also used : MethodAppearanceDecisionInput(freemarker.ext.beans.BeansWrapper.MethodAppearanceDecisionInput) IndexedPropertyDescriptor(java.beans.IndexedPropertyDescriptor) PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) MethodAppearanceDecision(freemarker.ext.beans.BeansWrapper.MethodAppearanceDecision) MethodDescriptor(java.beans.MethodDescriptor)

Example 84 with BeanInfo

use of java.beans.BeanInfo in project WorldPainter by Captain-Chaos.

the class HeightMapPropertiesPanel method addField.

private void addField(String name, Object bean, String propertyName, Number min, Number max, String text) {
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.anchor = GridBagConstraints.NORTHWEST;
    constraints.insets = new Insets(2, 2, 2, 2);
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.anchor = GridBagConstraints.BASELINE_LEADING;
    JLabel label = new JLabel(name);
    add(label, constraints);
    if (text != null) {
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.weightx = 1.0;
        JLabel valueLabel = new JLabel();
        valueLabel.setText(text);
        add(valueLabel, constraints);
        return;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            if (propertyDescriptor.getName().equalsIgnoreCase(propertyName)) {
                constraints.gridwidth = GridBagConstraints.REMAINDER;
                constraints.weightx = 1.0;
                if (propertyDescriptor.getWriteMethod() == null) {
                    JLabel valueLabel = new JLabel();
                    Object value = propertyDescriptor.getReadMethod().invoke(bean);
                    if (value != null) {
                        valueLabel.setText(value.toString());
                    }
                    add(valueLabel, constraints);
                    return;
                }
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                if (propertyType == String.class) {
                    JTextField field = new JTextField();
                    field.setText((String) propertyDescriptor.getReadMethod().invoke(bean));
                    field.getDocument().addDocumentListener(new DocumentListener() {

                        @Override
                        public void insertUpdate(DocumentEvent event) {
                            updateProperty();
                        }

                        @Override
                        public void removeUpdate(DocumentEvent event) {
                            updateProperty();
                        }

                        @Override
                        public void changedUpdate(DocumentEvent event) {
                            updateProperty();
                        }

                        private void updateProperty() {
                            try {
                                propertyDescriptor.getWriteMethod().invoke(bean, field.getText());
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                throw new RuntimeException(e);
                            }
                            updateListener(propertyName);
                        }
                    });
                    add(field, constraints);
                } else if ((propertyType == boolean.class) || (propertyType == Boolean.class)) {
                    JCheckBox checkBox = new JCheckBox(" ");
                    checkBox.setSelected(Boolean.TRUE.equals(propertyDescriptor.getReadMethod().invoke(bean)));
                    checkBox.addActionListener(event -> {
                        try {
                            propertyDescriptor.getWriteMethod().invoke(bean, checkBox.isSelected());
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            throw new RuntimeException(e);
                        }
                        updateListener(propertyName);
                    });
                    add(checkBox, constraints);
                } else if ((Number.class.isAssignableFrom(propertyType)) || (propertyType.isPrimitive() && (propertyType != boolean.class) && (propertyType != char.class))) {
                    JSpinner spinner = new JSpinner(new SpinnerNumberModel((Number) propertyDescriptor.getReadMethod().invoke(bean), (Comparable) min, (Comparable) max, 1));
                    spinner.addChangeListener(event -> {
                        try {
                            propertyDescriptor.getWriteMethod().invoke(bean, spinner.getValue());
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            throw new RuntimeException(e);
                        }
                        updateListener(propertyName);
                    });
                    add(spinner, constraints);
                } else {
                    throw new IllegalArgumentException("Property " + propertyName + " of type " + propertyType.getSimpleName() + " not supported");
                }
                return;
            }
        }
        throw new IllegalArgumentException("Bean of type " + bean.getClass().getSimpleName() + " has no property named " + propertyName);
    } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
Also used : org.pepsoft.worldpainter.heightMaps(org.pepsoft.worldpainter.heightMaps) java.awt(java.awt) Introspector(java.beans.Introspector) DocumentListener(javax.swing.event.DocumentListener) BufferedImage(java.awt.image.BufferedImage) PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) DocumentEvent(javax.swing.event.DocumentEvent) HeightMap(org.pepsoft.worldpainter.HeightMap) javax.swing(javax.swing) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DocumentListener(javax.swing.event.DocumentListener) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) PropertyDescriptor(java.beans.PropertyDescriptor) DocumentEvent(javax.swing.event.DocumentEvent) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 85 with BeanInfo

use of java.beans.BeanInfo in project thymeleaf by thymeleaf.

the class OGNLShortcutExpression method getObjectProperty.

private static Object getObjectProperty(final ICache<ExpressionCacheKey, Object> expressionCache, final String propertyName, final Object target) {
    final Class<?> currClass = OgnlRuntime.getTargetClass(target);
    final ExpressionCacheKey cacheKey = computeMethodCacheKey(currClass, propertyName);
    Method readMethod = null;
    if (expressionCache != null) {
        readMethod = (Method) expressionCache.get(cacheKey);
    }
    if (readMethod == null) {
        final BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(currClass);
        } catch (final IntrospectionException e) {
            // Something went wrong during introspection - wash hands, just let OGNL decide what to do
            throw new OGNLShortcutExpressionNotApplicableException();
        }
        final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if (propertyDescriptors != null) {
            for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                if (propertyDescriptor.getName().equals(propertyName)) {
                    readMethod = propertyDescriptor.getReadMethod();
                    if (readMethod != null && expressionCache != null) {
                        expressionCache.put(cacheKey, readMethod);
                    }
                    break;
                }
            }
        }
    }
    if (readMethod == null) {
        // The property name does not match any getter methods - better let OGNL decide what to do
        throw new OGNLShortcutExpressionNotApplicableException();
    }
    try {
        return readMethod.invoke(target, NO_PARAMS);
    } catch (final IllegalAccessException e) {
        // Oops! we better let OGNL take care of this its own way...
        throw new OGNLShortcutExpressionNotApplicableException();
    } catch (final InvocationTargetException e) {
        // Oops! we better let OGNL take care of this its own way...
        throw new OGNLShortcutExpressionNotApplicableException();
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) ExpressionCacheKey(org.thymeleaf.cache.ExpressionCacheKey) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

BeanInfo (java.beans.BeanInfo)420 PropertyDescriptor (java.beans.PropertyDescriptor)328 Method (java.lang.reflect.Method)217 SimpleBeanInfo (java.beans.SimpleBeanInfo)167 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)161 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)148 IntrospectionException (java.beans.IntrospectionException)115 InvocationTargetException (java.lang.reflect.InvocationTargetException)38 HashMap (java.util.HashMap)33 Test (org.junit.jupiter.api.Test)33 ArrayList (java.util.ArrayList)30 Field (java.lang.reflect.Field)17 Map (java.util.Map)17 Test (org.junit.Test)13 EventSetDescriptor (java.beans.EventSetDescriptor)12 MethodDescriptor (java.beans.MethodDescriptor)12 List (java.util.List)11 BeanDescriptor (java.beans.BeanDescriptor)10 HashSet (java.util.HashSet)8 Introspector (java.beans.Introspector)7