public static void copyProperties(Object target, Object source, String[] ignoreProperties) { if (target instanceof Map) { throw new UnsupportedOperationException("target is Map unsuported"); } PropertyDescriptor[] targetPds = getPropertyDescriptors(target.getClass()); List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; for (int i = 0; i < targetPds.length; i++) { PropertyDescriptor targetPd = targetPds[i]; if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { try { if (source instanceof Map) { Map map = (Map) source; if (map.containsKey(targetPd.getName())) { Object value = map.get(targetPd.getName()); setProperty(target, targetPd, value); } } else { PropertyDescriptor sourcePd = getPropertyDescriptors(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { Object value = getProperty(source, sourcePd); setProperty(target, targetPd, value); } } } catch (Throwable ex) { throw new IllegalArgumentException( "Could not copy properties on:" + targetPd.getDisplayName(), ex); } } } }
private static MenuManager generateBooleanEditorFor( final IMenuManager manager, final MenuManager subMenu, final PropertyDescriptor thisP, final Editable[] editables, final Layers theLayers, final Layer topLevelLayer) { boolean currentVal = false; final Method getter = thisP.getReadMethod(); final Method setter = thisP.getWriteMethod(); MenuManager result = subMenu; try { final Boolean valNow = (Boolean) getter.invoke(editables[0], (Object[]) null); currentVal = valNow.booleanValue(); } catch (final Exception e) { CorePlugin.logError( Status.ERROR, "Failed to retrieve old value for:" + editables[0].getName(), e); } final IAction changeThis = new Action(thisP.getDisplayName(), IAction.AS_CHECK_BOX) { public void run() { try { final ListPropertyAction la = new ListPropertyAction( thisP.getDisplayName(), editables, getter, setter, new Boolean(isChecked()), theLayers, topLevelLayer); CorePlugin.run(la); } catch (final Exception e) { CorePlugin.logError(IStatus.INFO, "While executing boolean editor for:" + thisP, e); } } }; changeThis.setChecked(currentVal); changeThis.setToolTipText(thisP.getShortDescription()); // is our sub-menu already created? if (result == null) { String nameStr; if (editables.length > 1) nameStr = MULTIPLE_ITEMS_STR; else nameStr = editables[0].getName(); result = new MenuManager(nameStr); manager.add(result); } result.add(changeThis); return result; }
private PropertyDescriptor getPropertyByName(String propName) { for (int i = 0; i < properties_.length; i++) { PropertyDescriptor prop = properties_[i]; if (propName.equals(prop.getDisplayName()) || propName.equals(prop.getName())) { return prop; } } return null; }
/** * Called by {@link #createChangeMetaData()} to create metadata for a given parameter. It finds * the method that corresponds to the parameter and calls the corresponding create*MetaData * methods such as {@link #createRequiredDatabasesMetaData(String, DatabaseChangeProperty)} to * determine the correct values for the ChangeParameterMetaData fields. * * @throws UnexpectedLiquibaseException if the passed parameter does not exist */ protected ChangeParameterMetaData createChangeParameterMetadata(String parameterName) { try { String displayName = parameterName.replaceAll("([A-Z])", " $1"); displayName = displayName.substring(0, 1).toUpperCase() + displayName.substring(1); PropertyDescriptor property = null; for (PropertyDescriptor prop : Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors()) { if (prop.getDisplayName().equals(parameterName)) { property = prop; break; } } if (property == null) { throw new UnexpectedLiquibaseException("Could not find property " + parameterName); } Method readMethod = property.getReadMethod(); if (readMethod == null) { readMethod = getClass().getMethod("is" + StringUtils.upperCaseFirst(property.getName())); } Type type = readMethod.getGenericReturnType(); DatabaseChangeProperty changePropertyAnnotation = readMethod.getAnnotation(DatabaseChangeProperty.class); String mustEqualExisting = createMustEqualExistingMetaData(parameterName, changePropertyAnnotation); String description = createDescriptionMetaData(parameterName, changePropertyAnnotation); Map<String, Object> examples = createExampleValueMetaData(parameterName, changePropertyAnnotation); String since = createSinceMetaData(parameterName, changePropertyAnnotation); SerializationType serializationType = createSerializationTypeMetaData(parameterName, changePropertyAnnotation); String[] requiredForDatabase = createRequiredDatabasesMetaData(parameterName, changePropertyAnnotation); String[] supportsDatabase = createSupportedDatabasesMetaData(parameterName, changePropertyAnnotation); return new ChangeParameterMetaData( this, parameterName, displayName, description, examples, since, type, requiredForDatabase, supportsDatabase, mustEqualExisting, serializationType); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }
/** * getDisplayName purpose. * * <p>This is used to provide the locale to the property descriptor if it is required. This method * is thread safe. * * <p>This method must be both synchornized and static. The global locale is maintained from start * to completion of execution, even when an unexpected exception occurs. * * @param pd PropertyDescriptor to get the display name from * @param locale Locale to use if required. * @return String the Display Name */ public static synchronized String getDisplayName(PropertyDescriptor pd) { String r = ""; try { // to safely reset the locale. r = pd.getDisplayName(); } finally { } return r; }
@SuppressWarnings({"rawtypes"}) private EditorHelper findHelperFor(PropertyDescriptor prop, Editable subject) { EditorHelper res = null; // is there an explicit editor specified? Class specificEditor = prop.getPropertyEditorClass(); // did we find one? if (specificEditor != null) { Object theEditor = null; try { theEditor = specificEditor.newInstance(); } catch (Exception e) { CorePlugin.logError(Status.ERROR, "whilst finding helper", e); } if (theEditor instanceof java.beans.PropertyEditor) { final java.beans.PropertyEditor propEditor = (java.beans.PropertyEditor) theEditor; // ok. wrap it. if (!(propEditor instanceof DoNotUseTagEditorInPropertiesView)) { if (propEditor.getTags() != null) { // ok - do one of the combo-box editor types final String[] theTags = propEditor.getTags(); res = new TagListHelper(theTags, propEditor); } } } } if (res == null) { // ok, find the type of object we're working with Class rawClass = EditableWrapper.getPropertyClass(_thisProp); for (Iterator iter = _myHelperList.iterator(); iter.hasNext(); ) { EditorHelper thisHelper = (EditorHelper) iter.next(); if (thisHelper.editsThis(rawClass)) { res = thisHelper; break; } } if (res == null) { // ok, log the error String msg = "editor not found for:" + EditableWrapper.getPropertyClass(prop) + "(" + prop.getDisplayName() + ")"; System.out.println(msg); } } return res; }
/** * Generate the ChangeMetaData for this class. Default implementation reads from the @{@link * DatabaseChange } annotation and calls out to {@link #createChangeParameterMetadata(String)} for * each property. * * @throws UnexpectedLiquibaseException if no @DatabaseChange annotation on this Change class */ @Override public ChangeMetaData createChangeMetaData() { try { DatabaseChange databaseChange = this.getClass().getAnnotation(DatabaseChange.class); if (databaseChange == null) { throw new UnexpectedLiquibaseException( "No @DatabaseChange annotation for " + getClass().getName()); } Set<ChangeParameterMetaData> params = new HashSet<ChangeParameterMetaData>(); for (PropertyDescriptor property : Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors()) { if (isInvalidProperty(property)) { continue; } Method readMethod = property.getReadMethod(); Method writeMethod = property.getWriteMethod(); if (readMethod == null) { try { readMethod = this.getClass().getMethod("is" + StringUtils.upperCaseFirst(property.getName())); } catch (Exception ignore) { // it was worth a try } } if (readMethod != null && writeMethod != null) { DatabaseChangeProperty annotation = readMethod.getAnnotation(DatabaseChangeProperty.class); if (annotation == null || annotation.isChangeProperty()) { params.add(createChangeParameterMetadata(property.getDisplayName())); } } } Map<String, String> notes = new HashMap<String, String>(); for (DatabaseChangeNote note : databaseChange.databaseNotes()) { notes.put(note.database(), note.notes()); } return new ChangeMetaData( databaseChange.name(), databaseChange.description(), databaseChange.priority(), databaseChange.appliesTo(), notes, params); } catch (Throwable e) { throw new UnexpectedLiquibaseException(e); } }
/** * Creates a description for the attribute corresponding to this property descriptor. Attempts to * create the description using metadata from either the getter or setter attributes, otherwise * uses the property name. */ protected String getAttributeDescription(PropertyDescriptor propertyDescriptor, String beanKey) { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); ManagedAttribute getter = (readMethod != null) ? this.attributeSource.getManagedAttribute(readMethod) : null; ManagedAttribute setter = (writeMethod != null) ? this.attributeSource.getManagedAttribute(writeMethod) : null; if (getter != null && StringUtils.hasText(getter.getDescription())) { return getter.getDescription(); } else if (setter != null && StringUtils.hasText(setter.getDescription())) { return setter.getDescription(); } return propertyDescriptor.getDisplayName(); }
public Object getRawValue() { Object res = null; try { // find out the type of the editor Method m = _thisProp.getReadMethod(); if (m == null) { System.out.println("tripped, prop was:" + _thisProp.getDisplayName()); } else { res = m.invoke(_subject, (Object[]) null); } } catch (Exception e) { MWC.Utilities.Errors.Trace.trace(e); } return res; }
/** * Constructs a bean view that views the specified class. * * @param viewedClass the viewed class * @throws IntrospectionException if bean introspection fails * @see Introspector#getBeanInfo(Class) */ public BeanForm(final Class<T> viewedClass) throws IntrospectionException { final GroupLayoutBuilder builder = new GroupLayoutBuilder(this); this.beanInfo = Introspector.getBeanInfo(viewedClass); for (final PropertyDescriptor pd : this.beanInfo.getPropertyDescriptors()) { final PropertyEditor editor = PropertyEditorManager.findEditor(pd.getPropertyType()); if (editor == null) { continue; } final JTextField textField = new JTextField(); textField.setEditable(false); textField.setText(editor.getAsText()); this.fieldMap.put(pd.getName(), textField); builder.field(pd.getDisplayName(), textField); } builder.build(); }
private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source) throws MergerException { try { BeanInfo beanInfo = Introspector.getBeanInfo(targetClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method getter = propertyDescriptor.getReadMethod(); Method setter = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getDisplayName(); if (PropertyUtils.isWriteable(target, propertyName)) { // check for mergeCollection MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter); if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { PropertyUtils.setProperty( target, propertyName, mergeList(mergeCollection, propertyName, target, source)); } // check for merge Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter); PropertyUtils.setProperty( target, propertyName, mergeProperties(mergeAnnotation, propertyName, target, source)); } } } catch (NoSuchMethodException e) { throw new MergerException("NoSuchMethodException while trying to merge", e); } catch (IntrospectionException e) { throw new MergerException("IntrospectionException while trying to merge", e); } catch (IllegalAccessException e) { throw new MergerException("IllegalAccessException while trying to merge", e); } catch (InvocationTargetException e) { throw new MergerException("InvocationTargetException while trying to merge", e); } return target; }
private void addProperty( PropertyDescriptor propertyDescriptor, JComponent editor, GridBagLayout grid) { String text = propertyDescriptor.getDisplayName(); String newText = ""; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (((c >= 'A') && (c <= 'Z')) || (i == 0)) { if (i == 0) { c += ('A' - 'a'); } newText += (" " + c); } else { newText += c; } } JLabel label = new JLabel(newText + ": ", null, JLabel.RIGHT); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.fill = GridBagConstraints.BOTH; grid.setConstraints(label, c); propertyPanel.add(label); c.gridwidth = GridBagConstraints.REMAINDER; grid.setConstraints(editor, c); propertyPanel.add(editor); JPanel blankLine = new JPanel() { private static final long serialVersionUID = 4514530330521503732L; public Dimension getPreferredSize() { return new Dimension(10, 2); } }; grid.setConstraints(blankLine, c); propertyPanel.add(blankLine); }
/* * see java.beans.FeatureDescriptor#FeatureDescriptor(FeatureDescriptor) */ public static void copyNonMethodProperties(PropertyDescriptor source, PropertyDescriptor target) throws IntrospectionException { target.setExpert(source.isExpert()); target.setHidden(source.isHidden()); target.setPreferred(source.isPreferred()); target.setName(source.getName()); target.setShortDescription(source.getShortDescription()); target.setDisplayName(source.getDisplayName()); // copy all attributes (emulating behavior of private FeatureDescriptor#addTable) Enumeration<String> keys = source.attributeNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); target.setValue(key, source.getValue(key)); } // see java.beans.PropertyDescriptor#PropertyDescriptor(PropertyDescriptor) target.setPropertyEditorClass(source.getPropertyEditorClass()); target.setBound(source.isBound()); target.setConstrained(source.isConstrained()); }
public static List<AttributeDefinition> buildAttributesList(Class<?> theClass) { List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(theClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getWriteMethod() == null || !Modifier.isPublic(propertyDescriptor.getWriteMethod().getModifiers())) { continue; } Builder builder = AttributeDefinition.builder(new PassThroughStringLocalizer()) .id(propertyDescriptor.getName()) .name(propertyDescriptor.getDisplayName()) .description(propertyDescriptor.getShortDescription()); addEnumValues(propertyDescriptor.getPropertyType(), builder); AttributeDefinition a = builder.build(); attributes.add(a); } } catch (IntrospectionException ex) { LOGGER.error("building attribute list failed", ex); } return attributes; }
public CassandraConfigElementBeanInfo() { super(CassandraConfigElement.class); createPropertyGroup("cassandra", new String[] {"connectionId", "host", "port", "cluster"}); createPropertyGroup( "hostconfig", new String[] { "thriftSocketTimeout", "retryDownedHostDelaySec", "retryDownedHostQueueSize", "maxWaitTimeIfExhausted", "retryDownedHosts", "loadBalancingPolicy", "setAutoDiscoverHosts", "setHostTimeoutCounter" }); PropertyDescriptor p = property("connectionId"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "cassConn"); p = property("host"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "cloudssd-cassandra.cern.ch"); p = property("port"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "9160"); p = property("cluster"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "TestCondCass"); p = property("thriftSocketTimeout"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "10000"); p = property("retryDownedHostDelaySec"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "30"); p = property("retryDownedHostQueueSize"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "128"); p = property("maxWaitTimeIfExhausted"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "60000"); p = property("retryDownedHosts"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, Boolean.TRUE); p = property("loadBalancingPolicy"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "leastActive"); p = property("setAutoDiscoverHosts"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, Boolean.TRUE); p = property("setHostTimeoutCounter"); p.setValue(NOT_UNDEFINED, Boolean.TRUE); p.setValue(DEFAULT, "20"); if (log.isDebugEnabled()) { for (PropertyDescriptor pd : getPropertyDescriptors()) { log.debug(pd.getName()); log.debug(pd.getDisplayName()); } } }
public String getFullName() { return _relatedPropertyDescriptor == null ? "<none>" : _relatedBeanClass.getSimpleName() + "." + _relatedPropertyDescriptor.getDisplayName(); }
public String getName() { return _relatedPropertyDescriptor == null ? "<none>" : _relatedPropertyDescriptor.getDisplayName(); }
public Object getId() { return _thisProp.getDisplayName(); }
private static JasperDesign getJasperDesign(List<PropertyDescriptor> props) throws JRException { // JasperDesign JasperDesign jasperDesign = new JasperDesign(); jasperDesign.setName("NoXmlDesignReport"); jasperDesign.setPageWidth(595); jasperDesign.setPageHeight(842); jasperDesign.setColumnWidth(515); jasperDesign.setColumnSpacing(0); jasperDesign.setColumnCount(1); jasperDesign.setLeftMargin(40); jasperDesign.setRightMargin(40); jasperDesign.setTopMargin(50); jasperDesign.setBottomMargin(50); // Fonts JRDesignStyle normalStyle = new JRDesignStyle(); normalStyle.setName("Sans_Normal"); normalStyle.setDefault(true); normalStyle.setFontName("DejaVu Sans"); normalStyle.setFontSize(12); normalStyle.setPdfFontName("Helvetica"); normalStyle.setPdfEncoding("Cp1252"); normalStyle.setPdfEmbedded(false); jasperDesign.addStyle(normalStyle); JRDesignStyle boldStyle = new JRDesignStyle(); boldStyle.setName("Sans_Bold"); boldStyle.setFontName("DejaVu Sans"); boldStyle.setFontSize(12); boldStyle.setBold(true); boldStyle.setPdfFontName("Helvetica-Bold"); boldStyle.setPdfEncoding("Cp1252"); boldStyle.setPdfEmbedded(false); jasperDesign.addStyle(boldStyle); JRDesignStyle italicStyle = new JRDesignStyle(); italicStyle.setName("Sans_Italic"); italicStyle.setFontName("DejaVu Sans"); italicStyle.setFontSize(12); italicStyle.setItalic(true); italicStyle.setPdfFontName("Helvetica-Oblique"); italicStyle.setPdfEncoding("Cp1252"); italicStyle.setPdfEmbedded(false); jasperDesign.addStyle(italicStyle); // Parameters JRDesignParameter parameter = new JRDesignParameter(); parameter.setName("ReportTitle"); parameter.setValueClass(java.lang.String.class); jasperDesign.addParameter(parameter); // Fields int i = 1; for (PropertyDescriptor p : props) { JRDesignField field = new JRDesignField(); field.setName(p.getName()); field.setValueClass(resolveType(p)); jasperDesign.addField(field); i++; } // Title JRDesignBand band = new JRDesignBand(); band.setHeight(50); JRDesignTextField textField = new JRDesignTextField(); textField.setBlankWhenNull(true); textField.setX(0); textField.setY(20); textField.setWidth(510); textField.setHeight(30); textField.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); textField.setStyle(normalStyle); textField.setFontSize(22); JRDesignExpression expression = new JRDesignExpression(); expression.setValueClass(java.lang.String.class); expression.setText("$P{ReportTitle}"); textField.setExpression(expression); band.addElement(textField); jasperDesign.setTitle(band); // Page header band = new JRDesignBand(); band.setHeight(20); int x = 0; for (PropertyDescriptor p : props) { JRDesignStaticText staticText = new JRDesignStaticText(); staticText.setX(x); staticText.setY(0); if (p.getName().equals("message")) { staticText.setWidth(400); x += 400; } else { staticText.setWidth(100); x += 100; } staticText.setHeight(20); staticText.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); staticText.setVerticalAlignment(JRAlignment.VERTICAL_ALIGN_MIDDLE); staticText.setStyle(boldStyle); staticText.setStretchType(JRDesignStaticText.STRETCH_TYPE_RELATIVE_TO_TALLEST_OBJECT); staticText.setText(p.getDisplayName()); band.addElement(staticText); } jasperDesign.setPageHeader(band); // Column header band = new JRDesignBand(); jasperDesign.setColumnHeader(band); band = new JRDesignBand(); band.setHeight(25); x = 0; for (PropertyDescriptor p : props) { textField = new JRDesignTextField(); textField.setX(x); textField.setY(0); if (p.getName().equals("message")) { textField.setWidth(400); x += 400; } else { textField.setWidth(100); x += 100; } textField.setHeight(20); textField.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); textField.setVerticalAlignment(JRAlignment.VERTICAL_ALIGN_MIDDLE); textField.setStyle(normalStyle); expression = new JRDesignExpression(); Class type = resolveType(p); expression.setValueClass(type); expression.setText("$F{" + p.getName() + "}"); textField.setExpression(expression); textField.setStretchWithOverflow(true); band.addElement(textField); } jasperDesign.setDetail(band); // Column footer band = new JRDesignBand(); jasperDesign.setColumnFooter(band); // Page footer band = new JRDesignBand(); jasperDesign.setPageFooter(band); // Summary band = new JRDesignBand(); jasperDesign.setSummary(band); return jasperDesign; }
/** * @param prop * @param value * @return */ public static PropertyEditor findEditor(PropertyDescriptor prop, Object value) { PropertyEditor editor = null; Class pec = prop.getPropertyEditorClass(); Class type = prop.getPropertyType(); try { if (pec != null) { editor = (PropertyEditor) pec.newInstance(); } } catch (Exception e) { editor = null; } if (editor == null) { if (value != null) { // Try to unwrap primitives if (Primitives.isWrapperType(value.getClass())) { editor = PropertyEditorManager.findEditor(Primitives.unwrap(value.getClass())); } else { editor = PropertyEditorManager.findEditor(value.getClass()); } } if (editor == null && (BeanInspector.isJavaPrimitive(value.getClass()))) { Class<?> prim = BeanInspector.getBoxedType(value.getClass()); if (prim != null) { editor = PropertyEditorManager.findEditor(prim); } if (editor == null) { prim = BeanInspector.getUnboxedType(value.getClass()); if (prim != null) { editor = PropertyEditorManager.findEditor(prim); } } } if (editor == null) { editor = PropertyEditorManager.findEditor(type); } if ((editor == null) && useDefaultGOE) { if (type.isArray()) { Class<?> unwrapped = Primitives.isWrapperType(type.getComponentType()) ? Primitives.unwrap(type.getComponentType()) : type; if (unwrapped.isPrimitive()) { editor = new ArrayEditor(); } else { editor = new ObjectArrayEditor<>(unwrapped.getComponentType()); } } else if (type.isEnum()) { editor = new EnumEditor(); } else { editor = new GenericObjectEditor(); ((GenericObjectEditor) editor).setClassType(type); } } } if (editor == null) { // If it's a user-defined property we give a warning. String getterClass = prop.getReadMethod().getDeclaringClass().getName(); if (getterClass.indexOf("java.") != 0) { System.err.println( "Warning: Can't find public property editor" + " for property \"" + prop.getDisplayName() + "\" (class \"" + type.getName() + "\"). Skipping."); } } else if (editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor).setClassType(type); } return editor; }
private static <T> T parseElementWithChildren( XMLStreamReader reader, String element, Class<T> clazz) throws XMLStreamException, IllegalAccessException, InstantiationException, IntrospectionException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { Stack<String> stack = new Stack<String>(); Map<Method, List<Object>> listMap = new HashMap<Method, List<Object>>(); String temValue = null; T obj = clazz.newInstance(); // parse attribute if (element != null && !element.isEmpty()) { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { String attrName = property.getDisplayName(); String attrValue = reader.getAttributeValue(null, attrName); if (attrValue != null && !attrValue.isEmpty()) { Method setter = property.getWriteMethod(); Class<?> type = property.getPropertyType(); if (String.class.isAssignableFrom(type)) { setter.invoke(obj, attrValue); } else if (Integer.class.isAssignableFrom(type)) { setter.invoke(obj, Integer.parseInt(attrValue)); } else if (Long.class.isAssignableFrom(type)) { setter.invoke(obj, Long.parseLong(attrValue)); } else if (Float.class.isAssignableFrom(type)) { setter.invoke(obj, Float.parseFloat(attrValue)); } else if (Double.class.isAssignableFrom(type)) { setter.invoke(obj, Double.parseDouble(attrValue)); } else if (Boolean.class.isAssignableFrom(type)) { setter.invoke(obj, Boolean.parseBoolean(attrValue)); } else if (Date.class.isAssignableFrom(type)) { try { setter.invoke(obj, DateUtil.parseDateWithDataBase(attrValue)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } while (reader.hasNext()) { reader.next(); int event = reader.getEventType(); if (XMLStreamConstants.START_ELEMENT == event) { String startElement = reader.getLocalName(); boolean isInstanceType = false; // from xml, check if the element has children elements; // to the object, check if the related property is user defined type. for (PropertyDescriptor property : getInstanceTypeProperties(clazz)) { if (startElement.equalsIgnoreCase(property.getDisplayName())) { Class<?> type = property.getPropertyType(); Method setter = property.getWriteMethod(); isInstanceType = true; Object child = parseElementWithChildren(reader, startElement, type); setter.invoke(obj, child); break; } } // generic type should not be the primary type! for (PropertyDescriptor property : getListTypeProperties(clazz)) { // support the plural as well String propertyName = property.getDisplayName(); if (startElement.equalsIgnoreCase(propertyName) || (startElement + "s").equalsIgnoreCase(propertyName) || (startElement + "es").equalsIgnoreCase(propertyName)) { Method setter = property.getWriteMethod(); ParameterizedType genericType = (ParameterizedType) property.getReadMethod().getGenericReturnType(); Type[] types = genericType.getActualTypeArguments(); if (types.length == 1) { List<Object> list = listMap.get(setter); if (list == null) { list = new ArrayList<Object>(); listMap.put(setter, list); } Class<?> listGenericClass = (Class<?>) types[0]; Object child = parseElementWithChildren(reader, startElement, listGenericClass); list.add(child); } isInstanceType = true; break; } } // the root element and the elements with children won't be put into stack. if (!startElement.equals(element) && !isInstanceType) { stack.push(startElement); } } else if (XMLStreamConstants.CHARACTERS == event) { temValue = reader.getText(); } else if (XMLStreamConstants.END_ELEMENT == event) { String endElement = reader.getLocalName(); // stop parsing when meeting the end of the root element if (endElement.equals(element)) { break; } // retrieve the element with value and match the object property. if (endElement.equals(stack.pop()) && stack.isEmpty()) { for (PropertyDescriptor property : getStringTypeProperties(clazz)) { if (endElement.equalsIgnoreCase(property.getDisplayName())) { Method setter = property.getWriteMethod(); setter.invoke(obj, temValue); break; } } } } } if (listMap.size() > 0) { for (Map.Entry<Method, List<Object>> entry : listMap.entrySet()) { Method setter = entry.getKey(); List<Object> li = entry.getValue(); setter.invoke(obj, li); } } return obj; }
@SuppressWarnings("rawtypes") private static MenuManager generateListEditorFor( final IMenuManager manager, final MenuManager subMenu, final PropertyDescriptor thisP, final Editable[] editables, final Layers theLayers, final Layer topLevelLayer) { // find out the type of the editor final Method m = thisP.getReadMethod(); final Class cl = m.getReturnType(); MenuManager result = subMenu; // is there a custom editor for this type? final Class c = thisP.getPropertyEditorClass(); PropertyEditor pe = null; // try to create an editor for this class try { if (c != null) pe = (PropertyEditor) c.newInstance(); } catch (final Exception e) { MWC.Utilities.Errors.Trace.trace(e); } // did it work? if (pe == null) { // try to find an editor for this through our manager pe = PropertyEditorManager.findEditor(cl); } // retrieve the tags final String[] tags = pe.getTags(); // are there any tags for this class? if (tags != null) { // create a drop-down list final MenuManager thisChoice = new MenuManager(thisP.getDisplayName()); // sort out the setter details final Method getter = thisP.getReadMethod(); // get the current value Object val = null; try { val = getter.invoke(editables[0], (Object[]) null); } catch (final Exception e) { MWC.Utilities.Errors.Trace.trace(e); } pe.setValue(val); // convert the current value to text final String currentValue = pe.getAsText(); // and now a drop-down item for each options for (int j = 0; j < tags.length; j++) { final String thisTag = tags[j]; pe.setAsText(thisTag); final Object thisValue = pe.getValue(); // create the item final IAction thisA = new Action(thisTag, IAction.AS_RADIO_BUTTON) { public void run() { try { // hey, since this is a radio button, we get two events when the // selection changes - one for the value being unset, and the // other // for the value being set. So just fire for the new value (the // one that's checked) if (isChecked()) { final Method setter = thisP.getWriteMethod(); // ok, place the change in the action final ListPropertyAction la = new ListPropertyAction( thisP.getDisplayName(), editables, getter, setter, thisValue, theLayers, topLevelLayer); // and add it to the history CorePlugin.run(la); } } catch (final Exception e) { CorePlugin.logError( IStatus.INFO, "While executing select editor for:" + thisP, e); } } }; // is this the current one? if (thisTag.equals(currentValue)) { thisA.setChecked(true); } // add it to the menu thisChoice.add(thisA); } // is our sub-menu already created? if (result == null) { String nameStr; if (editables.length > 1) nameStr = MULTIPLE_ITEMS_STR; else nameStr = editables[0].getName(); result = new MenuManager(nameStr); manager.add(result); } result.add(thisChoice); } return result; }
protected boolean isInvalidProperty(PropertyDescriptor property) { return property.getDisplayName().equals("metaClass"); }
/** * Get human readable title of the property (one that can be put into GUI). * * @return human readable title of the property (one that can be put into GUI). */ public String getTitle() { return propertyDescriptor.getDisplayName(); }
public String getDisplayName() { return _thisProp.getDisplayName(); }