Java Examples for java.beans.IntrospectionException

The following java examples will help you to understand the usage of java.beans.IntrospectionException. These source code samples are taken from different open source projects.

Example 1
Project: openmap-master  File: GenericPropertySheet.java View source code
synchronized void setTarget(Object targ) {
    // System.out.println("Enter>
    // PropertySheetPanel.setTarget()");
    // We make the panel invisible during the reconfiguration
    // to try to reduce screen flicker.
    setVisible(false);
    removeAll();
    targetBean = targ;
    try {
        BeanInfo bi = Introspector.getBeanInfo(targetBean.getClass());
        properties = bi.getPropertyDescriptors();
    } catch (IntrospectionException ex) {
        error("GenericPropertySheet: Couldn't introspect", ex);
        return;
    }
    editors = new PropertyEditor[properties.length];
    values = new Object[properties.length];
    views = new Component[properties.length];
    labels = new JLabel[properties.length];
    int numEditorsToDisplay = 0;
    for (int i = 0; i < properties.length; i++) {
        String name = properties[i].getDisplayName();
        // Don't display hidden or expert properties.
        if (properties[i].isHidden() || properties[i].isExpert()) {
            System.out.println("Ignoring hidden or expert property " + name);
            continue;
        }
        Class type = properties[i].getPropertyType();
        Method getter = properties[i].getReadMethod();
        Method setter = properties[i].getWriteMethod();
        // Only display read/write properties.
        if ((getter == null) || (setter == null)) {
            System.out.println("Ignoring read-only/write-only property " + name);
            continue;
        }
        Component view = null;
        try {
            Object args[] = {};
            Object value = getter.invoke(targetBean, args);
            values[i] = value;
            PropertyEditor editor = null;
            Class pec = properties[i].getPropertyEditorClass();
            if (pec != null) {
                try {
                    editor = (PropertyEditor) pec.newInstance();
                } catch (Exception ex) {
                    System.out.println("Cannot instantiate editor class: " + pec);
                    System.out.println("Will try to find editor using " + "PropertyEditorManager");
                }
            }
            if (editor == null)
                editor = PropertyEditorManager.findEditor(type);
            editors[i] = editor;
            // If we can't edit this component, skip it.
            if (editor == null) {
                // If it's a user-defined property we give a
                // warning.
                String getterClass = properties[i].getReadMethod().getDeclaringClass().getName();
                if (getterClass.indexOf("java.") != 0)
                    System.err.println("Warning: Can't find public property editor for property \"" + name + "\".  Skipping.");
                continue;
            }
            // System.out.println("About to set value " + value);
            editor.setValue(value);
            editor.addPropertyChangeListener(_frame);
            // Now figure out how to display it...
            if (editor.isPaintable() && editor.supportsCustomEditor())
                view = new PropertyCanvas(_frame, editor);
            else if (editor.getTags() != null)
                view = new PropertySelector(editor);
            else if (editor.getAsText() != null) {
                view = new PropertyText(editor);
            } else {
                System.err.println("Warning: Property \"" + name + "\" has non-displayabale editor. Skipping.");
                continue;
            }
            if (editor instanceof GenericPropertyEditorInterface)
                ((GenericPropertyEditorInterface) editor).setTargetBean(targetBean);
        } catch (InvocationTargetException ex) {
            System.err.println("Skipping property " + name + " ; exception on target: " + ex.getTargetException());
            ex.getTargetException().printStackTrace();
            continue;
        } catch (Exception ex) {
            System.err.println("Skipping property " + name + "; exception: " + ex);
            ex.printStackTrace();
            continue;
        }
        labels[i] = new JLabel(name, JLabel.LEFT);
        views[i] = view;
        numEditorsToDisplay++;
    }
    // end for
    this.setLayout(new GridLayout(numEditorsToDisplay, 2));
    for (int i = 0; i < properties.length; i++) if (views[i] != null) {
        add(labels[i]);
        add(views[i]);
    }
    _frame.setNumEditorsToDisplay(numEditorsToDisplay);
    _frame.setFrameSize();
    processEvents = true;
    setVisible(true);
// System.out.println("Exit> PropertySheetPanel.setTarget()");
}
Example 2
Project: sitebricks-master  File: MvelEvaluatorCompiler.java View source code
//generates a parsing context with type information from the backing type's javabean properties
private ParserContext singleBackingTypeParserContext() throws ExpressionCompileException {
    ParserContext context = new ParserContext();
    context.setStrongTyping(true);
    context.addInput("this", backingType);
    PropertyDescriptor[] propertyDescriptors;
    try {
        propertyDescriptors = Introspector.getBeanInfo(backingType).getPropertyDescriptors();
    } catch (IntrospectionException e) {
        throw new ExpressionCompileException("Could not read class " + backingType);
    }
    // read @Visible annotated fields.
    for (Field field : backingType.getDeclaredFields()) {
        if (field.isAnnotationPresent(Visible.class)) {
            context.addInput(field.getName(), field.getType());
            if (!field.getAnnotation(Visible.class).readOnly()) {
                writeableProperties.add(field.getName());
            }
        }
    }
    // read javabean properties -- these override @Visible fields.
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        // skip getClass()
        if (CLASS.equals(propertyDescriptor.getName()))
            continue;
        if (null != propertyDescriptor.getWriteMethod()) {
            writeableProperties.add(propertyDescriptor.getName());
        }
        // if this is a collection, determine its type parameter
        if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
            Type propertyType;
            if (propertyDescriptor.getReadMethod() != null) {
                propertyType = propertyDescriptor.getReadMethod().getGenericReturnType();
            } else {
                propertyType = propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0];
            }
            ParameterizedType collectionType = (ParameterizedType) Generics.getExactSuperType(propertyType, Collection.class);
            Class<?>[] parameterClasses = new Class[1];
            Type parameterType = collectionType.getActualTypeArguments()[0];
            parameterClasses[0] = Generics.erase(parameterType);
            context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType(), parameterClasses);
        } else {
            context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType());
        }
    }
    return context;
}
Example 3
Project: jeboorker-master  File: BaseBeanInfo.java View source code
public ExtendedPropertyDescriptor addProperty(String propertyName) {
    ExtendedPropertyDescriptor descriptor;
    try {
        if (propertyName == null || propertyName.trim().length() == 0) {
            throw new IntrospectionException("bad property name");
        }
        descriptor = ExtendedPropertyDescriptor.newPropertyDescriptor(propertyName, getType());
        try {
            descriptor.setDisplayName(getResources().getString(propertyName));
        } catch (MissingResourceException e) {
        }
        try {
            descriptor.setShortDescription(getResources().getString(propertyName + ".shortDescription"));
        } catch (MissingResourceException e) {
        }
        addPropertyDescriptor(descriptor);
        return descriptor;
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}
Example 4
Project: bigtable-sql-master  File: SquirrelPreferencesBeanInfo.java View source code
/**
	 * See http://tinyurl.com/63no6t for discussion of the proper thread-safe way to implement
	 * getPropertyDescriptors().
	 * 
	 * @see java.beans.SimpleBeanInfo#getPropertyDescriptors()
	 */
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
    try {
        PropertyDescriptor[] result = new PropertyDescriptor[] { new PropertyDescriptor(SESSION_PROPERTIES, SquirrelPreferences.class, "getSessionProperties", "setSessionProperties"), new PropertyDescriptor(MAIN_FRAME_STATE, SquirrelPreferences.class, "getMainFrameWindowState", "setMainFrameWindowState"), new PropertyDescriptor(SHOW_CONTENTS_WHEN_DRAGGING, SquirrelPreferences.class, "getShowContentsWhenDragging", "setShowContentsWhenDragging"), new PropertyDescriptor(TABBED_STYLE, SquirrelPreferences.class, "getTabbedStyle", "setTabbedStyle"), new PropertyDescriptor(USE_SCROLLABLE_TABBED_PANES_FOR_SESSION_TABS, SquirrelPreferences.class, "getUseScrollableTabbedPanesForSessionTabs", "setUseScrollableTabbedPanesForSessionTabs"), new PropertyDescriptor(SHOW_TABBED_STYLE_HINT, SquirrelPreferences.class, "getShowTabbedStyleHint", "setShowTabbedStyleHint"), new PropertyDescriptor(LOGIN_TIMEOUT, SquirrelPreferences.class, "getLoginTimeout", "setLoginTimeout"), new PropertyDescriptor(LARGE_SCRIPT_STMT_COUNT, SquirrelPreferences.class, "getLargeScriptStmtCount", "setLargeScriptStmtCount"), new PropertyDescriptor(JDBC_DEBUG_TYPE, SquirrelPreferences.class, "getJdbcDebugType", "setJdbcDebugType"), new PropertyDescriptor(SHOW_MAIN_STATUS_BAR, SquirrelPreferences.class, "getShowMainStatusBar", "setShowMainStatusBar"), new PropertyDescriptor(SHOW_MAIN_TOOL_BAR, SquirrelPreferences.class, "getShowMainToolBar", "setShowMainToolBar"), new PropertyDescriptor(SHOW_ALIASES_TOOL_BAR, SquirrelPreferences.class, "getShowAliasesToolBar", "setShowAliasesToolBar"), new PropertyDescriptor(SHOW_DRIVERS_TOOL_BAR, SquirrelPreferences.class, "getShowDriversToolBar", "setShowDriversToolBar"), new PropertyDescriptor(SHOW_TOOLTIPS, SquirrelPreferences.class, "getShowToolTips", "setShowToolTips"), new PropertyDescriptor(SCROLLABLE_TABBED_PANES, SquirrelPreferences.class, "getUseScrollableTabbedPanes", "setUseScrollableTabbedPanes"), new IndexedPropertyDescriptor(ACTION_KEYS, SquirrelPreferences.class, "getActionKeys", "setActionKeys", "getActionKeys", "setActionKeys"), new PropertyDescriptor(PROXY, SquirrelPreferences.class, "getProxySettings", "setProxySettings"), new PropertyDescriptor(UPDATE, SquirrelPreferences.class, "getUpdateSettings", "setUpdateSettings"), new PropertyDescriptor(SHOW_LOADED_DRIVERS_ONLY, SquirrelPreferences.class, "getShowLoadedDriversOnly", "setShowLoadedDriversOnly"), new PropertyDescriptor(MAXIMIMIZE_SESSION_SHEET_ON_OPEN, SquirrelPreferences.class, "getMaximizeSessionSheetOnOpen", "setMaximizeSessionSheetOnOpen"), new PropertyDescriptor(SHOW_COLOR_ICONS_IN_TOOLBAR, SquirrelPreferences.class, "getShowColoriconsInToolbar", "setShowColoriconsInToolbar"), new PropertyDescriptor(FIRST_RUN, SquirrelPreferences.class, "isFirstRun", "setFirstRun"), new PropertyDescriptor(CONFIRM_SESSION_CLOSE, SquirrelPreferences.class, "getConfirmSessionClose", "setConfirmSessionClose"), new IndexedPropertyDescriptor(PLUGIN_STATUSES, SquirrelPreferences.class, "getPluginStatuses", "setPluginStatuses", "getPluginStatus", "setPluginStatus"), new PropertyDescriptor(NEW_SESSION_VIEW, SquirrelPreferences.class, "getNewSessionView", "setNewSessionView"), new PropertyDescriptor(FILE_OPEN_IN_PREVIOUS_DIR, SquirrelPreferences.class, "isFileOpenInPreviousDir", "setFileOpenInPreviousDir"), new PropertyDescriptor(FILE_OPEN_IN_SPECIFIED_DIR, SquirrelPreferences.class, "isFileOpenInSpecifiedDir", "setFileOpenInSpecifiedDir"), new PropertyDescriptor(FILE_SPECIFIED_DIR, SquirrelPreferences.class, "getFileSpecifiedDir", "setFileSpecifiedDir"), new PropertyDescriptor(FILE_PREVIOUS_DIR, SquirrelPreferences.class, "getFilePreviousDir", "setFilePreviousDir"), new PropertyDescriptor(SHOW_PLUGIN_FILES_IN_SPLASH_SCREEN, SquirrelPreferences.class, "getShowPluginFilesInSplashScreen", "setShowPluginFilesInSplashScreen"), new PropertyDescriptor(WARN_JRE_JDBC_MISMATCH, SquirrelPreferences.class, "getWarnJreJdbcMismatch", "setWarnJreJdbcMismatch"), new PropertyDescriptor(WARN_FOR_UNSAVED_FILE_EDITS, SquirrelPreferences.class, "getWarnForUnsavedFileEdits", "setWarnForUnsavedFileEdits"), new PropertyDescriptor(WARN_FOR_UNSAVED_BUFFER_EDITS, SquirrelPreferences.class, "getWarnForUnsavedBufferEdits", "setWarnForUnsavedBufferEdits"), new PropertyDescriptor(SHOW_SESSION_STARTUP_TIME_HINT, SquirrelPreferences.class, "getShowSessionStartupTimeHint", "setShowSessionStartupTimeHint"), new PropertyDescriptor(SHOW_DEBUG_LOG_MESSAGES, SquirrelPreferences.class, "getShowDebugLogMessage", "setShowDebugLogMessages"), new PropertyDescriptor(SHOW_INFO_LOG_MESSAGES, SquirrelPreferences.class, "getShowInfoLogMessages", "setShowInfoLogMessages"), new PropertyDescriptor(SHOW_ERROR_LOG_MESSAGES, SquirrelPreferences.class, "getShowErrorLogMessages", "setShowErrorLogMessages"), new PropertyDescriptor(SAVE_PREFERENCES_IMMEDIATELY, SquirrelPreferences.class, "getSavePreferencesImmediately", "setSavePreferencesImmediately"), new PropertyDescriptor(SELECT_ON_RIGHT_MOUSE_CLICK, SquirrelPreferences.class, "getSelectOnRightMouseClick", "setSelectOnRightMouseClick"), new PropertyDescriptor(SHOW_PLEASE_WAIT_DIALOG, SquirrelPreferences.class, "getShowPleaseWaitDialog", "setShowPleaseWaitDialog"), new PropertyDescriptor(PREFERRED_LOCALE, SquirrelPreferences.class, "getPreferredLocale", "setPreferredLocale") };
        return result;
    } catch (IntrospectionException e) {
        throw new Error(e);
    }
}
Example 5
Project: alien4cloud-master  File: DeploymentTopologyService.java View source code
/**
     * Check that the property is not already defined in a source
     *
     * @param sourcePropertyValue null or an already defined Property Value.
     * @param messageSource The named source to add in the exception message in case of failure.
     */
private void buildConstaintException(AbstractPropertyValue sourcePropertyValue, PropertyDefinition propertyDefinition, String messageSource, String propertyName, Object propertyValue) throws ConstraintViolationException {
    if (sourcePropertyValue != null) {
        try {
            EqualConstraint constraint = new EqualConstraint();
            if (sourcePropertyValue instanceof ScalarPropertyValue) {
                constraint.setEqual(((ScalarPropertyValue) sourcePropertyValue).getValue());
            }
            ConstraintUtil.ConstraintInformation information = ConstraintUtil.getConstraintInformation(constraint);
            // If admin has defined a value users should not be able to override it.
            throw new ConstraintViolationException("Overriding value specified " + messageSource + " is not authorized.", null, information);
        } catch (IntrospectionException e) {
            log.info("Constraint introspection error for property <" + propertyName + "> value <" + propertyValue + ">", e);
            throw new ConstraintTechnicalException("Constraint introspection error for property <" + propertyName + "> value <" + propertyValue + ">", e);
        }
    }
}
Example 6
Project: geotools-old-master  File: ValidationBeanInfo.java View source code
/**
     * Implementation of getPropertyDescriptors.  This method should be called
     * by all overriding sub-class methods.  Property names 'name',
     * 'description', 'typeNames'
     *
     *
     * @see java.beans.BeanInfo#getPropertyDescriptors()
     */
public PropertyDescriptor[] getPropertyDescriptors() {
    try {
        PropertyDescriptor[] pd = new PropertyDescriptor[2];
        ResourceBundle resourceBundle = getResourceBundle(Validation.class);
        pd[0] = createPropertyDescriptor("name", Validation.class, resourceBundle);
        pd[0].setExpert(false);
        pd[1] = createPropertyDescriptor("description", Validation.class, resourceBundle);
        pd[1].setExpert(false);
        return pd;
    } catch (IntrospectionException e) {
        e.printStackTrace();
        return new PropertyDescriptor[0];
    }
}
Example 7
Project: visuwall-master  File: ELHiddenTagBeanInfo.java View source code
public PropertyDescriptor[] getPropertyDescriptors() {
    ArrayList proplist = new ArrayList();
    try {
        proplist.add(new PropertyDescriptor("accesskey", ELHiddenTag.class, null, "setAccesskeyExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("alt", ELHiddenTag.class, null, "setAltExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("altKey", ELHiddenTag.class, null, "setAltKeyExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("bundle", ELHiddenTag.class, null, "setBundleExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("dir", ELHiddenTag.class, null, "setDirExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("disabled", ELHiddenTag.class, null, "setDisabledExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("indexed", ELHiddenTag.class, null, "setIndexedExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("lang", ELHiddenTag.class, null, "setLangExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("name", ELHiddenTag.class, null, "setNameExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onblur", ELHiddenTag.class, null, "setOnblurExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onchange", ELHiddenTag.class, null, "setOnchangeExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onclick", ELHiddenTag.class, null, "setOnclickExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("ondblclick", ELHiddenTag.class, null, "setOndblclickExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onfocus", ELHiddenTag.class, null, "setOnfocusExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onkeydown", ELHiddenTag.class, null, "setOnkeydownExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onkeypress", ELHiddenTag.class, null, "setOnkeypressExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onkeyup", ELHiddenTag.class, null, "setOnkeyupExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onmousedown", ELHiddenTag.class, null, "setOnmousedownExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onmousemove", ELHiddenTag.class, null, "setOnmousemoveExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onmouseout", ELHiddenTag.class, null, "setOnmouseoutExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onmouseover", ELHiddenTag.class, null, "setOnmouseoverExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("onmouseup", ELHiddenTag.class, null, "setOnmouseupExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("property", ELHiddenTag.class, null, "setPropertyExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("style", ELHiddenTag.class, null, "setStyleExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("styleClass", ELHiddenTag.class, null, "setStyleClassExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("styleId", ELHiddenTag.class, null, "setStyleIdExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("title", ELHiddenTag.class, null, "setTitleExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("titleKey", ELHiddenTag.class, null, "setTitleKeyExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("value", ELHiddenTag.class, null, "setValueExpr"));
    } catch (IntrospectionException ex) {
    }
    try {
        proplist.add(new PropertyDescriptor("write", ELHiddenTag.class, null, "setWriteExpr"));
    } catch (IntrospectionException ex) {
    }
    PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()];
    return ((PropertyDescriptor[]) proplist.toArray(result));
}
Example 8
Project: violetumleditor-master  File: PropertyEditorWidget.java View source code
private void populateWidget() {
    WContainerWidget container = new WContainerWidget();
    WVBoxLayout vbox = new WVBoxLayout();
    try {
        Introspector.flushFromCaches(bean.getClass());
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] descriptors = (PropertyDescriptor[]) info.getPropertyDescriptors().clone();
        Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() {

            public int compare(PropertyDescriptor d1, PropertyDescriptor d2) {
                Integer p1 = (Integer) d1.getValue("priority");
                Integer p2 = (Integer) d2.getValue("priority");
                if (p1 == null && p2 == null)
                    return 0;
                if (p1 == null)
                    return 1;
                if (p2 == null)
                    return -1;
                return p1.intValue() - p2.intValue();
            }
        });
        ResourceBundle rs = ResourceBundle.getBundle(ResourceBundleConstant.NODE_AND_EDGE_STRINGS, Locale.getDefault());
        for (int i = 0; i < descriptors.length; i++) {
            AbstractPropertyEditorWidget<?> editor = getEditorWidget(bean, descriptors[i]);
            if (editor != null) {
                vbox.addWidget(editor);
                this.isSomethingToEdit = true;
            }
        }
    } catch (IntrospectionException exception) {
        exception.printStackTrace();
    }
    container.setLayout(vbox);
    setImplementation(container);
}
Example 9
Project: openjdk8-jdk-master  File: GenSwingBeanInfo.java View source code
/**
     * Generates the BeanInfo source file using instrospection and a
     * Hashtable full of hints. This the only public method in this class.
     *
     * @param classname Root name of the class. i.e., JButton
     * @param dochash A hashtable containing the DocBeanInfo.
     */
public void genBeanInfo(String packageName, String classname, Hashtable dochash) {
    // The following initial values are just examples.  All of these
    // fields are initialized below.
    String beanClassName = "JInternalFrame";
    String beanClassObject = "javax.swing.JInternalFrame.class";
    String beanDescription = "<A description of this component>.";
    String beanPropertyDescriptors = "<createSwingPropertyDescriptor code>";
    String classPropertyDescriptors = "<createSwingClassPropertyDescriptor code>";
    Class cls = getClass(packageName, classname);
    if (cls == null) {
        messageAndExit("Can't find class: " + classname);
    }
    // Get the output stream.
    PrintStream out = initOutputFile(classname);
    // Run the Introspector and initialize the variables
    BeanInfo beanInfo = null;
    BeanDescriptor beanDescriptor = null;
    try {
        if (cls == javax.swing.JComponent.class) {
            // Go all the way up the heirarchy for JComponent
            beanInfo = Introspector.getBeanInfo(cls);
        } else {
            beanInfo = Introspector.getBeanInfo(cls, cls.getSuperclass());
        }
        beanDescriptor = beanInfo.getBeanDescriptor();
        beanDescription = beanDescriptor.getShortDescription();
    } catch (IntrospectionException e) {
        messageAndExit("Introspection failed for " + cls.getName() + " " + e);
    }
    beanClassName = beanDescriptor.getName();
    beanClassObject = cls.getName() + ".class";
    if (DEBUG) {
        System.out.println(">>>>GenSwingBeanInfo class: " + beanClassName);
    }
    // Generate the Class BeanDescriptor information first
    if (dochash.size() > 0) {
        if (dochash.containsKey(beanClassName)) {
            DocBeanInfo dbi = (DocBeanInfo) dochash.remove(beanClassName);
            classPropertyDescriptors = genBeanDescriptor(dbi);
            if (DEBUG)
                System.out.println("ClassPropertyDescriptors: " + classPropertyDescriptors);
            if (!(dbi.desc.equals("null")))
                beanDescription = dbi.desc;
        } else
            beanDescription = beanDescriptor.getShortDescription();
    } else
        beanDescription = beanDescriptor.getShortDescription();
    // Generate the Property descriptors
    beanPropertyDescriptors = genPropertyDescriptors(beanInfo, dochash);
    // Dump the template to out, substituting values for
    // @(token) tokens as they're encountered.
    int currentIndex = 0;
    // not loading this to get around build issue for now
    String template = loadTemplate();
    // current class.
    while (currentIndex < template.length()) {
        // Find the Token
        int tokenStart = template.indexOf("@(", currentIndex);
        if (tokenStart != -1) {
            out.print(template.substring(currentIndex, tokenStart));
            int tokenEnd = template.indexOf(")", tokenStart);
            if (tokenEnd == -1) {
                messageAndExit("Bad @(<token>) beginning at " + tokenStart);
            }
            String token = template.substring(tokenStart + 2, tokenEnd);
            if (token.equals(TOK_BEANCLASS)) {
                out.print(beanClassName);
            } else if (token.equals(TOK_CLASSDESC)) {
                if (!(classPropertyDescriptors.equals("<createSwingClassPropertyDescriptor code>"))) {
                    printDescriptors(out, classPropertyDescriptors, template, tokenStart);
                }
            } else if (token.equals(TOK_BEANPACKAGE)) {
                out.print(packageName);
            } else if (token.equals(TOK_BEANOBJECT)) {
                out.print(beanClassObject);
            } else if (token.equals(TOK_BEANDESC)) {
                out.print(beanDescription);
            } else if (token.equals(TOK_ENUMVARS)) {
                out.print(enumcode);
            } else if (token.equals(TOK_PROPDESC)) {
                printDescriptors(out, beanPropertyDescriptors, template, tokenStart);
            } else if (token.equals("#")) {
            // Ignore the @(#) Version Control tag if it exists.
            } else {
                messageAndExit("Unrecognized token @(" + token + ")");
            }
            currentIndex = tokenEnd + 1;
        } else {
            // tokenStart == -1 - We are finsihed.
            out.print(template.substring(currentIndex, template.length()));
            break;
        }
    }
    out.close();
}
Example 10
Project: openjdk-master  File: InheritanceBeanPropertyTest.java View source code
// ---------- run test ----------
public static void main(String[] args) throws Exception {
    Class<?> ic1 = ISet2Impl.class.getInterfaces()[0], ic2 = IGet2Impl.class.getInterfaces()[0];
    Class<?> cases[] = { OverloadGet.class, OverloadGet.class.getSuperclass(), OverloadSet.class, OverloadSet.class.getSuperclass(), OverloadIGet.class, OverloadISet.class, OverrideAnnotatedGet.class.getSuperclass(), OverrideAnnotatedIs.class.getSuperclass(), OverrideAnnotatedSet.class.getSuperclass(), AbstractGet2Ext.class.getSuperclass(), IGetImpl.class, IGetImpl2.class, IGetImpl3.class, IIsImpl.class, IIsImpl2.class, IIsImpl3.class, ISetImpl.class, ISetImpl2.class, ISetImpl3.class, ic1, // ic2,  // TODO: uncomment/update after 8155013 fix
    OverrideProtectedGet.class, HideStaticGet.class };
    boolean passed = true;
    for (Class<?> c : cases) {
        java.lang.reflect.Field f = c.getDeclaredField("TESTCASE");
        f.setAccessible(true);
        String descr = f.get(c).toString();
        System.out.println("\n" + c.getSimpleName() + " (" + descr + "):");
        BeanInfo i;
        try {
            i = Introspector.getBeanInfo(c, (c.equals(ic1) || c.equals(ic2)) ? null : Object.class);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
        boolean ok;
        if (isDefault(c)) {
            ok = checkDefault(i);
        } else {
            ok = checkInfo(i, ignoreVals(c));
        }
        System.out.println(ok ? "OK" : "NOK");
        passed = passed && ok;
    }
    if (!passed) {
        throw new RuntimeException("test failed");
    }
    System.out.println("\ntest passed");
}
Example 11
Project: tapestry-model-master  File: HibernateDescriptorDecorator.java View source code
/**
	 * I couldn't find a way to get the "mappedBy" value from the collection
	 * metadata, so I'm getting it from the OneToMany annotation.
	 */
private void decorateOneToManyCollection(final Class beanType, final CollectionDescriptor descriptor, org.hibernate.mapping.Collection mapping) {
    if (descriptor.isOneToMany() && mapping.isInverse()) {
        try {
            Field propertyField = beanType.getDeclaredField(descriptor.getName());
            PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(beanType).getPropertyDescriptors();
            PropertyDescriptor beanPropDescriptor = F.flow(propertyDescriptors).filter(new Predicate<PropertyDescriptor>() {

                public boolean accept(PropertyDescriptor propertyDescriptor) {
                    return propertyDescriptor.getName().equals(descriptor.getName());
                }
            }).first();
            Method readMethod = beanPropDescriptor.getReadMethod();
            String mappedBy = "";
            if (readMethod.isAnnotationPresent(javax.persistence.OneToMany.class)) {
                mappedBy = readMethod.getAnnotation(javax.persistence.OneToMany.class).mappedBy();
            } else if (propertyField.isAnnotationPresent(javax.persistence.OneToMany.class)) {
                mappedBy = propertyField.getAnnotation(javax.persistence.OneToMany.class).mappedBy();
            }
            if (!"".equals(mappedBy)) {
                descriptor.setInverseProperty(mappedBy);
            }
        } catch (SecurityException e) {
            logger.warn("Couldn't decorate collection: " + beanType.getSimpleName() + "." + descriptor.getName(), e);
        } catch (NoSuchFieldException e) {
            logger.warn("Couldn't decorate collection: " + beanType.getSimpleName() + "." + descriptor.getName(), e);
        } catch (IntrospectionException e) {
            logger.warn("Couldn't decorate collection: " + beanType.getSimpleName() + "." + descriptor.getName(), e);
        }
    }
}
Example 12
Project: dk-master  File: BeanMapUtils.java View source code
/**
	 * @Description: 将对象转为Map
	 * @Author Yang Cheng
	 * @Date: Feb 9, 2012 1:56:20 AM
	 * @param <T>
	 * @param bean
	 * @return
	 * @return Map<String,String>
	 */
public static <T> Map<String, String> beanToMap(T bean) {
    Class<? extends Object> type = bean.getClass();
    Map<String, String> returnMap = new HashMap<String, String>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                returnMap.put(propertyName, result(result));
            }
        }
    } catch (IntrospectionException e) {
        log.error(e);
        throw new RuntimeException("分析类属性失败", e);
    } catch (IllegalAccessException e) {
        log.error(e);
        throw new RuntimeException("分析类属性失败", e);
    } catch (InvocationTargetException e) {
        log.error(e);
        throw new RuntimeException("分析类属性失败", e);
    }
    return returnMap;
}
Example 13
Project: cloudtm-data-platform-master  File: SpatialFieldBridge.java View source code
private Double getCoordinateFromField(String coordinateField, Object value) {
    Class<?> clazz = value.getClass();
    try {
        Field latitude = clazz.getField(coordinateField);
        return (Double) latitude.get(value);
    } catch (NoSuchFieldException e) {
        try {
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(coordinateField, clazz, "get" + capitalize(coordinateField), null);
            Method latitudeGetter = propertyDescriptor.getReadMethod();
            if (latitudeGetter != null) {
                return (Double) latitudeGetter.invoke(value);
            } else {
                throw LOG.cannotReadFieldForClass(coordinateField, clazz.getName());
            }
        } catch (IllegalAccessException ex) {
            throw LOG.cannotReadFieldForClass(coordinateField, clazz.getName());
        } catch (InvocationTargetException ex) {
            throw LOG.cannotReadFieldForClass(coordinateField, clazz.getName());
        } catch (IntrospectionException ex) {
            throw LOG.cannotReadFieldForClass(coordinateField, clazz.getName());
        }
    } catch (IllegalAccessException e) {
        throw LOG.cannotReadFieldForClass(coordinateField, clazz.getName());
    }
}
Example 14
Project: hibernate-core-ogm-master  File: Cloneable.java View source code
private void checkListeners() {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(getClass(), Object.class);
        internalCheckListeners(beanInfo);
    } catch (IntrospectionException t) {
        throw new HibernateException("Unable to validate listener config", t);
    } finally {
        if (beanInfo != null) {
            // release the jdk internal caches everytime to ensure this
            // plays nicely with destroyable class-loaders
            Introspector.flushFromCaches(getClass());
        }
    }
}
Example 15
Project: cdt-tests-runner-master  File: DebugUtil.java View source code
/**
	 * Prints the values of javabean properties to the console.
	 * This method is not recursive, it does not print nested properties.
	 * 
	 * Example of usage: 
	 * 
	 * IResource resource = ...;
	 * DebugUtil.printObjectProperties(resource);
	 * DebugUtil.printObjectProperties(resource.getResourceAttributes());
	 * @since 5.1
	 */
public static void printObjectProperties(Object obj) {
    try {
        System.out.println("Object: " + obj);
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor propertyDescriptor : info.getPropertyDescriptors()) {
            Method getter = propertyDescriptor.getReadMethod();
            try {
                System.out.println("  " + getter.getName() + "=" + getter.invoke(obj, new Object[0]));
            } catch (Exception e) {
            }
        }
    } catch (IntrospectionException e) {
    }
}
Example 16
Project: richfaces-master  File: DependencyInjectorImpl.java View source code
private void locateManagedPropertyDescriptors(Class<?> clazz, IntrospectionData introspectionData, Map<String, ResourceParameter> injectableFields) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        if (beanInfo != null) {
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            if (descriptors != null) {
                for (PropertyDescriptor descriptor : descriptors) {
                    String propertyName = descriptor.getName();
                    ResourceParameter dependency = injectableFields.get(propertyName);
                    if (dependency == null) {
                        dependency = getAnnotation(descriptor, ResourceParameter.class);
                    }
                    if (dependency != null) {
                        Injector<?> injector = new PropertyDependencyInjector(descriptor, dependency);
                        introspectionData.addInjector(propertyName, injector);
                    }
                }
            }
        }
    } catch (IntrospectionException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(e.getMessage(), e);
        }
    } finally {
        Introspector.flushFromCaches(clazz);
    }
}
Example 17
Project: JBossAS51-master  File: ModelMBeanInvoker.java View source code
/**
    * 
    * @param d
    * @return
    * @throws Exception
    */
protected List getInterceptors(Descriptor d) throws Exception {
    if (d == null)
        return null;
    Descriptor[] interceptorDescriptors = (Descriptor[]) d.getFieldValue(INTERCEPTORS);
    if (interceptorDescriptors == null)
        return null;
    ArrayList interceptors = new ArrayList();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    for (int i = 0; i < interceptorDescriptors.length; i++) {
        Descriptor desc = interceptorDescriptors[i];
        String code = (String) desc.getFieldValue("code");
        // Ignore the legacy required interceptors
        if (code.equals(ModelMBeanInterceptor.class.getName()) || code.equals(ObjectReferenceInterceptor.class.getName()) || code.equals(PersistenceInterceptor2.class.getName())) {
            log.debug("Ignoring obsolete legacy interceptor: " + code);
            continue;
        }
        Class interceptorClass = loader.loadClass(code);
        Interceptor interceptor = null;
        // Check for a ctor(MBeanInvoker)
        Class[] ctorSig = { MBeanInvoker.class };
        try {
            Constructor ctor = interceptorClass.getConstructor(ctorSig);
            Object[] ctorArgs = { this };
            interceptor = (Interceptor) ctor.newInstance(ctorArgs);
        } catch (Throwable t) {
            log.debug("Could not invoke CTOR(MBeanInvoker) for '" + interceptorClass + "', trying default CTOR: " + t.getMessage());
            interceptor = (Interceptor) interceptorClass.newInstance();
        }
        interceptors.add(interceptor);
        // Apply any interceptor attributes
        String[] names = desc.getFieldNames();
        HashMap propertyMap = new HashMap();
        if (names.length > 1) {
            BeanInfo beanInfo = Introspector.getBeanInfo(interceptorClass);
            PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
            for (int p = 0; p < props.length; p++) {
                String fieldName = props[p].getName();
                propertyMap.put(fieldName, props[p]);
            }
            // Map each attribute to the corresponding interceptor property
            for (int n = 0; n < names.length; n++) {
                String name = names[n];
                if (name.equals("code"))
                    continue;
                String text = (String) desc.getFieldValue(name);
                PropertyDescriptor pd = (PropertyDescriptor) propertyMap.get(name);
                if (pd == null)
                    throw new IntrospectionException("No PropertyDescriptor for attribute:" + name);
                Method setter = pd.getWriteMethod();
                if (setter != null) {
                    Class ptype = pd.getPropertyType();
                    PropertyEditor editor = PropertyEditorManager.findEditor(ptype);
                    if (editor == null)
                        throw new IntrospectionException("Cannot convert string to interceptor attribute:" + name);
                    editor.setAsText(text);
                    Object args[] = { editor.getValue() };
                    setter.invoke(interceptor, args);
                }
            }
        }
    }
    if (interceptors.size() == 0)
        interceptors = null;
    return interceptors;
}
Example 18
Project: ESPlorer-master  File: ReflectionUtil.java View source code
/**
     * @param base
     * @param property
     * @return
     * @throws ELException
     * @throws PropertyNotFoundException
     */
public static PropertyDescriptor getPropertyDescriptor(Object base, Object property) throws ELException, PropertyNotFoundException {
    String name = ELSupport.coerceToString(property);
    PropertyDescriptor p = null;
    try {
        PropertyDescriptor[] desc = Introspector.getBeanInfo(base.getClass()).getPropertyDescriptors();
        for (int i = 0; i < desc.length; i++) {
            if (desc[i].getName().equals(name)) {
                return desc[i];
            }
        }
    } catch (IntrospectionException ie) {
        throw new ELException(ie);
    }
    throw new PropertyNotFoundException(MessageFactory.get("error.property.notfound", base, name));
}
Example 19
Project: Rio-master  File: Watch.java View source code
/**
     * @see WatchMBean#getCalculables
     */
@SuppressWarnings("unchecked")
public TabularData getCalculables() {
    try {
        Calculable[] calculables;
        if (localRef != null) {
            calculables = localRef.getCalculable();
        } else {
            calculables = watchDataSource.getCalculable();
        }
        CompositeType type = JMXUtil.createCompositeType(JMXUtil.toMap(calculables[0]), "Calculable", "Calculable");
        TabularType tabularType = new TabularType("Calculables", "Calculables", type, new String[] { "when" });
        TabularDataSupport tabularDataSupport = new TabularDataSupport(tabularType);
        for (Calculable calculable : calculables) {
            CompositeData compositeData = new CompositeDataSupport(type, JMXUtil.toMap(calculable));
            tabularDataSupport.put(compositeData);
        }
        return tabularDataSupport;
    } catch (OpenDataException e) {
        logger.warn(e.toString(), e);
    } catch (IntrospectionException e) {
        logger.warn(e.toString(), e);
    } catch (IllegalAccessException e) {
        logger.warn(e.toString(), e);
    } catch (InvocationTargetException e) {
        logger.warn(e.toString(), e);
    } catch (RemoteException e) {
        logger.warn(e.toString(), e);
    }
    return null;
}
Example 20
Project: Valkyrie-RCP-master  File: AbstractNestedMemberPropertyAccessor.java View source code
@Override
public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException {
    try {
        String actualPropertyName = org.springframework.beans.PropertyAccessorUtils.getPropertyName(propertyName);
        PropertyDescriptor pd = new PropertyDescriptor(actualPropertyName, getTargetClass());
        if (pd != null) {
            Class type = getPropertyType(propertyName);
            if (pd.getReadMethod() != null) {
                return new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1));
            } else if (pd.getWriteMethod() != null) {
                return new TypeDescriptor(BeanUtils.getWriteMethodParameter(pd));
            }
        }
    } catch (InvalidPropertyException ex) {
    } catch (IntrospectionException e) {
        throw new RuntimeException("Error creating property descriptor", e);
    }
    return null;
}
Example 21
Project: sqlpower-library-master  File: SPObjectPropertyChangeUndoableEdit.java View source code
@Override
public void redo() throws CannotRedoException {
    try {
        ((SPObject) event.getSource()).setMagicEnabled(false);
        modifyProperty(event.getNewValue());
    } catch (IllegalAccessException e) {
        logger.error("Couldn't access setter for " + event.getPropertyName(), e);
        throw new CannotRedoException();
    } catch (InvocationTargetException e) {
        logger.error("Setter for " + event.getPropertyName() + " on " + event.getSource() + " threw exception", e);
        throw new CannotRedoException();
    } catch (IntrospectionException e) {
        logger.error("Couldn't introspect source object " + event.getSource(), e);
        throw new CannotRedoException();
    } finally {
        ((SPObject) event.getSource()).setMagicEnabled(true);
    }
    super.redo();
}
Example 22
Project: jxta-master  File: PSEMembershipServiceBeanInfo.java View source code
/**
     *  [email protected]}
     **/
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
    try {
        PropertyDescriptor defaultcredential = new PropertyDescriptor("defaultCredential", PSEMembershipService.class, "getDefaultCredential", "setDefaultCredential");
        defaultcredential.setBound(true);
        PropertyDescriptor addcredential = new PropertyDescriptor("addCredential", PSEMembershipService.class);
        addcredential.setBound(true);
        PropertyDescriptor rv[] = { addcredential, defaultcredential };
        return rv;
    } catch (IntrospectionException failed) {
        throw new UndeclaredThrowableException(failed, "Configuration error");
    }
}
Example 23
Project: teiid-designer-master  File: TeiidScriptEngine.java View source code
public Map<String, Method> getMethodMap(Class<?> clazz) throws ScriptException {
    Map<Class<?>, Map<String, Method>> clazzMaps = null;
    Map<String, Method> methodMap = null;
    if (properties != null) {
        clazzMaps = properties.get();
        if (clazzMaps != null) {
            methodMap = clazzMaps.get(clazz);
            if (methodMap != null) {
                return methodMap;
            }
        }
    }
    try {
        BeanInfo info = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] pds = info.getPropertyDescriptors();
        methodMap = new LinkedHashMap<String, Method>();
        if (pds != null) {
            for (int j = 0; j < pds.length; j++) {
                PropertyDescriptor pd = pds[j];
                if (pd.getReadMethod() == null || pd instanceof IndexedPropertyDescriptor) {
                    continue;
                }
                String name = pd.getName();
                Method m = pd.getReadMethod();
                methodMap.put(name, m);
            }
        }
        MethodDescriptor[] mds = info.getMethodDescriptors();
        if (pds != null) {
            for (int j = 0; j < mds.length; j++) {
                MethodDescriptor md = mds[j];
                if (md.getMethod() == null || md.getMethod().getParameterTypes().length > 0 || md.getMethod().getReturnType() == Void.class || md.getMethod().getReturnType() == void.class) {
                    continue;
                }
                String name = md.getName();
                Method m = md.getMethod();
                methodMap.put(name, m);
            }
        }
        if (clazzMaps == null) {
            clazzMaps = Collections.synchronizedMap(new LRUCache<Class<?>, Map<String, Method>>(100));
            properties = new SoftReference<Map<Class<?>, Map<String, Method>>>(clazzMaps);
        }
        clazzMaps.put(clazz, methodMap);
    } catch (IntrospectionException e) {
        throw new ScriptException(e);
    }
    return methodMap;
}
Example 24
Project: liferay-ide-master  File: NameFragment.java View source code
public ICompletionProposal[] getMethodCompletionProposals(int subOffset, int offset, Class parentClass, IResource file) {
    if (instanceOf(parentClass, String.class) || instanceOf(parentClass, Number.class) || instanceOf(parentClass, Date.class) || instanceOf(parentClass, Collection.class) || instanceOf(parentClass, List.class) || instanceOf(parentClass, Map.class))
        return null;
    String prefix = getContent().substring(1, subOffset);
    List proposals = new ArrayList();
    String pUpper = prefix.toUpperCase();
    try {
        BeanInfo bi = Introspector.getBeanInfo(parentClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String propertyName = pd.getName();
            if (//$NON-NLS-1$
            !propertyName.equals("class") && propertyName.toUpperCase().startsWith(pUpper)) {
                proposals.add(new CompletionProposal(propertyName, offset - subOffset + 1, getContent().length() - 1, propertyName.length(), //$NON-NLS-1$
                null, //$NON-NLS-1$
                propertyName + " - " + pd.getReadMethod().getReturnType().getName(), //$NON-NLS-1$
                null, //$NON-NLS-1$
                null));
            }
        }
        for (int i = 0; i < parentClass.getMethods().length; i++) {
            Method m = parentClass.getMethods()[i];
            String mName = m.getName();
            if (//$NON-NLS-1$
            m.getParameterTypes().length > 0 && mName.startsWith("get") && mName.toUpperCase().startsWith(pUpper)) {
                StringBuffer display = new StringBuffer();
                display.append(mName);
                //$NON-NLS-1$
                display.append(//$NON-NLS-1$
                "(");
                for (int j = 0; j < m.getParameterTypes().length; j++) {
                    if (//$NON-NLS-1$
                    j > 0)
                        //$NON-NLS-1$
                        display.append(", ");
                    display.append(m.getParameterTypes()[j].getName());
                }
                //$NON-NLS-1$
                display.append(//$NON-NLS-1$
                ")");
                String //$NON-NLS-1$
                actual = //$NON-NLS-1$
                mName + "()";
                int tLength = actual.length();
                if (m.getParameterTypes().length > 0)
                    tLength--;
                proposals.add(new CompletionProposal(actual, offset - subOffset + 1, getContent().length() - 1, tLength, //$NON-NLS-1$
                null, //$NON-NLS-1$
                display.toString() + " - " + m.getReturnType().getName(), //$NON-NLS-1$
                null, //$NON-NLS-1$
                null));
            }
        }
        return completionProposals(proposals);
    } catch (IntrospectionException e) {
        return null;
    }
}
Example 25
Project: wso2-synapse-master  File: BeanMediator.java View source code
/**
     * Sets a property of a bean attached to the current message context.
     * @param synCtx The current message for mediation
     * @return true If mediation should continue
     */
private boolean mediateSetPropertyAction(MessageContext synCtx) {
    Object bean = synCtx.getProperty(varName);
    if (bean == null) {
        handleException("Bean with var name '" + varName + "' was not found.", synCtx);
        return false;
    }
    Object valueObj = value.evaluateObjectValue(synCtx);
    if (bean instanceof Map) {
        ((Map) bean).put(propertyName, valueObj);
    } else {
        try {
            BeanUtils.invokeInstanceMethod(bean, new PropertyDescriptor(propertyName, bean.getClass()).getWriteMethod(), new Object[] { valueObj });
        } catch (IntrospectionException e) {
            handleException("Could not resolve the setter method for '" + propertyName + "' property in '" + bean.getClass() + "'.", e, synCtx);
        } catch (SynapseException e) {
            handleException("Error while invoking the setter method for '" + propertyName + "' property on '" + bean.getClass() + "'.", e, synCtx);
        }
    }
    return true;
}
Example 26
Project: ilarkesto-master  File: BeanMap.java View source code
private void initialise() {
    if (getBean() == null)
        return;
    Class beanClass = getBean().getClass();
    try {
        // BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if (propertyDescriptors != null) {
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
                if (propertyDescriptor != null) {
                    String name = propertyDescriptor.getName();
                    Method readMethod = propertyDescriptor.getReadMethod();
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    Class aType = propertyDescriptor.getPropertyType();
                    if (readMethod != null) {
                        readMethods.put(name, readMethod);
                    }
                    if (writeMethods != null) {
                        writeMethods.put(name, writeMethod);
                    }
                    types.put(name, aType);
                }
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}
Example 27
Project: rabbitmq-java-client-master  File: JSONWriter.java View source code
/**
     * Write only a certain subset of the object's properties and fields.
     * @param klass the class to look up properties etc in
     * @param object the object
     * @param properties explicit list of property/field names to include - may be null for "all"
     */
public void writeLimited(Class<?> klass, Object object, String[] properties) {
    Set<String> propertiesSet = null;
    if (properties != null) {
        propertiesSet = new HashSet<String>();
        for (String p : properties) {
            propertiesSet.add(p);
        }
    }
    add('{');
    indentLevel += 2;
    newline();
    boolean needComma = false;
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(klass);
    } catch (IntrospectionException ie) {
        info = null;
    }
    if (info != null) {
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            String name = prop.getName();
            if (propertiesSet == null && name.equals("class")) {
                // We usually don't want the class in there.
                continue;
            }
            if (propertiesSet == null || propertiesSet.contains(name)) {
                Method accessor = prop.getReadMethod();
                if (accessor != null && !Modifier.isStatic(accessor.getModifiers())) {
                    try {
                        Object value = accessor.invoke(object, (Object[]) null);
                        if (needComma) {
                            add(',');
                            newline();
                        }
                        needComma = true;
                        add(name, value);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    Field[] ff = object.getClass().getDeclaredFields();
    for (int i = 0; i < ff.length; ++i) {
        Field field = ff[i];
        int fieldMod = field.getModifiers();
        String name = field.getName();
        if (propertiesSet == null || propertiesSet.contains(name)) {
            if (!Modifier.isStatic(fieldMod)) {
                try {
                    Object v = field.get(object);
                    if (needComma) {
                        add(',');
                        newline();
                    }
                    needComma = true;
                    add(name, v);
                } catch (Exception e) {
                }
            }
        }
    }
    indentLevel -= 2;
    newline();
    add('}');
}
Example 28
Project: framework-master  File: Design.java View source code
/**
     * Constructs a component hierarchy from the design specified as an html
     * tree.
     *
     * <p>
     * If a component root is given, the component instances created during
     * reading the design are assigned to its member fields based on their id,
     * local id, and caption
     *
     * @param doc
     *            the html tree
     * @param componentRoot
     *            optional component root instance. The type must match the type
     *            of the root element in the design.
     * @param classWithFields
     *            a class (componentRoot class or a super class) with some
     *            member fields. The member fields whose type is assignable from
     *            [email protected] Component} are bound to fields in the design based on
     *            id/local id/caption
     */
private static DesignContext designToComponentTree(Document doc, Component componentRoot, Class<?> classWithFields) {
    DesignContext designContext = new DesignContext(doc);
    designContext.readPackageMappings(doc);
    // No special handling for a document without a body element - should be
    // taken care of by jsoup.
    Element root = doc.body();
    Elements children = root.children();
    if (children.size() > 1) {
        throw new DesignException("The first level of a component hierarchy should contain at most one root component, but found " + children.size() + ".");
    }
    Element element = children.isEmpty() ? null : children.first();
    if (componentRoot != null) {
        if (element == null) {
            throw new DesignException("The root element cannot be null when the specified root Component is" + " not null.");
        }
        // user has specified root instance that may have member fields that
        // should be bound
        final FieldBinder binder;
        try {
            binder = new FieldBinder(componentRoot, classWithFields);
        } catch (IntrospectionException e) {
            throw new DesignException("Could not bind fields of the root component", e);
        }
        // create listener for component creations that binds the created
        // components to the componentRoot instance fields
        ComponentCreationListener creationListener = (ComponentCreatedEvent event) -> {
            binder.bindField(event.getComponent(), event.getLocalId());
        };
        designContext.addComponentCreationListener(creationListener);
        // create subtree
        designContext.readDesign(element, componentRoot);
        // make sure that all the member fields are bound
        Collection<String> unboundFields = binder.getUnboundFields();
        if (!unboundFields.isEmpty()) {
            throw new DesignException("Found unbound fields from component root " + unboundFields);
        }
        // no need to listen anymore
        designContext.removeComponentCreationListener(creationListener);
    } else {
        // createChild creates the entire component hierarchy
        componentRoot = element == null ? null : designContext.readDesign(element);
    }
    designContext.setRootComponent(componentRoot);
    return designContext;
}
Example 29
Project: Payara-master  File: GenericCrudCommand.java View source code
@Override
public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
    if (type.isAssignableFrom(List.class)) {
        final List<ConfigBeanProxy> values;
        try {
            if (annotated instanceof Method) {
                values = (List<ConfigBeanProxy>) ((Method) annotated).invoke(component);
            } else if (annotated instanceof Field) {
                values = (List<ConfigBeanProxy>) ((Field) annotated).get(component);
            } else {
                String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invalid_type", "Invalid annotated type {0} passed to InjectionResolver:getValue()", annotated.getClass().toString());
                logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVALID_ANNO_TYPE, annotated.getClass().toString());
                throw new MultiException(new IllegalArgumentException(msg));
            }
        } catch (IllegalAccessException e) {
            String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
            logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
            throw new MultiException(new IllegalStateException(msg, e));
        } catch (InvocationTargetException e) {
            String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
            logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
            throw new MultiException(new IllegalStateException(msg, e));
        }
        Object value = delegate.getValue(component, annotated, genericType, type);
        if (value == null) {
            if (logger.isLoggable(level)) {
                logger.log(level, "Value of " + annotated.toString() + " is null");
            }
            return null;
        }
        Type genericReturnType = null;
        if (annotated instanceof Method) {
            genericReturnType = ((Method) annotated).getGenericReturnType();
        } else if (annotated instanceof Field) {
            genericReturnType = ((Field) annotated).getGenericType();
        }
        if (genericReturnType == null) {
            throw new MultiException(new IllegalArgumentException("Cannot determine parametized type from " + annotated.toString()));
        }
        final Class<? extends ConfigBeanProxy> itemType = Types.erasure(Types.getTypeArgument(genericReturnType, 0));
        if (logger.isLoggable(level)) {
            logger.log(level, "Found that List<?> really is a List<" + itemType.toString() + ">");
        }
        if (itemType == null) {
            String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.nongeneric_type", "The List type returned by {0} must be a generic type", annotated.toString());
            logger.log(Level.SEVERE, ConfigApiLoggerInfo.LIST_NOT_GENERIC_TYPE, annotated.toString());
            throw new MultiException(new IllegalArgumentException(msg));
        }
        if (!ConfigBeanProxy.class.isAssignableFrom(itemType)) {
            String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.wrong_type", "The generic type {0} is not supported, only List<? extends ConfigBeanProxy> is", annotated.toString());
            logger.log(Level.SEVERE, ConfigApiLoggerInfo.GENERIC_TYPE_NOT_SUPPORTED, annotated.toString());
            throw new MultiException(new IllegalArgumentException(msg));
        }
        Properties props = convertStringToProperties(value.toString(), ':');
        if (logger.isLoggable(level)) {
            for (Map.Entry<Object, Object> entry : props.entrySet()) {
                logger.log(level, "Subtype " + itemType + " key:" + entry.getKey() + " value:" + entry.getValue());
            }
        }
        final BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(itemType);
        } catch (IntrospectionException e) {
            String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.introspection_failure", "Failure {0} while instrospecting {1} to find all getters and setters", e.getMessage(), itemType.getName());
            LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.INTROSPECTION_FAILED, e, itemType.getName());
            throw new MultiException(new IllegalStateException(msg, e));
        }
        for (final Map.Entry<Object, Object> entry : props.entrySet()) {
            ConfigBeanProxy child = (ConfigBeanProxy) component;
            try {
                ConfigBeanProxy cc = child.createChild(itemType);
                new InjectionManager().inject(cc, itemType, new InjectionResolver<Attribute>(Attribute.class) {

                    @Override
                    public boolean isOptional(AnnotatedElement annotated, Attribute annotation) {
                        return true;
                    }

                    @Override
                    public Method getSetterMethod(Method annotated, Attribute annotation) {
                        // variant.
                        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                            if (pd.getReadMethod().equals(annotated)) {
                                return pd.getWriteMethod();
                            }
                        }
                        return annotated;
                    }

                    @Override
                    public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
                        String name = annotated.getAnnotation(Attribute.class).value();
                        if ((name == null || name.length() == 0) && annotated instanceof Method) {
                            // maybe there is a better way to do this...
                            name = ((Method) annotated).getName().substring(3);
                            if (name.equalsIgnoreCase("name") || name.equalsIgnoreCase("key")) {
                                return type.cast(entry.getKey());
                            }
                            if (name.equalsIgnoreCase("value")) {
                                return type.cast(entry.getValue());
                            }
                        }
                        return null;
                    }
                });
                values.add(cc);
            } catch (TransactionFailure transactionFailure) {
                String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.transactionException", "Transaction exception {0} while injecting {1}", transactionFailure.getMessage(), itemType);
                LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.TX_FAILED, transactionFailure, itemType);
                throw new MultiException(new IllegalStateException(msg, transactionFailure));
            }
        }
        return null;
    }
    return delegate.getValue(component, annotated, genericType, type);
}
Example 30
Project: earthsci-master  File: AbstractLayerDelegator.java View source code
/**
	 * Copy the changed properties between layers, by calling the getters of the
	 * from layer and the setters on the to layer.
	 * 
	 * @param from
	 *            Layer to get property values from
	 * @param to
	 *            Layer to set property values on
	 */
private void copyProperties(Layer from, Layer to) {
    if (from == to) {
        return;
    }
    synchronized (propertiesChanged) {
        setPropertiesChangedTrackingEnabled(false);
        for (String property : propertiesChanged) {
            try {
                PropertyDescriptor fromPropertyDescriptor = new PropertyDescriptor(property, from.getClass());
                PropertyDescriptor toPropertyDescriptor = new PropertyDescriptor(property, to.getClass());
                Method getter = fromPropertyDescriptor.getReadMethod();
                Method setter = toPropertyDescriptor.getWriteMethod();
                Object value = getter.invoke(from);
                setter.invoke(to, value);
            } catch (IntrospectionException e) {
            } catch (Exception e) {
                logger.error("Error copying value between layers for property: " + property, e);
            }
        }
        setPropertiesChangedTrackingEnabled(true);
    }
}
Example 31
Project: dbfound-master  File: JsonUtil.java View source code
/**
	 * 将一个实体类对象转换成Json数据格式
	 * 
	 * @param bean
	 *            需要转换的实体类对象
	 * @return 转换后的Json格式字符串
	 */
public static String beanToJson(Object bean) {
    StringBuilder json = new StringBuilder();
    json.append("{");
    PropertyDescriptor[] props = null;
    try {
        props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
    } catch (IntrospectionException e) {
    }
    if (props != null) {
        for (int i = 0; i < props.length; i++) {
            try {
                String name = objectToJson(props[i].getName());
                String value = objectToJson(props[i].getReadMethod().invoke(bean));
                json.append(name);
                json.append(":");
                json.append(value);
                json.append(",");
            } catch (Exception e) {
            }
        }
        json.setCharAt(json.length() - 1, '}');
    } else {
        json.append("}");
    }
    return json.toString();
}
Example 32
Project: powermock-master  File: ReflectUtils.java View source code
private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) {
    try {
        BeanInfo info = Introspector.getBeanInfo(type, Object.class);
        PropertyDescriptor[] all = info.getPropertyDescriptors();
        if (read && write) {
            return all;
        }
        List properties = new ArrayList(all.length);
        for (int i = 0; i < all.length; i++) {
            PropertyDescriptor pd = all[i];
            if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) {
                properties.add(pd);
            }
        }
        return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]);
    } catch (IntrospectionException e) {
        throw new CodeGenerationException(e);
    }
}
Example 33
Project: Calendar-Application-master  File: JCalendarDemo.java View source code
/**
	 * Installes a demo bean.
	 * 
	 * @param bean
	 *            the demo bean
	 */
private void installBean(JComponent bean) {
    try {
        componentPanel.removeAll();
        componentPanel.add(bean);
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), bean.getClass().getSuperclass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        propertyPanel.removeAll();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        propertyPanel.setLayout(gridbag);
        int count = 0;
        String[] types = new String[] { "class java.util.Locale", "boolean", "int", "class java.awt.Color", "class java.util.Date", "class java.lang.String" };
        for (int t = 0; t < types.length; t++) {
            for (int i = 0; i < propertyDescriptors.length; i++) {
                if (propertyDescriptors[i].getWriteMethod() != null) {
                    String type = propertyDescriptors[i].getPropertyType().toString();
                    final PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
                    final JComponent currentBean = bean;
                    final Method readMethod = propertyDescriptor.getReadMethod();
                    final Method writeMethod = propertyDescriptor.getWriteMethod();
                    if (type.equals(types[t]) && (((readMethod != null) && (writeMethod != null)) || ("class java.util.Locale".equals(type)))) {
                        if ("boolean".equals(type)) {
                            boolean isSelected = false;
                            try {
                                Boolean booleanObj = ((Boolean) readMethod.invoke(bean, (Object[]) null));
                                isSelected = booleanObj.booleanValue();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            final JCheckBox checkBox = new JCheckBox("", isSelected);
                            checkBox.addActionListener(new ActionListener() {

                                public void actionPerformed(ActionEvent event) {
                                    try {
                                        if (checkBox.isSelected()) {
                                            writeMethod.invoke(currentBean, new Object[] { new Boolean(true) });
                                        } else {
                                            writeMethod.invoke(currentBean, new Object[] { new Boolean(false) });
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            addProperty(propertyDescriptors[i], checkBox, gridbag);
                            count += 1;
                        } else if ("int".equals(type)) {
                            JSpinField spinField = new JSpinField();
                            spinField.addPropertyChangeListener(new PropertyChangeListener() {

                                public void propertyChange(PropertyChangeEvent evt) {
                                    try {
                                        if (evt.getPropertyName().equals("value")) {
                                            writeMethod.invoke(currentBean, new Object[] { evt.getNewValue() });
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            });
                            try {
                                Integer integerObj = ((Integer) readMethod.invoke(bean, (Object[]) null));
                                spinField.setValue(integerObj.intValue());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            addProperty(propertyDescriptors[i], spinField, gridbag);
                            count += 1;
                        } else if ("class java.lang.String".equals(type)) {
                            String string = "";
                            try {
                                string = ((String) readMethod.invoke(bean, (Object[]) null));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            JTextField textField = new JTextField(string);
                            ActionListener actionListener = new ActionListener() {

                                public void actionPerformed(ActionEvent e) {
                                    try {
                                        writeMethod.invoke(currentBean, new Object[] { e.getActionCommand() });
                                    } catch (Exception ex) {
                                    }
                                }
                            };
                            textField.addActionListener(actionListener);
                            addProperty(propertyDescriptors[i], textField, gridbag);
                            count += 1;
                        } else if ("class java.util.Locale".equals(type)) {
                            JLocaleChooser localeChooser = new JLocaleChooser(bean);
                            localeChooser.setPreferredSize(new Dimension(200, localeChooser.getPreferredSize().height));
                            addProperty(propertyDescriptors[i], localeChooser, gridbag);
                            count += 1;
                        } else if ("class java.util.Date".equals(type)) {
                            Date date = null;
                            try {
                                date = ((Date) readMethod.invoke(bean, (Object[]) null));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            JDateChooser dateChooser = new JDateChooser(date);
                            dateChooser.addPropertyChangeListener(new PropertyChangeListener() {

                                public void propertyChange(PropertyChangeEvent evt) {
                                    try {
                                        if (evt.getPropertyName().equals("date")) {
                                            writeMethod.invoke(currentBean, new Object[] { evt.getNewValue() });
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            });
                            addProperty(propertyDescriptors[i], dateChooser, gridbag);
                            count += 1;
                        } else if ("class java.awt.Color".equals(type)) {
                            final JButton button = new JButton();
                            try {
                                final Color colorObj = ((Color) readMethod.invoke(bean, (Object[]) null));
                                button.setText("...");
                                button.setBackground(colorObj);
                                ActionListener actionListener = new ActionListener() {

                                    public void actionPerformed(ActionEvent e) {
                                        Color newColor = JColorChooser.showDialog(JCalendarDemo.this, "Choose Color", colorObj);
                                        button.setBackground(newColor);
                                        try {
                                            writeMethod.invoke(currentBean, new Object[] { newColor });
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                };
                                button.addActionListener(actionListener);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            addProperty(propertyDescriptors[i], button, gridbag);
                            count += 1;
                        }
                    }
                }
            }
        }
        URL iconURL = bean.getClass().getResource("images/" + bean.getName() + "Color16.gif");
        ImageIcon icon = new ImageIcon(iconURL);
        componentTitlePanel.setTitle(bean.getName(), icon);
        bean.invalidate();
        propertyPanel.invalidate();
        componentPanel.invalidate();
        componentPanel.repaint();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
}
Example 34
Project: spring-framework-2.5.x-master  File: MapMessageConverter.java View source code
public MapMessageConverter.RBeanInfo createBeanInfo(String name, Class bean) {
    try {
        RBeanInfo info = (RBeanInfo) beanInfo.get(name);
        if (info != null) {
            return info;
        }
        if (bean == null) {
            return null;
        }
        BeanInfo bi = Introspector.getBeanInfo(bean);
        Map getters = new HashMap();
        Map setters = new HashMap();
        PropertyDescriptor[] props = bi.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            String propName = prop.getName();
            Method readMethod = prop.getReadMethod();
            Method writeMethod = prop.getWriteMethod();
            if ((readMethod == null) || (writeMethod == null) || !(!propName.startsWith("get") && !propName.startsWith("set"))) {
                continue;
            }
            String ucPropName = propName.substring(0, 1).toUpperCase() + propName.substring(1);
            getters.put(ucPropName, readMethod);
            setters.put(ucPropName, writeMethod);
        }
        return new RBeanInfo(name, getters, setters);
    } catch (IntrospectionException e) {
        return new RBeanInfo(bean.getClass().getName(), new HashMap(), new HashMap());
    }
}
Example 35
Project: j2objc-master  File: IndexedPropertyDescriptorTest.java View source code
/*
     * Class under test for void IndexedPropertyDescriptor(String, Class)
     */
public void testIndexedPropertyDescriptorStringClass() throws IntrospectionException, SecurityException, NoSuchMethodException {
    String propertyName = "propertyFour";
    Class<MockJavaBean> beanClass = MockJavaBean.class;
    IndexedPropertyDescriptor ipd = new IndexedPropertyDescriptor(propertyName, beanClass);
    String capitalName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
    Method readMethod = beanClass.getMethod("get" + capitalName, (Class[]) null);
    Method writeMethod = beanClass.getMethod("set" + capitalName, new Class[] { String[].class });
    Method indexedReadMethod = beanClass.getMethod("get" + capitalName, new Class[] { Integer.TYPE });
    Method indexedWriteMethod = beanClass.getMethod("set" + capitalName, new Class[] { Integer.TYPE, String.class });
    assertEquals(readMethod, ipd.getReadMethod());
    assertEquals(writeMethod, ipd.getWriteMethod());
    assertEquals(indexedReadMethod, ipd.getIndexedReadMethod());
    assertEquals(indexedWriteMethod, ipd.getIndexedWriteMethod());
    assertEquals(String[].class, ipd.getPropertyType());
    assertEquals(String.class, ipd.getIndexedPropertyType());
    assertFalse(ipd.isBound());
    assertFalse(ipd.isConstrained());
    assertEquals(propertyName, ipd.getDisplayName());
    assertEquals(propertyName, ipd.getName());
    assertEquals(propertyName, ipd.getShortDescription());
    assertNotNull(ipd.attributeNames());
    assertFalse(ipd.isExpert());
    assertFalse(ipd.isHidden());
    assertFalse(ipd.isPreferred());
    // Regression for HARMONY-1236
    try {
        new IndexedPropertyDescriptor("0xDFRF", Float.TYPE);
        fail("IntrospectionException expected");
    } catch (IntrospectionException e) {
    }
}
Example 36
Project: solmix-master  File: DataUtils.java View source code
/**
     * Return Property Type of given class.
     * 
     * @param c bean class .
     * @param propertyName property of the bean class
     * @return property type class
     * @throws IntrospectionException
     */
public static Class<?> getPropertyType(Class<?> c, String propertyName) throws IntrospectionException {
    if (c == null)
        throw new NullPointerException("Class parameter can not be null");
    if (propertyName == null)
        throw new NullPointerException("Property name parameter can not be null");
    if ("".equals(propertyName.trim()))
        throw new IntrospectionException("Property name parameter can not be empty");
    String path[] = propertyName.split("\\.");
    Class<?> propertyType = null;
    Field fields[] = c.getDeclaredFields();
    int i = 0;
    int length = fields != null ? fields.length : 0;
    do {
        if (i >= length)
            break;
        Field field = fields[i];
        if (path[0].equals(field.getName())) {
            propertyType = field.getType();
            break;
        }
        i++;
    } while (true);
    if (propertyType == null) {
        Method methods[] = c.getMethods();
        Method arr$[] = methods;
        int len$ = arr$.length;
        int i$ = 0;
        do {
            if (i$ >= len$)
                break;
            Method method = arr$[i$];
            if (path[0].equals(getterName(method))) {
                propertyType = method.getReturnType();
                break;
            }
            i$++;
        } while (true);
    }
    if (propertyType == null) {
        fields = getClassFields(c);
        length = fields.length;
        i = 0;
        do {
            if (i >= length)
                break;
            Field field = fields[i];
            if (path[0].equals(field.getName())) {
                propertyType = field.getType();
                break;
            }
            i++;
        } while (true);
    }
    if (propertyType == null) {
        Method methods[] = getClassMethods(c);
        Method arr$[] = methods;
        int len$ = arr$.length;
        int i$ = 0;
        do {
            if (i$ >= len$)
                break;
            Method method = arr$[i$];
            if (path[0].equals(getterName(method))) {
                propertyType = method.getReturnType();
                break;
            }
            i$++;
        } while (true);
    }
    if (propertyType == null)
        throw new IntrospectionException((new StringBuilder()).append("Property \"").append(path[0]).append("\" is not found in class \"").append(c.getName()).append("\"").toString());
    if (path.length > 1) {
        String subName = "";
        for (i = 1; i < path.length; i++) {
            if (!"".equals(subName))
                subName = (new StringBuilder()).append(subName).append(".").toString();
            subName = (new StringBuilder()).append(subName).append(path[i]).toString();
        }
        if (!propertyType.isPrimitive())
            return getPropertyType(propertyType, subName);
        else
            throw new IntrospectionException((new StringBuilder()).append("Found primitive property \"").append(path[0]).append("\" in class \"").append(c.getName()).append("\". It can not have subproperty \"").append(subName).append("\"").toString());
    } else {
        return propertyType;
    }
}
Example 37
Project: lucene-solr-master  File: SolrPluginUtils.java View source code
private static Method findSetter(Class<?> clazz, String setterName, String key, Class<?> paramClazz) {
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException ie) {
        throw new RuntimeException("Error getting bean info for class : " + clazz.getName(), ie);
    }
    for (final boolean matchParamClazz : new boolean[] { true, false }) {
        for (final MethodDescriptor desc : beanInfo.getMethodDescriptors()) {
            final Method m = desc.getMethod();
            final Class<?> p[] = m.getParameterTypes();
            if (m.getName().equals(setterName) && p.length == 1 && (!matchParamClazz || paramClazz.equals(p[0]))) {
                return m;
            }
        }
    }
    throw new RuntimeException("No setter corrresponding to '" + key + "' in " + clazz.getName());
}
Example 38
Project: google-web-toolkit-svnmirror-master  File: GwtSpecificValidatorCreator.java View source code
private void writeFields(SourceWriter sw) throws UnableToCompleteException {
    // Create a static array of all valid property names.
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(beanHelper.getClazz());
    } catch (IntrospectionException e) {
        throw error(logger, e);
    }
    // private static final java.util.List<String> ALL_PROPERTY_NAMES =
    sw.println("private static final java.util.List<String> ALL_PROPERTY_NAMES = ");
    sw.indent();
    sw.indent();
    // Collections.<String>unmodifiableList(
    sw.println("java.util.Collections.<String>unmodifiableList(");
    sw.indent();
    sw.indent();
    // java.util.Arrays.<String>asList(
    sw.print("java.util.Arrays.<String>asList(");
    // "foo","bar" );
    sw.print(Joiner.on(",").join(Iterables.transform(ImmutableList.copyOf(beanInfo.getPropertyDescriptors()), Functions.compose(TO_LITERAL, PROPERTY_DESCRIPTOR_TO_NAME))));
    sw.println("));");
    sw.outdent();
    sw.outdent();
    sw.outdent();
    sw.outdent();
    // Create a variable for each constraint of each property
    for (PropertyDescriptor p : beanHelper.getBeanDescriptor().getConstrainedProperties()) {
        int count = 0;
        for (ConstraintDescriptor<?> constraint : p.getConstraintDescriptors()) {
            writeConstraintDescriptor(sw, constraint, constraintDescriptorVar(p.getPropertyName(), count++));
        }
        writePropertyDescriptor(sw, p);
        if (p.isCascaded()) {
            beansToValidate.add(isIterableOrMap(p.getElementClass()) ? createBeanHelper(beanHelper.getAssociationType(p, true)) : createBeanHelper(p.getElementClass()));
        }
    }
    // Create a variable for each constraint of this class.
    int count = 0;
    for (ConstraintDescriptor<?> constraint : beanHelper.getBeanDescriptor().getConstraintDescriptors()) {
        writeConstraintDescriptor(sw, constraint, constraintDescriptorVar("this", count++));
    }
    // Now write the BeanDescriptor after we already have the
    // PropertyDescriptors and class constraints
    writeBeanDescriptor(sw);
    sw.println();
}