List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
From source file:eagle.query.aggregate.timeseries.AbstractAggregator.java
protected String createGroupFromQualifiers(TaggedLogAPIEntity entity, String groupbyField, int i) { try {//from w w w .j a v a2s.c o m PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(entity, groupbyField); if (pd == null) return null; // _groupbyFieldPlacementCache.put(groupbyField, false); _groupbyFieldPlacementCache[i] = false; return (String) (pd.getReadMethod().invoke(entity)); } catch (NoSuchMethodException ex) { return null; } catch (InvocationTargetException ex) { return null; } catch (IllegalAccessException ex) { return null; } }
From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { Element root = document.getDocumentElement(); Document post = null;//from ww w.ja v a 2s . c o m Element response = document.createElement("response"); try { Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get .getDatabaseObjectByQName(request); xpath = new TwsCachedXPathAPI(); post = XMLUtils.parseDOM(request.getInputStream()); postElt = document.importNode(post.getFirstChild(), true); String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue(); DatabaseObject object = map.get(objectQName); // String comment = getPropertyValue(object, "comment").toString(); // object.setComment(comment); if (object instanceof Project) { Project project = (Project) object; String objectNewName = getPropertyValue(object, "name").toString(); Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName); map.remove(objectQName); map.put(project.getQName(), project); } BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); Method setter = propertyDescriptor.getWriteMethod(); Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType(); if (propertyTypeClass.isPrimitive()) { propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass); } try { String propertyValue = getPropertyValue(object, propertyName).toString(); Object oPropertyValue = createObject(propertyTypeClass, propertyValue); if (object.isCipheredProperty(propertyName)) { Method getter = propertyDescriptor.getReadMethod(); String initialValue = (String) getter.invoke(object, (Object[]) null); if (oPropertyValue.equals(initialValue) || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) { oPropertyValue = initialValue; } else { object.hasChanged = true; } } if (oPropertyValue != null) { Object args[] = { oPropertyValue }; setter.invoke(object, args); } } catch (IllegalArgumentException e) { } } Engine.theApp.databaseObjectsManager.exportProject(object.getProject()); response.setAttribute("state", "success"); response.setAttribute("message", "Project have been successfully updated!"); } catch (Exception e) { Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage()); response.setAttribute("state", "error"); response.setAttribute("message", "Error during saving the properties!"); Element stackTrace = document.createElement("stackTrace"); stackTrace.setTextContent(e.getMessage()); root.appendChild(stackTrace); } finally { xpath.resetCache(); } root.appendChild(response); }
From source file:org.codehaus.enunciate.modules.xfire_client.EnunciatedClientOperationBinding.java
public void readMessage(InMessage message, MessageContext context) throws XFireFault { if (this.responseInfo == null) { throw new XFireFault("Message cannot be read: no response info was found.", XFireFault.RECEIVER); }//from ww w . j a va 2 s. co m Service service = context.getService(); AegisBindingProvider provider = (AegisBindingProvider) service.getBindingProvider(); Class beanClass = this.responseInfo.getBeanClass(); Type type = provider.getType(service, beanClass); Object bean = type.readObject(new ElementReader(message.getXMLStreamReader()), context); List parameters = new ArrayList(); if (this.responseInfo.isBare()) { //if it's bare, the bean doesn't need to be unwrapped. parameters.add(bean); } else { //The operation is not bare, unwrap the bean. PropertyDescriptor[] pds = this.responseInfo.getPropertyOrder(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor descriptor = pds[i]; try { parameters.add(descriptor.getReadMethod().invoke(bean, null)); } catch (IllegalAccessException e) { throw new XFireFault( "Problem with property " + descriptor.getName() + " on " + beanClass.getName() + ".", e, XFireFault.RECEIVER); } catch (InvocationTargetException e) { throw new XFireFault( "Problem with property " + descriptor.getName() + " on " + beanClass.getName() + ".", e, XFireFault.RECEIVER); } } } message.setBody(parameters); }
From source file:com.opencsv.bean.StatefulBeanToCsv.java
/** * Writes a bean out to the {@link java.io.Writer} provided to the * constructor./*www . ja v a2 s . c o m*/ * * @param bean A bean to be written to a CSV destination * @throws CsvDataTypeMismatchException If a field of the bean is * annotated improperly or an unsupported data type is supposed to be * written * @throws CsvRequiredFieldEmptyException If a field is marked as required, * but the source is null */ public void write(T bean) throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException { if (bean != null) { ++lineNumber; beforeFirstWrite(bean); List<String> contents = new ArrayList<String>(); int numColumns = mappingStrategy.findMaxFieldIndex(); if (mappingStrategy.isAnnotationDriven()) { BeanField beanField; for (int i = 0; i <= numColumns; i++) { beanField = mappingStrategy.findField(i); try { String s = beanField != null ? beanField.write(bean) : ""; contents.add(StringUtils.defaultString(s)); } // Combine to a multi-catch once we support Java 7 catch (CsvDataTypeMismatchException e) { e.setLineNumber(lineNumber); if (throwExceptions) { throw e; } else { capturedExceptions.add(e); } } catch (CsvRequiredFieldEmptyException e) { e.setLineNumber(lineNumber); if (throwExceptions) { throw e; } else { capturedExceptions.add(e); } } } } else { PropertyDescriptor desc; for (int i = 0; i <= numColumns; i++) { try { desc = mappingStrategy.findDescriptor(i); Object o = desc != null ? desc.getReadMethod().invoke(bean, (Object[]) null) : null; contents.add(ObjectUtils.toString(o, "")); // Once we support Java 7 // contents.add(Objects.toString(o, "")); } // Combine in a multi-catch with Java 7 catch (IntrospectionException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } catch (IllegalAccessException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } catch (InvocationTargetException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } } } csvwriter.writeNext(contents.toArray(new String[contents.size()])); } }
From source file:org.archive.crawler.restlet.JobRelatedResource.java
/** * Starting at (and including) the given object, adds nested Map * representations of named beans to the {@code namedBeans} Collection. The * nested Map representations are particularly suitable for use with with * {@link XmlMarshaller}.// ww w. ja va 2s .c o m * * @param namedBeans * the Collection to add to * @param obj * object to make a presentable Map for, if it has a beanName * @param alreadyWritten * Set of objects already made presentable whose addition to * {@code namedBeans} should be suppressed */ protected void addPresentableNestedNames(Collection<Object> namedBeans, Object obj, Set<Object> alreadyWritten) { if (obj == null || alreadyWritten.contains(obj) || obj.getClass().getName().startsWith("org.springframework.")) { return; } Reference baseRef = getRequest().getResourceRef().getBaseRef(); if (baseRef.getPath().endsWith("beans")) { baseRef.setPath(baseRef.getPath() + "/"); } if (getBeanToNameMap().containsKey(obj)) { // this object is itself a named bean Map<String, Object> bean = new LinkedHashMap<String, Object>(); bean.put("name", getBeanToNameMap().get(obj)); bean.put("url", new Reference(baseRef, "../beans/" + getBeanToNameMap().get(obj)).getTargetRef()); bean.put("class", obj.getClass().getName()); namedBeans.add(bean); // nest children namedBeans = new LinkedList<Object>(); bean.put("children", namedBeans); } // alreadyWritten.contains() can fail on exception from hashCode() // method. For example, ArrayList.hashCode() iterates over elements // to compute hash. It can fail with ConcurrentModificationException. // We need to use a set based on object identity, instead of regular // java.util.Set which is equals-based. For now, error from contains() // is simply ignored (assuming not written). boolean writtenBefore = false; try { writtenBefore = alreadyWritten.contains(obj); } catch (Exception ex) { // pass } if (!writtenBefore) { alreadyWritten.add(obj); BeanWrapperImpl bwrap = new BeanWrapperImpl(obj); for (PropertyDescriptor pd : getPropertyDescriptors(bwrap)) { if (pd.getReadMethod() != null) { String propName = pd.getName(); try { Object propValue = bwrap.getPropertyValue(propName); addPresentableNestedNames(namedBeans, propValue, alreadyWritten); } catch (BeansException ex) { // getter may throw UnsupportedOperationException, for ex. // ignore such properties. } } } if (obj.getClass().isArray()) { List<?> list = Arrays.asList(obj); for (int i = 0; i < list.size(); i++) { addPresentableNestedNames(namedBeans, list.get(i), alreadyWritten); } } if (obj instanceof Iterable<?>) { try { for (Object next : (Iterable<?>) obj) { addPresentableNestedNames(namedBeans, next, alreadyWritten); } } catch (Exception e) { LOGGER.warning("problem iterating over " + obj + " - " + e); } } } }
From source file:org.dspace.app.rest.model.hateoas.DSpaceResource.java
public DSpaceResource(T data, Utils utils, String... rels) { this.data = data; if (data != null) { try {/*from w w w .jav a 2s . c om*/ LinksRest links = data.getClass().getDeclaredAnnotation(LinksRest.class); if (links != null && rels != null) { List<String> relsList = Arrays.asList(rels); for (LinkRest linkAnnotation : links.links()) { if (!relsList.contains(linkAnnotation.name())) { continue; } String name = linkAnnotation.name(); Link linkToSubResource = utils.linkToSubResource(data, name); String apiCategory = data.getCategory(); String model = data.getType(); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkAnnotation.name()); if (!linkRepository.isEmbeddableRelation(data, linkAnnotation.name())) { continue; } try { //RestModel linkClass = linkAnnotation.linkClass().newInstance(); Method[] methods = linkRepository.getClass().getMethods(); boolean found = false; for (Method m : methods) { if (StringUtils.equals(m.getName(), linkAnnotation.method())) { // TODO add support for single linked object other than for collections Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m.invoke( linkRepository, null, ((BaseObjectRest) data).getId(), null, null); EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult, null); embedded.put(name, ep); found = true; } } // TODO custom exception if (!found) { throw new RuntimeException("Method for relation " + linkAnnotation.name() + " not found: " + linkAnnotation.method()); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } } } for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); String name = pd.getName(); if (readMethod != null && !"class".equals(name)) { LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class); if (linkAnnotation != null) { if (StringUtils.isNotBlank(linkAnnotation.name())) { name = linkAnnotation.name(); } Link linkToSubResource = utils.linkToSubResource(data, name); // no method is specified to retrieve the linked object(s) so check if it is already here if (StringUtils.isBlank(linkAnnotation.method())) { this.add(linkToSubResource); Object linkedObject = readMethod.invoke(data); Object wrapObject = linkedObject; if (linkedObject instanceof RestModel) { RestModel linkedRM = (RestModel) linkedObject; wrapObject = utils .getResourceRepository(linkedRM.getCategory(), linkedRM.getType()) .wrapResource(linkedRM); } else { if (linkedObject instanceof List) { List<RestModel> linkedRMList = (List<RestModel>) linkedObject; if (linkedRMList.size() > 0) { DSpaceRestRepository<RestModel, ?> resourceRepository = utils .getResourceRepository(linkedRMList.get(0).getCategory(), linkedRMList.get(0).getType()); // TODO should we force pagination also of embedded resource? // This will force a pagination with size 10 for embedded collections as well // int pageSize = 1; // PageImpl<RestModel> page = new PageImpl( // linkedRMList.subList(0, // linkedRMList.size() > pageSize ? pageSize : linkedRMList.size()), new PageRequest(0, pageSize), linkedRMList.size()); PageImpl<RestModel> page = new PageImpl(linkedRMList); wrapObject = new EmbeddedPage(linkToSubResource.getHref(), page.map(resourceRepository::wrapResource), linkedRMList); } else { wrapObject = null; } } } if (linkedObject != null) { embedded.put(name, wrapObject); } else { embedded.put(name, null); } Method writeMethod = pd.getWriteMethod(); writeMethod.invoke(data, new Object[] { null }); } else { // call the link repository try { //RestModel linkClass = linkAnnotation.linkClass().newInstance(); String apiCategory = data.getCategory(); String model = data.getType(); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkAnnotation.name()); Method[] methods = linkRepository.getClass().getMethods(); boolean found = false; for (Method m : methods) { if (StringUtils.equals(m.getName(), linkAnnotation.method())) { // TODO add support for single linked object other than for collections Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m .invoke(linkRepository, null, ((BaseObjectRest) data).getId(), null, null); EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult, null); embedded.put(name, ep); found = true; } } // TODO custom exception if (!found) { throw new RuntimeException("Method for relation " + linkAnnotation.name() + " not found: " + linkAnnotation.method()); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) { Link linkToSubResource = utils.linkToSubResource(data, name); this.add(linkToSubResource); RestModel linkedObject = (RestModel) readMethod.invoke(data); if (linkedObject != null) { embedded.put(name, utils .getResourceRepository(linkedObject.getCategory(), linkedObject.getType()) .wrapResource(linkedObject)); } else { embedded.put(name, null); } Method writeMethod = pd.getWriteMethod(); writeMethod.invoke(data, new Object[] { null }); } } } } catch (IntrospectionException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } this.add(utils.linkToSingleResource(data, Link.REL_SELF)); } }
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass.java
private void flowStrategy(Collection<String> closureNames) { for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && !Modifier.isStatic(readMethod.getModifiers())) { final Class<?> propertyType = propertyDescriptor.getPropertyType(); if ((propertyType == Object.class || propertyType == Closure.class) && propertyDescriptor.getName().endsWith(FLOW_SUFFIX)) { String closureName = propertyDescriptor.getName(); String flowId = closureName.substring(0, closureName.length() - FLOW_SUFFIX.length()); flows.put(flowId, propertyDescriptor); closureNames.add(flowId); configureMappingForMethodAction(flowId); }// ww w .jav a2s . com } } if (!isReadableProperty(defaultActionName) && closureNames.size() == 1) { defaultActionName = closureNames.iterator().next(); } }
From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java
protected void captureOutput(final Object o, final RunnerContext ctx, final EList<CaptureOutput> outputs) throws Exception { here: for (final CaptureOutput output : outputs) { final String name = output.getLocalName(); final String storeName = output.getContextName() == null ? name : output.getContextName(); logger.debug("Capture output: {} -> {}", name, storeName); final BeanInfo bi = Introspector.getBeanInfo(o.getClass()); for (final PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getName().equals(name)) { final Object value = pd.getReadMethod().invoke(o); ctx.getMap().put(storeName, value); logger.debug("By BeanInfo - value: {}", value); continue here; }//w w w . j a va 2 s . co m } final Field field = Reflections.findField(o.getClass(), name); if (field != null && field.getAnnotation(Output.class) != null) { final Object value = InjectHelper.getField(o, field); ctx.getMap().put(storeName, value); logger.debug("By field - value: {}", value); continue; } if (field != null) { throw new IllegalStateException(String.format( "Unable to capture output. Field '%s' of class '%s' is not marked with @Output and is not accessible using a getter.")); } throw new IllegalStateException( String.format("Unable to capture output '%s' of class '%s'", name, o.getClass())); } }
From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java
private static Object getProperty(Object obj, String fieldName) { PropertyDescriptor pd = getPropertyDescriptor(obj.getClass(), fieldName); if (pd == null || pd.getReadMethod() == null) { throw new IllegalStateException( "In class" + obj.getClass() + ", no getter method found for field '" + fieldName + "'"); }/* w ww . j a va 2 s . co m*/ try { return pd.getReadMethod().invoke(obj, (Object[]) null); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.codehaus.groovy.grails.commons.ClassPropertyFetcher.java
private void init() { FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() { public void doWith(Field field) { if (field.isSynthetic()) { return; }/*from ww w . ja va 2 s . c o m*/ final int modifiers = field.getModifiers(); if (!Modifier.isPublic(modifiers)) { return; } final String name = field.getName(); if (name.indexOf('$') == -1) { boolean staticField = Modifier.isStatic(modifiers); if (staticField) { staticFetchers.put(name, new FieldReaderFetcher(field, staticField)); } else { instanceFetchers.put(name, new FieldReaderFetcher(field, staticField)); } } } }; MethodCallback methodCallback = new ReflectionUtils.MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (method.isSynthetic()) { return; } if (!Modifier.isPublic(method.getModifiers())) { return; } if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); staticFetchers.put(name, fetcher); staticFetchers.put(StringUtils.uncapitalize(name), fetcher); } } } } }; List<Class<?>> allClasses = resolveAllClasses(clazz); for (Class<?> c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { try { fieldCallback.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { try { methodCallback.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access method '" + method.getName() + "': " + ex); } } } propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor desc : propertyDescriptors) { Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }