Java Code Examples for java.beans.BeanInfo

The following are top voted examples for showing how to use java.beans.BeanInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: Test4520754.java   Source Code and License 7 votes vote down vote up
private static BeanInfo getBeanInfo(Boolean mark, Class type) {
    System.out.println("test=" + mark + " for " + type);
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(type);
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
    if (info == null) {
        throw new Error("could not find BeanInfo for " + type);
    }
    if (mark != info.getBeanDescriptor().getValue("test")) {
        throw new Error("could not find marked BeanInfo for " + type);
    }
    return info;
}
 
Example 2
Project: convertigo-engine   File: GetIcon.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServiceException {

	String className = request.getParameter("className");
	String large = request.getParameter("large");

	if (className == null || !className.startsWith("com.twinsoft.convertigo.beans"))
		throw new ServiceException("Must provide className parameter", null);

	try {
		BeanInfo bi = CachedIntrospector.getBeanInfo(GenericUtils.<Class<? extends DatabaseObject>>cast(Class.forName(className)));
		int iconType = large != null && large.equals("true") ? BeanInfo.ICON_COLOR_32x32 : BeanInfo.ICON_COLOR_16x16;
		IOUtils.copy(bi.getBeanDescriptor().getBeanClass().getResourceAsStream(MySimpleBeanInfo.getIconName(bi, iconType)), response.getOutputStream());
	} catch (Exception e) {
		throw new ServiceException("Icon unreachable", e);
	}

	Engine.logAdmin.info("The image has been exported");
}
 
Example 3
Project: incubator-netbeans   File: ReflectionInfo.java   Source Code and License 6 votes vote down vote up
private static List<ReflectionInfo> fromObject(Integer index, Object obj) throws IntrospectionException {
    if (obj == null || obj.getClass().getName().startsWith("java.lang") // NOI18N
            || obj.getClass().getName().startsWith("java.math")) { // NOI18N
        // Let the default handle this
        return Collections.singletonList(new ReflectionInfo(index, null));
    } else {
        BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class);
        List<ReflectionInfo> result = new ArrayList<>();
        for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
            result.add(new ReflectionInfo(index, pd.getName()));
        }
        if (result.isEmpty()) {
            return Collections.singletonList(new ReflectionInfo(index, null));
        } else {
            return result;
        }
    }
}
 
Example 4
Project: lams   File: Cloneable.java   Source Code and License 6 votes vote down vote up
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 5
Project: gate-core   File: AbstractResource.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the value for a specified parameter for this resource.
 *
 * @param paramaterName the name for the parameter
 * @param parameterValue the value the parameter will receive
 */
@Override
public void setParameterValue(String paramaterName, Object parameterValue)
            throws ResourceInstantiationException{
  // get the beaninfo for the resource bean, excluding data about Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = getBeanInfo(this.getClass());
  } catch(Exception e) {
    throw new ResourceInstantiationException(
      "Couldn't get bean info for resource " + this.getClass().getName()
      + Strings.getNl() + "Introspector exception was: " + e
    );
  }
  setParameterValue(this, resBeanInf, paramaterName, parameterValue);
}
 
Example 6
Project: springbootWeb   File: RootClassInfo.java   Source Code and License 6 votes vote down vote up
private RootClassInfo(String className, List<String> warnings) {
    super();
    this.className = className;
    this.warnings = warnings;

    if (className == null) {
        return;
    }
    
    FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(className);
    String nameWithoutGenerics = fqjt.getFullyQualifiedNameWithoutTypeParameters();
    if (!nameWithoutGenerics.equals(className)) {
        genericMode = true;
    }

    try {
        Class<?> clazz = ObjectFactory.externalClassForName(nameWithoutGenerics);
        BeanInfo bi = Introspector.getBeanInfo(clazz);
        propertyDescriptors = bi.getPropertyDescriptors();
    } catch (Exception e) {
        propertyDescriptors = null;
        warnings.add(getString("Warning.20", className)); //$NON-NLS-1$
    }
}
 
Example 7
Project: incubator-netbeans   File: IconPanel.java   Source Code and License 6 votes vote down vote up
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    Node node = Visualizer.findNode(value);
    thumbImage = node.getIcon(BeanInfo.ICON_COLOR_32x32);
    this.selected = isSelected;
    label.setOpaque(selected);
    if (selected) {
      label.setBackground(UIManager.getColor("List.selectionBackground"));
      label.setForeground(UIManager.getColor("List.selectionForeground"));
    } else {
      label.setBackground(UIManager.getColor("Label.background"));
      label.setForeground(UIManager.getColor("Label.foreground"));
    }
    this.focused = cellHasFocus;
    this.label.setText(node.getDisplayName());

    return this;
}
 
Example 8
Project: openjdk-jdk10   File: OverridePropertyInfoTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        BeanInfo i = Introspector.getBeanInfo(C.class, Object.class);
        PropertyDescriptor[] pds = i.getPropertyDescriptors();

        Checker.checkEq("number of properties", pds.length, 1);
        PropertyDescriptor p = pds[0];
        Checker.checkEq("property description", p.getShortDescription(), "CHILD");

        Checker.checkEq("isBound",  p.isBound(),  false);
        Checker.checkEq("isExpert", p.isExpert(), false);
        Checker.checkEq("isHidden", p.isHidden(), false);
        Checker.checkEq("isPreferred", p.isPreferred(), false);
        Checker.checkEq("required", p.getValue("required"), false);
        Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), false);

        Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"),
            new Object[]{"BOTTOM", 3, "javax.swing.SwingConstants.BOTTOM"});
    }
 
Example 9
Project: openjdk-jdk10   File: OverrideUserDefPropertyInfoTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        BeanInfo i = Introspector.getBeanInfo(C.class, Object.class);
        Checker.checkEq("description",
            i.getBeanDescriptor().getShortDescription(), "CHILD");

        PropertyDescriptor[] pds = i.getPropertyDescriptors();
        Checker.checkEq("number of properties", pds.length, 1);
        PropertyDescriptor p = pds[0];

        Checker.checkEq("property description", p.getShortDescription(), "CHILDPROPERTY");
        Checker.checkEq("isBound",  p.isBound(),  childFlag);
        Checker.checkEq("isExpert", p.isExpert(), childFlag);
        Checker.checkEq("isHidden", p.isHidden(), childFlag);
        Checker.checkEq("isPreferred", p.isPreferred(), childFlag);
        Checker.checkEq("required", p.getValue("required"), childFlag);
        Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), childFlag);

        Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"),
            new Object[]{"BOTTOM", 3, "javax.swing.SwingConstants.BOTTOM"});
    }
 
Example 10
Project: myfaces-trinidad   File: TableBuilder.java   Source Code and License 6 votes vote down vote up
private void _setPropertySetters(Class<?> klass, List<Object> props)
  throws IntrospectionException
{
  BeanInfo beanInfo = Introspector.getBeanInfo(klass);
  PropertyDescriptor[] descs = beanInfo.getPropertyDescriptors();
  for(int i=0, sz=props.size(); i<sz; i++)
  {
    String name = (String)props.get(i);
    PropertyDescriptor desc = _getDescriptor(descs, name);
    if (desc == null)
    {
      throw new IllegalArgumentException("property:"+name+" not found on:"
        +klass);
    }
    Method setter = desc.getWriteMethod();
    if (setter == null)
    {
      throw new IllegalArgumentException("No way to set property:"+name+" on:"
        +klass);
    }
    props.set(i, setter);
  }
}
 
Example 11
Project: bubichain-sdk-java   File: PojoPropertiesConverter.java   Source Code and License 6 votes vote down vote up
private void resolveParamProperties() throws IntrospectionException{
    List<ArgDefEntry<RequestParamDefinition>> reqParamDefs = new LinkedList<>();

    BeanInfo beanInfo = Introspector.getBeanInfo(argType);
    PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor propDesc : propDescs) {
        //            TypeDescriptor propTypeDesc;
        //            propTypeDesc = beanWrapper.getPropertyTypeDescriptor(propDesc.getName());


        //            RequestParam reqParamAnno = propTypeDesc.getAnnotation(RequestParam.class);
        RequestParam reqParamAnno = propDesc.getPropertyType().getAnnotation(RequestParam.class);
        if (reqParamAnno == null) {
            // 忽略未标注 RequestParam 的属性;
            continue;
        }
        RequestParamDefinition reqParamDef = RequestParamDefinition.resolveDefinition(reqParamAnno);
        ArgDefEntry<RequestParamDefinition> defEntry = new ArgDefEntry<>(reqParamDefs.size(), propDesc.getPropertyType(),
                reqParamDef);
        reqParamDefs.add(defEntry);
        propNames.add(propDesc.getName());
    }
    paramResolver = RequestParamResolvers.createParamResolver(reqParamDefs);
}
 
Example 12
Project: neoscada   File: AbstractObjectExporter.java   Source Code and License 6 votes vote down vote up
/**
 * create data items from the properties
 */
protected void createDataItems ( final Class<?> targetClazz )
{
    try
    {
        final BeanInfo bi = Introspector.getBeanInfo ( targetClazz );
        for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
        {
            final DataItem item = createItem ( pd, targetClazz );
            this.items.put ( pd.getName (), item );

            final Map<String, Variant> itemAttributes = new HashMap<String, Variant> ();
            fillAttributes ( pd, itemAttributes );
            this.attributes.put ( pd.getName (), itemAttributes );

            initAttribute ( pd );
        }
    }
    catch ( final IntrospectionException e )
    {
        logger.info ( "Failed to read initial item", e );
    }
}
 
Example 13
Project: zooadmin   File: BeanMapUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将对象转为Map,为null的字段跳过,同时保持有序
 * @param bean
 * @return
 * @throws IntrospectionException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map bean2MapNull(Object bean) throws IntrospectionException,
		IllegalAccessException, InvocationTargetException {
	Class type = bean.getClass();
	Map returnMap = new TreeMap();
	BeanInfo beanInfo = Introspector.getBeanInfo(type);
	PropertyDescriptor[] propertyDescriptors = beanInfo
			.getPropertyDescriptors();
	for (int i = 0; i < propertyDescriptors.length; i++) {
		PropertyDescriptor descriptor = propertyDescriptors[i];
		String propertyName = descriptor.getName();
		if (!propertyName.equals("class")) {
			Method readMethod = descriptor.getReadMethod();
			Object result = readMethod.invoke(bean, new Object[0]);
			if (result != null) {
				returnMap.put(propertyName, result);
			} else {
				//没有值的字段直接跳过
			}
		}
	}
	return returnMap;
}
 
Example 14
Project: iBase4J   File: InstanceUtil.java   Source Code and License 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
	Map<String, Object> map = newHashMap();
	if (obj == null) {
		return map;
	}
	try {
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			// 过滤class属性
			if (!key.equals("class")) {
				// 得到property对应的getter方法
				Method getter = property.getReadMethod();
				Object value = getter.invoke(obj);
				map.put(key, value);
			}
		}
	} catch (Exception e) {
		System.out.println("transBean2Map Error " + e);
	}
	return map;
}
 
Example 15
Project: incubator-netbeans   File: AbstractContextMenuFactory.java   Source Code and License 6 votes vote down vote up
private void configureMenuItem (JMenuItem item, String containerCtx, String action, ActionProvider provider, Map context) {
//        System.err.println("ConfigureMenuItem: " + containerCtx + "/" + action);
        item.setName(action);
        item.putClientProperty(KEY_ACTION, action);
        item.putClientProperty(KEY_CONTAINERCONTEXT, containerCtx);
        item.putClientProperty(KEY_CREATOR, this);
        item.setText(
            provider.getDisplayName(action, containerCtx));
        item.setToolTipText(provider.getDescription(action, containerCtx));
        int state = context == null ? ActionProvider.STATE_ENABLED | ActionProvider.STATE_VISIBLE :
            provider.getState (action, containerCtx, context);
        boolean enabled = (state & ActionProvider.STATE_ENABLED) != 0; 
        item.setEnabled(enabled);
        boolean visible = (state & ActionProvider.STATE_VISIBLE) != 0;
        //Intentionally use enabled property
        item.setVisible(enabled);
        item.setMnemonic(provider.getMnemonic(action, containerCtx));
        item.setDisplayedMnemonicIndex(provider.getMnemonicIndex(action, containerCtx));
        item.setIcon(provider.getIcon(action, containerCtx, BeanInfo.ICON_COLOR_16x16));
    }
 
Example 16
Project: incubator-netbeans   File: AbstractMenuFactory.java   Source Code and License 6 votes vote down vote up
private void configureMenuItem (JMenuItem item, String containerCtx, String action, ActionProvider provider, Map context) {
//        System.err.println("ConfigureMenuItem: " + containerCtx + "/" + action);
        item.setName(action);
        item.putClientProperty(KEY_ACTION, action);
        item.putClientProperty(KEY_CONTAINERCONTEXT, containerCtx);
        item.putClientProperty(KEY_CREATOR, this);
        item.setText(
            provider.getDisplayName(action, containerCtx));
//        System.err.println("  item text is " + item.getText());
        item.setToolTipText(provider.getDescription(action, containerCtx));
        int state = context == null ? ActionProvider.STATE_ENABLED | ActionProvider.STATE_VISIBLE :
            provider.getState (action, containerCtx, context);
        boolean enabled = (state & ActionProvider.STATE_ENABLED) != 0; 
//        System.err.println("action " + action + (enabled ? " enabled" : " disabled"));
        item.setEnabled(enabled);
        boolean visible = (state & ActionProvider.STATE_VISIBLE) != 0;
//        System.err.println("action " + action + (visible ? " visible" : " invisible"));
        item.setVisible(visible);
        item.setMnemonic(provider.getMnemonic(action, containerCtx));
        item.setDisplayedMnemonicIndex(provider.getMnemonicIndex(action, containerCtx));
        item.setIcon(provider.getIcon(action, containerCtx, BeanInfo.ICON_COLOR_16x16));
    }
 
Example 17
Project: incubator-netbeans   File: UINodeTest.java   Source Code and License 6 votes vote down vote up
public void testIconOfTheNode() throws Exception {
    LogRecord r = new LogRecord(Level.INFO, "icon_msg");
    r.setResourceBundleName("org.netbeans.modules.uihandler.TestBundle");
    r.setResourceBundle(ResourceBundle.getBundle("org.netbeans.modules.uihandler.TestBundle"));
    r.setParameters(new Object[] { new Integer(1), "Ahoj" });
    
    Node n = UINode.create(r);
    assertEquals("Name is taken from the message", "icon_msg", n.getName());
    
    if (!n.getDisplayName().matches(".*Ahoj.*")) {
        fail("wrong display name, shall contain Ahoj: " + n.getDisplayName());
    }
    
    Image img = n.getIcon(BeanInfo.ICON_COLOR_32x32);
    assertNotNull("Some icon", img);
    IconInfo imgReal = new IconInfo(img);
    IconInfo template = new IconInfo(getClass().getResource("testicon.png"));
    assertEquals("Icon from ICON_BASE used", template, imgReal);
    
    assertSerializedWell(n);
}
 
Example 18
Project: gate-core   File: CorpusAnnotationDiff.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the value for a specified parameter.
 *
 * @param paramaterName the name for the parameteer
 * @param parameterValue the value the parameter will receive
 */
@Override
public void setParameterValue(String paramaterName, Object parameterValue)
            throws ResourceInstantiationException{
  // get the beaninfo for the resource bean, excluding data about Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = Introspector.getBeanInfo(this.getClass(), Object.class);
  } catch(Exception e) {
    throw new ResourceInstantiationException(
      "Couldn't get bean info for resource " + this.getClass().getName()
      + Strings.getNl() + "Introspector exception was: " + e
    );
  }
  AbstractResource.setParameterValue(this, resBeanInf, paramaterName, parameterValue);
}
 
Example 19
Project: CodeGen   File: BuilderUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Bean --> Map
 * @param obj
 * @return
 */
public static Map<String, Object> transBean2Map(Object obj) {
    if(obj == null){
        return null;
    }
    Map<String, Object> map = new HashMap<>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!"class".equals(key)) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 20
Project: openjdk-jdk10   File: Test7195106.java   Source Code and License 6 votes vote down vote up
public static void main(String[] arg) throws Exception {
    BeanInfo info = Introspector.getBeanInfo(My.class);
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Unexpected behavior");
    }
    try {
        int[] array = new int[1024];
        while (true) {
            array = new int[array.length << 1];
        }
    }
    catch (OutOfMemoryError error) {
        System.gc();
    }
    if (null == info.getIcon(BeanInfo.ICON_COLOR_16x16)) {
        throw new Error("Explicit BeanInfo is collected");
    }
}
 
Example 21
Project: openjdk-jdk10   File: InheritPropertyInfoTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        BeanInfo i = Introspector.getBeanInfo(C.class, Object.class);
        PropertyDescriptor[] pds = i.getPropertyDescriptors();

        Checker.checkEq("number of properties", pds.length, 1);
        PropertyDescriptor p = pds[0];

        Checker.checkEq("property description", p.getShortDescription(), "BASE");

        Checker.checkEq("isBound",  p.isBound(),  true);
        Checker.checkEq("isExpert", p.isExpert(), true);
        Checker.checkEq("isHidden", p.isHidden(), true);
        Checker.checkEq("isPreferred", p.isPreferred(), true);
        Checker.checkEq("required", p.getValue("required"), true);
        Checker.checkEq("visualUpdate", p.getValue("visualUpdate"), true);

        Checker.checkEnumEq("enumerationValues", p.getValue("enumerationValues"),
            new Object[]{"TOP", 1, "javax.swing.SwingConstants.TOP"});
    }
 
Example 22
Project: automat   File: InstanceUtil.java   Source Code and License 6 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {
    Map<String, Object> map = newHashMap();
    if (obj == null) {
        return map;
    }
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        System.out.println("transBean2Map Error " + e);
    }
    return map;
}
 
Example 23
Project: neoscada   File: VariantBeanHelper.java   Source Code and License 6 votes vote down vote up
public static void apply ( final Map<String, Variant> data, final Object target, final WriteAttributeResults results ) throws IntrospectionException
{
    final BeanInfo bi = Introspector.getBeanInfo ( target.getClass () );

    for ( final Map.Entry<String, Variant> entry : data.entrySet () )
    {
        final PropertyDescriptor pd = findDescriptor ( bi, entry.getKey () );
        if ( pd != null )
        {
            try
            {
                applyValue ( target, pd, entry.getValue () );
                results.put ( entry.getKey (), WriteAttributeResult.OK );
            }
            catch ( final Exception e )
            {
                results.put ( entry.getKey (), new WriteAttributeResult ( e ) );
            }
        }
        else
        {
            results.put ( entry.getKey (), new WriteAttributeResult ( new IllegalArgumentException ( String.format ( "'%s' is not a property name of '%s'", entry.getKey (), target.getClass ().getName () ) ) ) );
        }
    }
}
 
Example 24
Project: zooadmin   File: BeanMapUtil.java   Source Code and License 6 votes vote down vote up
public static Object convertMap2Bean(Class type, Map map)
		throws IntrospectionException, IllegalAccessException,
		InstantiationException, InvocationTargetException {
	BeanInfo beanInfo = Introspector.getBeanInfo(type);
	Object obj = type.newInstance();
	PropertyDescriptor[] propertyDescriptors = beanInfo
			.getPropertyDescriptors();
	for (PropertyDescriptor pro : propertyDescriptors) {
		String propertyName = pro.getName();
		if (pro.getPropertyType().getName().equals("java.lang.Class")) {
			continue;
		}
		if (map.containsKey(propertyName)) {
			Object value = map.get(propertyName);
			Method setter = pro.getWriteMethod();
			setter.invoke(obj, value);
		}
	}
	return obj;
}
 
Example 25
Project: myfaces-trinidad   File: JavaIntrospector.java   Source Code and License 6 votes vote down vote up
/**
 * Introspect on a Java bean and learn about all its properties, exposed
 * methods, and events, subnject to some comtrol flags.
 *
 * @param beanClass  The bean class to be analyzed.
 * @param flags  Flags to control the introspection.
 *     If flags == USE_ALL_BEANINFO then we use all of the BeanInfo
 *         classes we can discover.
 *     If flags == IGNORE_IMMEDIATE_BEANINFO then we ignore any
 *           BeanInfo associated with the specified beanClass.
 *     If flags == IGNORE_ALL_BEANINFO then we ignore all BeanInfo
 *           associated with the specified beanClass or any of its
 *         parent classes.
 * @return  A BeanInfo object describing the target bean.
 * @exception IntrospectionException if an exception occurs during
 *              introspection.
 */
public static BeanInfo getBeanInfo(
  Class<?> beanClass,
  int      flags
  ) throws IntrospectionException
{
  // if they want all of the bean info, call the caching version of this
  // method so that we cache the result
  if (flags == USE_ALL_BEANINFO)
  {
    return getBeanInfo(beanClass);
  }
  else
  {
    //
    // use the uncached version
    //
    return new JavaIntrospector(beanClass, null, flags)._getBeanInfo();
  }
}
 
Example 26
Project: JAVA-   File: InstanceUtil.java   Source Code and License 6 votes vote down vote up
public static void transMap2Bean(Map<String, Object> map, Object obj) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (map.containsKey(key)) {
                Object value = map.get(key);
                // 得到property对应的setter方法
                Method setter = property.getWriteMethod();
                setter.invoke(obj, value);
            }
        }
    } catch (Exception e) {
        System.out.println("transMap2Bean Error " + e);
    }
    return;
}
 
Example 27
Project: lazycat   File: BeanELResolver.java   Source Code and License 6 votes vote down vote up
@Override
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
	if (base == null) {
		return null;
	}

	try {
		BeanInfo info = Introspector.getBeanInfo(base.getClass());
		PropertyDescriptor[] pds = info.getPropertyDescriptors();
		for (int i = 0; i < pds.length; i++) {
			pds[i].setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE);
			pds[i].setValue(TYPE, pds[i].getPropertyType());
		}
		return Arrays.asList((FeatureDescriptor[]) pds).iterator();
	} catch (IntrospectionException e) {
		//
	}

	return null;
}
 
Example 28
Project: convertigo-eclipse   File: ObjectExplorerWizardPage.java   Source Code and License 6 votes vote down vote up
@Override
public void performHelp() {
	String href = null;
	BeanInfo bi = getCurrentSelectedBeanInfo();
	if (bi != null) {
		String displayName = bi.getBeanDescriptor().getDisplayName();
		if ((displayName != null) && !displayName.equals(""))
			href = getBeanHelpHref(displayName);
	}
	
	if ((href == null) || href.equals(""))
		href = "convertigoObjects.html";
	
	String helpPageUri = "/com.twinsoft.convertigo.studio.help/help/helpRefManual/"+ href;
	PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpPageUri);
}
 
Example 29
Project: doctemplate   File: BeanMergeSource.java   Source Code and License 6 votes vote down vote up
private static Method getAccessMethod(Object o, String name) {

		Map<String, Method> methods = beanAccessMethodCache.get(o.getClass());
		if (methods == null) {
			methods = new HashMap<>();
			try {
				BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
				PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
				for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
					Method readMethod = propertyDescriptor.getReadMethod();
					if (readMethod != null) {
						methods.put(propertyDescriptor.getName().toLowerCase(), readMethod);
					}
				}
			} catch (IntrospectionException e) {
				log.warn("Introspection Exception", e);
			}
			synchronized (beanAccessMethodCache) {
				beanAccessMethodCache.put(o.getClass(), methods);
			}
		}
		return methods.get(name.toLowerCase());
	}
 
Example 30
Project: SummerFramework   File: XMLBeanFactory.java   Source Code and License 6 votes vote down vote up
private void autowiredByName(Bean bean) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClazz());
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        
        for (PropertyDescriptor desc : descriptors) {
            for (Bean definedBean : beanDefinitionList) {
                if (desc.getName().equals(definedBean.getName())) {
                    desc.getWriteMethod().invoke(bean.getObject(), createBean(definedBean) );
                    break;
                }
            }
        }
    } catch (Exception e) {
        throw new BeansException(e);
    }
}
 
Example 31
Project: SummerFramework   File: XMLBeanFactory.java   Source Code and License 6 votes vote down vote up
private void autowiredByType(Bean bean) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClazz());
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

        PropertyDescriptor usePd = null;
        List<Bean> foundBeans = new ArrayList<Bean>();
        for (PropertyDescriptor desc : descriptors) {
            for (Bean definedBean : beanDefinitionList) {
                if (desc.getPropertyType().equals(definedBean.getClazz())) {
                    foundBeans.add(definedBean);
                    usePd = desc;
                }
            }
        }
        
        if (!foundBeans.isEmpty()) {
            if (foundBeans.size() > 1)
                throw new BeansException("too many");
            usePd.getWriteMethod().invoke(bean.getObject(), createBean(foundBeans.get(0)) );
        }
    } catch (Exception e) {
        throw new BeansException(e);
    }
}
 
Example 32
Project: gate-core   File: AbstractResource.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the values for more parameters for a resource in one step.
 *
 * @param parameters a feature map that has parameter names as keys and
 * parameter values as values.
 */
public static void setParameterValues(Resource resource,
                                      FeatureMap parameters)
            throws ResourceInstantiationException{
  // get the beaninfo for the resource bean, excluding data about Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = getBeanInfo(resource.getClass());
  } catch(Exception e) {
    throw new ResourceInstantiationException(
      "Couldn't get bean info for resource " + resource.getClass().getName()
      + Strings.getNl() + "Introspector exception was: " + e
    );
  }

  Iterator<Object> parnameIter = parameters.keySet().iterator();
  while(parnameIter.hasNext()){
    String parName = (String)parnameIter.next();
    setParameterValue(resource, resBeanInf, parName, parameters.get(parName));
  }
}
 
Example 33
Project: generator_mybatis   File: RootClassInfo.java   Source Code and License 6 votes vote down vote up
private RootClassInfo(String className, List<String> warnings) {
    super();
    this.className = className;
    this.warnings = warnings;

    if (className == null) {
        return;
    }
    
    FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(className);
    String nameWithoutGenerics = fqjt.getFullyQualifiedNameWithoutTypeParameters();
    if (!nameWithoutGenerics.equals(className)) {
        genericMode = true;
    }

    try {
        Class<?> clazz = ObjectFactory.externalClassForName(nameWithoutGenerics);
        BeanInfo bi = Introspector.getBeanInfo(clazz);
        propertyDescriptors = bi.getPropertyDescriptors();
    } catch (Exception e) {
        propertyDescriptors = null;
        warnings.add(getString("Warning.20", className)); //$NON-NLS-1$
    }
}
 
Example 34
Project: openjdk-jdk10   File: TestMethodOrderDependence.java   Source Code and License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final BeanInfo beanInfo = Introspector.getBeanInfo(Sub.class);
    final PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    for (final PropertyDescriptor pd : pds) {
        System.err.println("pd = " + pd);
        final Class<?> type = pd.getPropertyType();
        if (type != Class.class && type != Long[].class
                && type != Integer.class && type != Enum.class) {
            throw new RuntimeException(Arrays.toString(pds));
        }
    }
}
 
Example 35
Project: slardar   File: ReflectUtils.java   Source Code and License 5 votes vote down vote up
public static PropertyDescriptor[] propertyDescriptors(Class<?> c) {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(c);
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

    return beanInfo.getPropertyDescriptors();
}
 
Example 36
Project: urule   File: ClassUtils.java   Source Code and License 5 votes vote down vote up
private static List<Variable> paserClass(String path,Class<?> cls, Collection<Class<?>> parsed) throws Exception{
	List<Variable> variables=new ArrayList<Variable>();
	BeanInfo beanInfo=Introspector.getBeanInfo(cls,Object.class);
	PropertyDescriptor[] pds= beanInfo.getPropertyDescriptors();
	
	if(pds!=null && !parsed.contains(cls)){
		parsed.add(cls);
		for(PropertyDescriptor pd:pds){
			Variable variable=new Variable();
			Class<?> type=pd.getPropertyType();
			Datatype dataType=getDateType(type);
			String propertyName=pd.getName();
			String label=getPropertyAnnotationLabel(cls, propertyName);
			String name=path+pd.getName();
			variable.setName(name);
			variable.setLabel(label==null?name:label);
			variable.setType(dataType);
			variable.setAct(Act.InOut);
			if(Datatype.Object.equals(dataType)){
				variables.addAll(paserClass(path+pd.getName()+".",type, parsed));
			}else{
				variables.add(variable);
			}
		}
	}
	return variables;
}
 
Example 37
Project: lams   File: Binder.java   Source Code and License 5 votes vote down vote up
@Override
public void processBeanInfo(BeanInfo beanInfo) throws Exception {
	for ( PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors() ) {
		if ( propertyDescriptor.getName().equals( attributeName ) ) {
			javaType = propertyDescriptor.getPropertyType();
			break;
		}
	}
}
 
Example 38
Project: TITAN   File: BeanInfoUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @desc 根据对象获取对象所有属性、属性值
 *
 * @author liuliang
 *
 * @param entity 对象
 * @return Map<String,Object> [key:属性名   value:属性名对应的值]
 */
public static Map<String,Object> getBeanInfo(Object entity){
	Map<String,Object> map = new HashMap<String, Object>(16);
	try {
		Class<?> clazz = entity.getClass();
		BeanInfo beanInfo = null;
		if(null == methodCache.get(clazz)){
			Class<?> superClazz =clazz.getSuperclass();
			beanInfo = Introspector.getBeanInfo(clazz, superClazz);
			methodCache.put(clazz, beanInfo);
			
			Introspector.flushFromCaches(clazz);
			if(null != superClazz){
				Introspector.flushFromCaches(superClazz);
			}
		}else{
			beanInfo = methodCache.get(clazz);
		}
		
		PropertyDescriptor[] pdArr = beanInfo.getPropertyDescriptors();
		for(PropertyDescriptor pd:pdArr){
			String fieldName = pd.getName();
			Object fieldValue = getFieldValue(pd.getReadMethod(),entity);
			map.put(fieldName, fieldValue);
		}
	} catch (IntrospectionException e) {
		logger.error("获取对象信息异常,entity:{}",entity.getClass(),e);
	}
	return map;
}
 
Example 39
Project: vind   File: FunctionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getterFunctionTest() throws IntrospectionException {
    final BeanInfo beanInfo = Introspector.getBeanInfo(GetterFunction.class);
    final Method applyMethod = Arrays.asList(beanInfo.getMethodDescriptors())
            .stream()
            .map(md -> md.getMethod())
            .filter(m -> m.getName().equals("apply"))
            .findAny()
            .get();
    final Class<?>[] parameterTypes = applyMethod.getParameterTypes();
    final Class<?> returnType = applyMethod.getReturnType();
    assertTrue(true);
}
 
Example 40
Project: openjdk-jdk10   File: Test4809008.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    printMemory("Start Memory");
    int introspected = 200;
    for (int i = 0; i < introspected; i++) {
        ClassLoader cl = new SimpleClassLoader();
        Class type = cl.loadClass("Bean");
        type.newInstance();

        // The methods and the bean info should be cached
        BeanInfo info = Introspector.getBeanInfo(type);

        cl = null;
        type = null;
        info = null;
        System.gc();
    }
    System.runFinalization();
    printMemory("End Memory");

    int finalized = SimpleClassLoader.numFinalizers;
    System.out.println(introspected + " classes introspected");
    System.out.println(finalized + " classes finalized");

    // good if at least half of the finalizers are run
    if (finalized < (introspected >> 1)) {
        throw new Error("ClassLoaders not finalized: " + finalized);
    }
}
 
Example 41
Project: incubator-netbeans   File: LanguagesDataLoaderBeanInfo.java   Source Code and License 5 votes vote down vote up
public BeanInfo[] getAdditionalBeanInfo() {
    try {
        return new BeanInfo[] {Introspector.getBeanInfo(MultiFileLoader.class)};
    } catch (IntrospectionException e) {
        throw new AssertionError(e);
    }
}
 
Example 42
Project: incubator-netbeans   File: WhereUsedDataLoaderBeanInfo.java   Source Code and License 5 votes vote down vote up
public BeanInfo[] getAdditionalBeanInfo() {
    try {
        return new BeanInfo[] {Introspector.getBeanInfo(UniFileLoader.class)};
    } catch (IntrospectionException e) {
        throw new AssertionError(e);
    }
}
 
Example 43
Project: openjdk-jdk10   File: Test4168475.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    Introspector.setBeanInfoSearchPath(PATH);
    BeanInfo info = Introspector.getBeanInfo(Component.class);
    PropertyDescriptor[] pds = info.getPropertyDescriptors();

    // The custom ComponentBeanInfo we deliver
    // only provides a single property.

    if (pds.length != 1) {
        throw new Error("wrong number of properties");
    }
    if (!pds[0].getName().equals("name")) {
        throw new Error("unexpected property name");
    }
}
 
Example 44
Project: tasfe-framework   File: FieldHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 通过方法获取属性
 * @param entityClass
 * @return
 */
public List<EntityField> getProperties(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = _getGenericTypeMap(entityClass);
    List<EntityField> entityFields = new ArrayList<EntityField>();
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor desc : descriptors) {
        if (desc != null && !"class".equals(desc.getName())) {
            EntityField entityField = new EntityField(desc);
            if (desc.getReadMethod() != null
                    && desc.getReadMethod().getGenericReturnType() != null
                    && desc.getReadMethod().getGenericReturnType() instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getReadMethod().getGenericReturnType()).getName()));
            } else if (desc.getWriteMethod() != null
                    && desc.getWriteMethod().getGenericParameterTypes() != null
                    && desc.getWriteMethod().getGenericParameterTypes().length == 1
                    && desc.getWriteMethod().getGenericParameterTypes()[0] instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getWriteMethod().getGenericParameterTypes()[0]).getName()));
            }
            entityFields.add(entityField);
        }
    }
    return entityFields;
}
 
Example 45
Project: lams   File: Util.java   Source Code and License 5 votes vote down vote up
public static void setBeanProps(Object obj, String[] propNames, Object[] propValues)  throws JobPersistenceException {
    
    if(propNames == null || propNames.length == 0)
        return;
    if(propNames.length != propValues.length)
        throw new IllegalArgumentException("propNames[].lenght != propValues[].length");
    
    String name = null;
    
    try {
        BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propDescs = bi.getPropertyDescriptors();
    
        for(int i=0; i < propNames.length; i++) {
            name = propNames[i];
            String c = name.substring(0, 1).toUpperCase(Locale.US);
            String methName = "set" + c + name.substring(1);
    
            java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs);
    
            if (setMeth == null) {
                throw new NoSuchMethodException(
                        "No setter for property '" + name + "'");
            }

            Class<?>[] params = setMeth.getParameterTypes();
            if (params.length != 1) {
                throw new NoSuchMethodException(
                    "No 1-argument setter for property '" + name + "'");
            }
            
            setMeth.invoke(obj, new Object[]{ propValues[i] });
        }
    }
    catch(Exception e) {
        throw new JobPersistenceException(
            "Unable to set property named: " + name +" of object of type: " + obj.getClass().getCanonicalName(), 
            e); 
    }
}
 
Example 46
Project: convertigo-eclipse   File: CreateExtractionRuleDialog.java   Source Code and License 5 votes vote down vote up
@Override
protected void okPressed() {
	BeanInfo bi = objectsExplorerComposite.getCurrentSelectedBeanInfo();
	if (bi != null) {
		beanClass = bi.getBeanDescriptor().getBeanClass();
	}
	super.okPressed();
}
 
Example 47
Project: convertigo-eclipse   File: ConvertigoPlugin.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the property descriptor of the selected property for this databaseObjectBeanInfo 
 * @param databaseObjectBeanInfo : BeanInfo of the selected databaseObject in the TreeExplorerView
 * @return PropertyDescriptor
 */
public PropertyDescriptor getSelectedPropertyDescriptor(BeanInfo databaseObjectBeanInfo) {
	PropertyDescriptor propertyDescriptor = null;
	
	// gets the properties editor
	PropertySheet view = ConvertigoPlugin.getDefault().getPropertiesView();
	Tree tree = (Tree) view.getCurrentPage().getControl();
	// gets the property selected in the property editor if one is selected
	TreeItem[] items = tree.getSelection();
	if (items.length > 0) {
		TreeItem selectedItem = items[0];
	
		// gets the local name of the selected property
		String text = selectedItem.getText();
        
        // gets the PropertyDescriptors of this databaseObject
        PropertyDescriptor[] descriptors = databaseObjectBeanInfo.getPropertyDescriptors();
        
        String displayName = null;
		int i = 0;
		
		// gets the PropertyDescriptor of the selected property 
		while (i < descriptors.length && propertyDescriptor == null) {
			displayName = descriptors[i].getDisplayName();
			if (displayName.equals(text))
				propertyDescriptor = descriptors[i];
			i++;
		}
	}	
	return propertyDescriptor;
}
 
Example 48
Project: incubator-netbeans   File: RepositoryBrowserPanel.java   Source Code and License 5 votes vote down vote up
protected Image getFolderIcon (int type) {
    Image img = null;
    if (type == BeanInfo.ICON_COLOR_16x16) {
        img = findIcon("Nb.Explorer.Folder.icon", "Tree.closedIcon"); //NOI18N
    }
    if (img == null) {
        img = super.getIcon(type);
    }
    return img;
}
 
Example 49
Project: gate-core   File: AbstractResource.java   Source Code and License 5 votes vote down vote up
public static BeanInfo getBeanInfo(Class<? extends Resource> c) throws IntrospectionException {
  
  BeanInfo r = beanInfoCache.get(c);
  if(r == null) {
    r = Introspector.getBeanInfo(c, Object.class);
    beanInfoCache.put(c, r);
  }
  return r;
}
 
Example 50
Project: convertigo-eclipse   File: NewObjectWizardPage.java   Source Code and License 5 votes vote down vote up
public BeanInfo getCurrentSelectedBeanInfo() {
	BeanInfo bi = null;
	if (composite != null) {
		bi = ((ObjectsExplorerComposite)composite).getCurrentSelectedBeanInfo();
	}
	return bi;
}
 
Example 51
Project: tk-mybatis   File: FieldHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 通过方法获取属性
 *
 * @param entityClass
 * @return
 */
public List<EntityField> getProperties(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = _getGenericTypeMap(entityClass);
    List<EntityField> entityFields = new ArrayList<EntityField>();
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
    } catch (IntrospectionException e) {
        throw new MapperException(e);
    }
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor desc : descriptors) {
        if (desc != null && !"class".equals(desc.getName())) {
            EntityField entityField = new EntityField(null, desc);
            if (desc.getReadMethod() != null
                    && desc.getReadMethod().getGenericReturnType() != null
                    && desc.getReadMethod().getGenericReturnType() instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getReadMethod().getGenericReturnType()).getName()));
            } else if (desc.getWriteMethod() != null
                    && desc.getWriteMethod().getGenericParameterTypes() != null
                    && desc.getWriteMethod().getGenericParameterTypes().length == 1
                    && desc.getWriteMethod().getGenericParameterTypes()[0] instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getWriteMethod().getGenericParameterTypes()[0]).getName()));
            }
            entityFields.add(entityField);
        }
    }
    return entityFields;
}
 
Example 52
Project: jaffa-framework   File: PropertyFilter.java   Source Code and License 5 votes vote down vote up
private static void getFieldList(Class clazz, List<String> fieldList, String prefix, Deque<Class> classStack) throws IntrospectionException {
    //To avoid recursion, bail out if the input Class has already been introspected
    if (classStack.contains(clazz)) {
        if (log.isDebugEnabled())
            log.debug("Fields from " + clazz + " prefixed by " + prefix + " will be ignored, since the class has already been introspected as per the stack " + classStack);
        return;
    } else
        classStack.addFirst(clazz);

    //Introspect the input Class
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    String name = pd.getName();
                    String qualifieldName = prefix == null || prefix.length() == 0 ? name : prefix + '.' + name;
                    Class type = pd.getPropertyType();
                    if (type.isArray())
                        type = type.getComponentType();
                    if (type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type) || IDateBase.class.isAssignableFrom(type) || Currency.class.isAssignableFrom(type) || type.isPrimitive() || type.isEnum())
                        fieldList.add(qualifieldName);
                    else
                        getFieldList(type, fieldList, qualifieldName, classStack);
                }
            }
        }
    }

    classStack.removeFirst();
}
 
Example 53
Project: incubator-netbeans   File: BIDataLoaderBeanInfo.java   Source Code and License 5 votes vote down vote up
@Override
public BeanInfo[] getAdditionalBeanInfo() {
    try {
        return new BeanInfo[]{Introspector.getBeanInfo(UniFileLoader.class)};
    } catch (IntrospectionException e) {
        throw new AssertionError(e);
    }
}
 
Example 54
Project: neoscada   File: VariantBeanHelper.java   Source Code and License 5 votes vote down vote up
private static PropertyDescriptor findDescriptor ( final BeanInfo bi, final String propertyName )
{
    for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
    {
        if ( pd.getName ().equals ( propertyName ) )
        {
            return pd;
        }
    }
    return null;
}
 
Example 55
Project: incubator-netbeans   File: AsynchronousTest.java   Source Code and License 5 votes vote down vote up
private void inspectNode(Node n) {
    n.getDisplayName();
    n.getHtmlDisplayName();
    n.getShortDescription();
    n.getIcon(BeanInfo.ICON_COLOR_16x16);
    n.canCopy();
    n.canCut();
    n.canRename();
    n.getNewTypes();
    n.getActions(true);
    n.getPreferredAction();
    inspectProperties(n);
}
 
Example 56
Project: incubator-netbeans   File: CommandCompletionProvider.java   Source Code and License 5 votes vote down vote up
@Override
protected ImageIcon getIcon() {
    if (insertText.endsWith("/")) { // NOI18N
        return ImageUtilities.loadImageIcon(ICON_FOLDER, false);
    } else if (fileResource != null) {
        return ImageUtilities.loadImageIcon(fileResource, true);
    } else if (icon != null) {
        return icon;
    } else {
        Path p = basePath.resolve(insertText);
        if (p != null) {
            FileObject f = FileUtil.toFileObject(p.toFile());
            if (f != null) {
                Node n;
                
                try {
                    DataObject d = DataObject.find(f);
                    n = d.getNodeDelegate();
                } catch (DataObjectNotFoundException ex) {
                    n = f.getLookup().lookup(Node.class);
                }
                if (n != null) {
                    return (ImageIcon)ImageUtilities.image2Icon(n.getIcon(BeanInfo.ICON_COLOR_16x16));
                }
            }
        }
        return icon = ImageUtilities.loadImageIcon(ICON_FILE, false);
    }
}
 
Example 57
Project: incubator-netbeans   File: FileSystemStatus.java   Source Code and License 5 votes vote down vote up
private Image annotateIcon(FileObject fo, int type) {
    String attr = null;
    if (type == BeanInfo.ICON_COLOR_16x16) {
        attr = "SystemFileSystem.icon"; // NOI18N
    } else if (type == BeanInfo.ICON_COLOR_32x32) {
        attr = "SystemFileSystem.icon32"; // NOI18N
    }
    if (attr != null) {
        Object value = fo.getAttribute(attr);
        if (value != null) {
            if (value instanceof URL) {
                return Toolkit.getDefaultToolkit().getImage((URL) value);
            } else if (value instanceof Image) {
                // #18832
                return (Image) value;
            } else {
                LOG.warning("Attribute " + attr + " on " + fo + " expected to be a URL or Image; was: " + value);
            }
        }
    }
    String base = (String) fo.getAttribute("iconBase"); // NOI18N
    if (base != null) {
        if (type == BeanInfo.ICON_COLOR_16x16) {
            return ImageUtilities.loadImage(base, true);
        } else if (type == BeanInfo.ICON_COLOR_32x32) {
            return ImageUtilities.loadImage(insertBeforeSuffix(base, "_32"), true); // NOI18N
        }
    }
    return null;
}
 
Example 58
Project: pipelines   File: UntypedOccurrenceBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public UntypedOccurrence apply(ExtendedRecord record) {
  UntypedOccurrence parsed = new UntypedOccurrence();
  parsed.setOccurrenceId(record.getId());

  // rewrite only to enable lookup by String
  Map<String,String> termsAsString = new HashMap<>();
  record.getCoreTerms().forEach((k,v)-> termsAsString.put(k.toString(), v.toString()));

  // set all DwC fields on the UntypedOccurrence
  try {
    BeanInfo info = Introspector.getBeanInfo(UntypedOccurrence.class);
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
      if (pd.getWriteMethod() != null) {
        String term = pd.getName();
        String value = termsAsString.get(DwcTerm.NS + term);
        if (value != null) {
          pd.getWriteMethod().invoke(parsed, value);
        }
      }
    }
    return parsed;
  } catch (Exception e) {
    throw new RuntimeException("Unable to introspect UntypedOccurrence", e);

  }
}
 
Example 59
Project: jaffa-framework   File: BeanHelper.java   Source Code and License 5 votes vote down vote up
/** This method will introspect the beanClass & get the getter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * @param beanClass The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be converted.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalArgumentException if the property cannot be found on the input class.
 * @throws ClassCastException if the input value can't be mapped to target class
 * @return a converted propertyValue compatible with the getter.
 * @deprecated Use DataTypeMapper.instance() instead.
 */
public static Object convertDataType(Class beanClass, String propertyName, String propertyValue)
throws IntrospectionException, IllegalArgumentException, ClassCastException {
    Object convertedPropertyValue = null;
    if (propertyValue != null) {
        boolean foundProperty = false;
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        foundProperty = true;
                        if (pd.getPropertyType().isEnum()) {
                            convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString());
                            if (convertedPropertyValue == null)
                                throw new IllegalArgumentException("Property " + beanClass.getName() + '.' + propertyName + ", cannot be set to the value " + propertyValue + ", since it is not defined in the Enum " + pd.getPropertyType());
                        } else {
                            convertedPropertyValue = DataTypeMapper.instance().map(propertyValue, pd.getPropertyType());
                        }
                        break;
                    }
                }
            }
        }
        if (!foundProperty)
            throw new IllegalArgumentException("Could not find the the property: " + beanClass.getName() + '.' + propertyName);
    }
    return convertedPropertyValue;
}
 
Example 60
Project: jdk8u-jdk   File: Test4168475.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    Introspector.setBeanInfoSearchPath(PATH);
    BeanInfo info = Introspector.getBeanInfo(Component.class);
    PropertyDescriptor[] pds = info.getPropertyDescriptors();

    // The custom ComponentBeanInfo we deliver
    // only provides a single property.

    if (pds.length != 1) {
        throw new Error("wrong number of properties");
    }
    if (!pds[0].getName().equals("name")) {
        throw new Error("unexpected property name");
    }
}