List of usage examples for java.lang.reflect Method getDeclaringClass
@Override
public Class<?> getDeclaringClass()
From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java
private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception { Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>(); Method[] methods = recordClass.getDeclaredMethods(); // get all get methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.equals("getProto")) { continue; }/*from www.ja va2 s . c o m*/ if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) { String propertyName = name.substring(3); Type valueType = m.getGenericReturnType(); GetSetPair p = ret.get(propertyName); if (p == null) { p = new GetSetPair(); p.propertyName = propertyName; p.type = valueType; p.getMethod = m; ret.put(propertyName, p); } else { Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName); } } } } // match get methods with set methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.startsWith("set") && (m.getParameterTypes().length == 1)) { String propertyName = name.substring(3); Type valueType = m.getGenericParameterTypes()[0]; GetSetPair p = ret.get(propertyName); if (p != null && p.type.equals(valueType)) { p.setMethod = m; } } } } // exclude incomplete get/set pair, and generate test value Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GetSetPair> cur = itr.next(); GetSetPair gsp = cur.getValue(); if ((gsp.getMethod == null) || (gsp.setMethod == null)) { LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName)); itr.remove(); } else { LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type)); gsp.testValue = genTypeValue(gsp.type); LOG.info(String.format(" testValue: %s\n", gsp.testValue)); } } return ret; }
From source file:sh.scrap.scrapper.functions.StringFunctionFactory.java
@Override public DataScrapperFunction create(String name, DataScrapperFunctionLibrary library, Object mainArgument, Map<String, Object> annotations) { return context -> subscription -> { Class<?> targetClass = stringUtils.contains(name) ? StringUtils.class : StringEscapeUtils.class; try {// ww w . j ava2 s . c o m Method method = findMethod(targetClass, name, mainArgument, annotations); if (method == null) { subscription.onError(new IllegalArgumentException("Unknown function [string:" + name + "]")); subscription.onComplete(); return; } String[] paramIndexes = discoverer.getParameterNames(method); subscription.onSubscribe(new Subscription() { @Override public void request(long n) { Object data = context.data(); context.objectProcessed(data); Object[] invokeArgs = new Object[method.getParameterCount()]; invokeArgs[0] = data; if (method.getParameterCount() > 1) invokeArgs[1] = mainArgument; for (int idx = method.getParameterCount() > 1 ? 2 : 1; idx < paramIndexes.length; idx++) invokeArgs[idx] = annotations.get(paramIndexes[idx]); try { try { data = method.invoke(method.getDeclaringClass(), invokeArgs); } catch (InvocationTargetException e) { throw e.getTargetException(); } } catch (Throwable e) { subscription.onError(e); subscription.onComplete(); return; } subscription.onNext(context.withData(data)); subscription.onComplete(); } @Override public void cancel() { } }); } catch (IllegalArgumentException e) { subscription.onError(e); subscription.onComplete(); } }; }
From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java
protected String getJavadocComments(final ITestNGMethod method) { try {//from w ww .j a v a2 s . co m final Method m = method.getMethod(); final String javaClass = m.getDeclaringClass().getName(); final String javaMethod = m.getName(); final JavaClass jc = getJavaDocBuilder(m.getDeclaringClass()).getClassByName(javaClass); final Class<?>[] types = method.getMethod().getParameterTypes(); final Type[] qdoxTypes = new Type[types.length]; for (int i = 0; i < types.length; i++) { final String type = getType(types[i]); final int dim = getDim(types[i]); qdoxTypes[i] = new Type(type, dim); } final JavaMethod jm = jc.getMethodBySignature(javaMethod, qdoxTypes); return jm.getComment(); } catch (final Throwable e) { logger.error("Exception loading the javadoc comments for : " + method.getMethodName() + e); return null; } }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }/*from www . j av a 2 s.com*/ final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }
From source file:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java
private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception { String snippetClassName = snippet.getContainer().getJavaClass().getName(); String snippetMethodName = snippet.getMethod().getName(); String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName() + "_Tests"; logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName); logger.debug("Tests: {}", testClassName); // create JaCoCo runtime and instrumenter IRuntime runtime = new LoggerRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); // start runtime RuntimeData data = new RuntimeData(); runtime.startup(data);/* w w w . j av a2 s.c o m*/ // create class loader JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter, getSnippetProject().getClassLoader()); // load test class // snippet class and other dependencies will be loaded and instrumented // on the fly Class<?> testClass = classLoader.loadClass(testClassName); TestCase testClassInstance = (TestCase) testClass.newInstance(); // invoke test methods // TODO separate collect and invoke for (Method m : testClass.getDeclaredMethods()) { if (m.isSynthetic()) { // skip synthetic method continue; } if (m.getName().startsWith("test")) { logger.trace("Invoking: " + m.getName()); try { m.invoke(testClassInstance); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException || cause instanceof AssertionFailedError) { logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "." + m.getName()); } else { logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName()); } logger.debug(e.getMessage(), e); } } else { logger.warn("Not test method: {}", m.getName()); } } // collect data ExecutionDataStore executionData = new ExecutionDataStore(); SessionInfoStore sessionInfos = new SessionInfoStore(); data.collect(executionData, sessionInfos, false); runtime.shutdown(); // get classes to analyse // store string to avoid the mess up between the different class loaders Set<String> javaClasses = new HashSet<>(); javaClasses.add(snippetClassName); for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) { javaClasses.add(inclConstructor.getDeclaringClass().getName()); } for (Method inclMethod : snippet.getIncludedMethods()) { javaClasses.add(inclMethod.getDeclaringClass().getName()); } // TODO inner classes are not handled well enough // TODO anonymous classes can also have anonymous classes -> recursion Set<String> toAdd = new HashSet<>(); for (String javaClass : javaClasses) { int i = 1; while (true) { // guess anonymous classes, like ClassName$1, ClassName$2 etc. try { classLoader.loadClass(javaClass + "$" + i); toAdd.add(javaClass + "$" + i); i++; } catch (ClassNotFoundException e) { // bad guess, no more anonymous classes on this level break; } } } javaClasses.addAll(toAdd); // analyse classes CoverageBuilder coverageBuilder = new CoverageBuilder(); Analyzer analyzer = new Analyzer(executionData, coverageBuilder); for (String javaClassName : javaClasses) { logger.trace("Analysing: {}", javaClassName); analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName); } // TODO remove debug // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs(); // PrintStream out = new PrintStream("D:/SETTE/!DUMP/" // + getTool().getName() + "/" + testClassName + ".out"); Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>(); for (final IClassCoverage cc : coverageBuilder.getClasses()) { String file = cc.getPackageName() + '/' + cc.getSourceFileName(); file = file.replace('\\', '/'); if (!coverageInfo.containsKey(file)) { coverageInfo.put(file, Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>())); } // out.printf("Coverage of class %s%n", cc.getName()); // // printCounter(out, "instructions", // cc.getInstructionCounter()); // printCounter(out, "branches", cc.getBranchCounter()); // printCounter(out, "lines", cc.getLineCounter()); // printCounter(out, "methods", cc.getMethodCounter()); // printCounter(out, "complexity", cc.getComplexityCounter()); for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) { switch (cc.getLine(l).getStatus()) { case ICounter.FULLY_COVERED: coverageInfo.get(file).getLeft().add(l); break; case ICounter.PARTLY_COVERED: coverageInfo.get(file).getMiddle().add(l); break; case ICounter.NOT_COVERED: coverageInfo.get(file).getRight().add(l); break; } } } // create coverage XML SnippetCoverageXml coverageXml = new SnippetCoverageXml(); coverageXml.setToolName(getTool().getName()); coverageXml.setSnippetProjectElement( new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath())); coverageXml.setSnippetElement( new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName())); coverageXml.setResultType(ResultType.S); for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo .entrySet()) { TreeSet<Integer> full = entry.getValue().getLeft(); TreeSet<Integer> partial = entry.getValue().getMiddle(); TreeSet<Integer> not = entry.getValue().getRight(); FileCoverageElement fce = new FileCoverageElement(); fce.setName(entry.getKey()); fce.setFullyCoveredLines(StringUtils.join(full, ' ')); fce.setPartiallyCoveredLines(StringUtils.join(partial, ' ')); fce.setNotCoveredLines(StringUtils.join(not, ' ')); coverageXml.getCoverage().add(fce); } coverageXml.validate(); // TODO needs more documentation File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy(), new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>")); serializer.write(coverageXml, coverageFile); // TODO move HTML generation to another file/phase File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet); String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()"; StringBuilder htmlData = new StringBuilder(); htmlData.append("<!DOCTYPE html>\n"); htmlData.append("<html lang=\"hu\">\n"); htmlData.append("<head>\n"); htmlData.append(" <meta charset=\"utf-8\" />\n"); htmlData.append(" <title>" + htmlTitle + "</title>\n"); htmlData.append(" <style type=\"text/css\">\n"); htmlData.append(" .code { font-family: 'Consolas', monospace; }\n"); htmlData.append(" .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n"); htmlData.append(" .code .green { background-color: #CCFFCC; }\n"); htmlData.append(" .code .yellow { background-color: #FFFF99; }\n"); htmlData.append(" .code .red { background-color: #FFCCCC; }\n"); htmlData.append(" .code .line .number {\n"); htmlData.append(" display: inline-block;\n"); htmlData.append(" width:50px;\n"); htmlData.append(" text-align:right;\n"); htmlData.append(" margin-right:5px;\n"); htmlData.append(" }\n"); htmlData.append(" </style>\n"); htmlData.append("</head>\n"); htmlData.append("\n"); htmlData.append("<body>\n"); htmlData.append(" <h1>" + htmlTitle + "</h1>\n"); for (FileCoverageElement fce : coverageXml.getCoverage()) { htmlData.append(" <h2>" + fce.getName() + "</h2>\n"); htmlData.append(" \n"); File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName()); List<String> srcLines = FileUtils.readLines(src); SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines()); SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines()); SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines()); htmlData.append(" <div class=\"code\">\n"); int i = 1; for (String srcLine : srcLines) { String divClass = getLineDivClass(i, full, partial, not); htmlData.append(" <div class=\"" + divClass + "\"><div class=\"number\">" + i + "</div> " + srcLine + "</div>\n"); i++; } htmlData.append(" </div>\n\n"); } // htmlData.append(" <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">2</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">8</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">10</div> goal = "Sample // snippet container",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">11</div> inputFactoryContainer = SampleContainer_Inputs.class)</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">13</div> private SampleContainer() {</div>\n"); // htmlData.append(" <div class=\"line red\"><div class=\"number\">14</div> throw new UnsupportedOperationException("Static // class");</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">15</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">16</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">17</div> @SetteRequiredStatementCoverage(value = 100)</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">18</div> public static boolean snippet(int x) {</div>\n"); // htmlData.append(" <div class=\"line yellow\"><div class=\"number\">19</div> if (20 * x + 2 == 42) {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">20</div> return true;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">21</div> } else {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">22</div> return false;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">23</div> }</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">24</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">25</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">26</div> </div>\n"); htmlData.append("</body>\n"); htmlData.append("</html>\n"); FileUtils.write(htmlFile, htmlData); }
From source file:com.qmetry.qaf.automation.testng.pro.QAFTestNGListener2.java
@SuppressWarnings("rawtypes") public void transform(ITestAnnotation testAnnotation, Class clazz, Constructor arg2, Method method) { try {/* w ww. jav a 2 s .co m*/ if ((method.getAnnotation(QAFDataProvider.class) != null) && (null != method.getParameterTypes()) && (null != method) && (method.getParameterTypes().length > 0)) { String dp = getDataProvider(method); if (StringUtil.isNotBlank(dp)) { testAnnotation.setDataProvider(dp); testAnnotation.setDataProviderClass(DataProviderUtil.class); } } if (null != method) { String tmtURL = getBundle().getString(method.getName() + ".testspec.url"); if (StringUtil.isNotBlank(tmtURL)) { String desc = String.format("%s<br/><a href=\"%s\">[test-spec]</a>", testAnnotation.getDescription(), tmtURL); testAnnotation.setDescription(desc); } if (getBundle().getBoolean("report.javadoc.link", false)) { String linkRelPath = String.format("%s%s.html#%s", getBundle().getString("javadoc.folderpath", "../../../docs/tests/"), method.getDeclaringClass().getCanonicalName().replaceAll("\\.", "/"), ClassUtil.getMethodSignture(method, false)); String desc = String.format( "%s " + getBundle().getString("report.javadoc.link.format", "<a href=\"%s\" target=\"_blank\">[View-doc]</a>"), testAnnotation.getDescription(), linkRelPath); testAnnotation.setDescription(desc); } testAnnotation .setDescription(getBundle().getSubstitutor().replace(testAnnotation.getDescription())); testAnnotation.setRetryAnalyzer(Class .forName(ApplicationProperties.RETRY_ANALYZER.getStringVal(RetryAnalyzer.class.getName()))); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.bval.jsr.ClassValidator.java
private <T> MethodDescriptorImpl findMethodDescriptor(final T object, final Method method) { return MethodDescriptorImpl.class.cast( BeanDescriptorImpl.class.cast(getConstraintsForClass(Proxies.classFor(method.getDeclaringClass()))) .getInternalConstraintsForMethod(method.getName(), method.getParameterTypes())); }
From source file:io.sinistral.proteus.server.tools.swagger.Reader.java
public Operation parseMethod(Method method) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType); return parseMethod(classType.getClass(), method, bd.findMethod(method.getName(), method.getParameterTypes()), Collections.<Parameter>emptyList(), Collections.<ApiResponse>emptyList(), Collections.emptyList()); }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException { net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue( "", null); AfxBeanUtils.copySamePropertyValue(pv2, pv); String propertyName = tokens.canonicalName; String actualName = tokens.actualName; if (tokens.keys != null) { // Apply indexes and map keys: fetch value for all keys but the last one. PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue;// ww w.j av a 2s. co m try { propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // Set value for last key. String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { // null map value case if (isAutoGrowNestedPaths()) { // #TO#DO#: cleanup, this is pretty hacky int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex); propValue = setDefaultValue(getterTokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } } if (propValue.getClass().isArray()) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(), tokens.keys.length); List<Object> list = (List<Object>) propValue; int index = Integer.parseInt(key); Object oldValue = null; if (isExtractOldValueForEditor() && index < list.size()) { oldValue = list.get(index); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); int size = list.size(); if (index >= size && index < this.autoGrowCollectionLimit) { for (int i = size; i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + size + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } else { try { list.set(index, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid list index in property path '" + propertyName + "'", ex); } } } else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), tokens.keys.length); Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(), tokens.keys.length); Map<Object, Object> map = (Map<Object, Object>) propValue; // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } // Pass full property name and old value in here, since we want full // conversion ability for map values. Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length)); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); } } else { PropertyDescriptor pd = pv.getResolvedDescriptor(); if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getWriteMethod() == null) { if (pv.isOptional()) { logger.debug("Ignoring optional value for property '" + actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); return; } else { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } } pv.getOriginalPropertyValue().setResolvedDescriptor(pd); } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.getConversionNecessary())) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { final Method readMethod = pd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } try { if (System.getSecurityManager() != null) { oldValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object); } }, acc); } else { oldValue = readMethod.invoke(object); } } catch (Exception ex) { if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName + "'", ex); } } } valueToApply = convertForProperty(propertyName, oldValue, originalValue, new TypeDescriptor(property(pd))); } pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue); } final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : pd.getWriteMethod()); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(this.object, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } }
From source file:io.sinistral.proteus.server.tools.swagger.Reader.java
private void readImplicitParameters(Method method, Operation operation) { processImplicitParams(ReflectionUtils.getAnnotation(method, ApiImplicitParams.class), operation); processImplicitParams(ReflectionUtils.getAnnotation(method.getDeclaringClass(), ApiImplicitParams.class), operation);/* w w w . ja v a 2s . c om*/ }