List of usage examples for java.lang.reflect Method getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.eucalyptus.upgrade.TestHarness.java
@SuppressWarnings("unchecked") private static String getDescription(Object o) { Class c = null;//from www . j a v a 2 s . c o m Method m = null; if (o instanceof Class && ((c = (Class) o).getAnnotation(TestDescription.class)) != null) { return ((TestDescription) c.getAnnotation(TestDescription.class)).value(); } else if (o instanceof Method && ((m = (Method) o).getAnnotation(TestDescription.class)) != null) { StringBuffer sb = new StringBuffer(); for (Class a : Lists.newArrayList(Before.class, After.class, Test.class, Ignore.class, Parameters.class)) { if (m.getAnnotation(a) != null) sb.append(" @").append(String.format("%-9.9s", a.getSimpleName())).append(" "); } return sb.append(" ").append(((TestDescription) m.getAnnotation(TestDescription.class)).value()) .toString(); } return ""; }
From source file:com.industrieit.ohr.OHRJavassister.java
private static Consistency getConsistency(Method meth) { try {//from w w w.ja v a 2 s.co m if (meth == null) { return Consistency.NORMAL; } Reify r = (Reify) meth.getAnnotation(Reify.class); return r.consistency(); } catch (Exception e) { //never happens throw new RuntimeException(e); } }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static boolean determineLaziness(Method method) { return method.isAnnotationPresent(OneToOne.class) && method.getAnnotation(OneToOne.class).fetch().equals(FetchType.LAZY) || method.isAnnotationPresent(OneToMany.class) && method.getAnnotation(OneToMany.class).fetch().equals(FetchType.LAZY) || method.isAnnotationPresent(ManyToOne.class) && method.getAnnotation(ManyToOne.class).fetch().equals(FetchType.LAZY) || method.isAnnotationPresent(ManyToMany.class) && method.getAnnotation(ManyToMany.class).fetch().equals(FetchType.LAZY); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static String determineValueGenerator(Method method) { return method.isAnnotationPresent(GeneratedValue.class) ? method.getAnnotation(GeneratedValue.class).generator() : null;// w w w .j av a2 s . c om }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Generate documentation for a documented method. * /*from www .j a v a 2 s.c o m*/ * @param baseUri * @param method * @return * @throws SiteWhereException */ protected static ParsedMethod parseMethod(String baseUri, Method method, File resources) throws SiteWhereException { ParsedMethod parsed = new ParsedMethod(); parsed.setName(method.getName()); parsed.setBaseUri(baseUri); ApiOperation op = method.getAnnotation(ApiOperation.class); if (op == null) { throw new SiteWhereException( "Spring ApiOperation annotation missing on documented method: " + method.getName()); } parsed.setSummary(op.value()); RequestMapping mapping = method.getAnnotation(RequestMapping.class); if (mapping == null) { throw new SiteWhereException( "Spring RequestMapping annotation missing on documented method: " + method.getName()); } // Find URI mapping. String[] mappings = mapping.value(); parsed.setRelativeUri("/"); if (mappings.length > 0) { parsed.setRelativeUri(mappings[0]); } // Find request method. RequestMethod[] methods = mapping.method(); if (methods.length == 0) { throw new SiteWhereException("No request methods configured."); } parsed.setRequestMethod(methods[0]); Documented documented = method.getAnnotation(Documented.class); String markdownFilename = documented.description(); if (markdownFilename.length() == 0) { markdownFilename = method.getName() + ".md"; } // Parse method-level markdown description. File markdownFile = new File(resources, markdownFilename); if (!markdownFile.exists()) { throw new SiteWhereException("Method markdown file missing: " + markdownFile.getAbsolutePath()); } PegDownProcessor processor = new PegDownProcessor(); String markdown = readFile(markdownFile); parsed.setDescription(processor.markdownToHtml(markdown)); // Parse parameters. List<ParsedParameter> params = parseParameters(method); Collections.sort(params, new Comparator<ParsedParameter>() { @Override public int compare(ParsedParameter o1, ParsedParameter o2) { return o1.getName().compareTo(o2.getName()); } }); parsed.setParameters(params); parseExamples(method, parsed, resources); return parsed; }
From source file:org.agiso.core.i18n.util.I18nUtils.java
private static String findGetterFieldCode(Class<?> c, String field, boolean reflectionCheck) throws IntrospectionException { for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors()) { if (pd.getName().equals(field)) { final Method g = pd.getReadMethod(); if (g != null) { // Jeli jest adnotacja I18n na metodzie odczytujcej pole, to pobieranie // pobieranie jej klucza (okrelonego przez 'value') lub klucza domylnego: if (g.isAnnotationPresent(I18n.class)) { if (g.getAnnotation(I18n.class).value().length() > 0) { return g.getAnnotation(I18n.class).value(); } else { return g.getDeclaringClass().getName() + CODE_SEPARATOR + field; }// w w w . j a v a 2s . c o m } else if (reflectionCheck) { // Pole nie jest opisane adnotacj I18n. Jeli do wyszukania maj by // wykorzystane mechanizmy refleksji, to sprawdzamy interfejsy i nadklas: for (Class<?> i : c.getInterfaces()) { String i18nCode = findGetterFieldCode(i, field, false); if (i18nCode != null) { return i18nCode; } } Class<?> s = c.getSuperclass(); if (s != null) { return findGetterFieldCode(s, field, true); } } } } } if (reflectionCheck) { for (Class<?> i : c.getInterfaces()) { String i18nCode = findGetterFieldCode(i, field, false); if (i18nCode != null) { return i18nCode; } } } return null; }
From source file:ca.uhn.fhir.rest.method.BaseMethodBinding.java
@SuppressWarnings("unchecked") public static BaseMethodBinding<?> bindMethod(Method theMethod, FhirContext theContext, Object theProvider) { Read read = theMethod.getAnnotation(Read.class); Search search = theMethod.getAnnotation(Search.class); Metadata conformance = theMethod.getAnnotation(Metadata.class); Create create = theMethod.getAnnotation(Create.class); Update update = theMethod.getAnnotation(Update.class); Delete delete = theMethod.getAnnotation(Delete.class); History history = theMethod.getAnnotation(History.class); Validate validate = theMethod.getAnnotation(Validate.class); GetTags getTags = theMethod.getAnnotation(GetTags.class); AddTags addTags = theMethod.getAnnotation(AddTags.class); DeleteTags deleteTags = theMethod.getAnnotation(DeleteTags.class); Transaction transaction = theMethod.getAnnotation(Transaction.class); Operation operation = theMethod.getAnnotation(Operation.class); GetPage getPage = theMethod.getAnnotation(GetPage.class); Patch patch = theMethod.getAnnotation(Patch.class); // ** if you add another annotation above, also add it to the next line: if (!verifyMethodHasZeroOrOneOperationAnnotation(theMethod, read, search, conformance, create, update, delete, history, validate, getTags, addTags, deleteTags, transaction, operation, getPage, patch)) { return null; }//from w w w . j a v a2s .co m if (getPage != null) { return new PageMethodBinding(theContext, theMethod); } Class<? extends IBaseResource> returnType; Class<? extends IBaseResource> returnTypeFromRp = null; if (theProvider instanceof IResourceProvider) { returnTypeFromRp = ((IResourceProvider) theProvider).getResourceType(); if (!verifyIsValidResourceReturnType(returnTypeFromRp)) { throw new ConfigurationException("getResourceType() from " + IResourceProvider.class.getSimpleName() + " type " + theMethod.getDeclaringClass().getCanonicalName() + " returned " + toLogString(returnTypeFromRp) + " - Must return a resource type"); } } Class<?> returnTypeFromMethod = theMethod.getReturnType(); if (getTags != null) { if (!TagList.class.equals(returnTypeFromMethod)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' from type " + theMethod.getDeclaringClass().getCanonicalName() + " is annotated with @" + GetTags.class.getSimpleName() + " but does not return type " + TagList.class.getName()); } } else if (MethodOutcome.class.isAssignableFrom(returnTypeFromMethod)) { // returns a method outcome } else if (IBundleProvider.class.equals(returnTypeFromMethod)) { // returns a bundle provider } else if (Bundle.class.equals(returnTypeFromMethod)) { // returns a bundle } else if (void.class.equals(returnTypeFromMethod)) { // returns a bundle } else if (Collection.class.isAssignableFrom(returnTypeFromMethod)) { returnTypeFromMethod = ReflectionUtil.getGenericCollectionTypeOfMethodReturnType(theMethod); if (returnTypeFromMethod == null) { ourLog.trace("Method {} returns a non-typed list, can't verify return type", theMethod); } else if (!verifyIsValidResourceReturnType(returnTypeFromMethod) && !isResourceInterface(returnTypeFromMethod)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' from " + IResourceProvider.class.getSimpleName() + " type " + theMethod.getDeclaringClass().getCanonicalName() + " returns a collection with generic type " + toLogString(returnTypeFromMethod) + " - Must return a resource type or a collection (List, Set) with a resource type parameter (e.g. List<Patient> or List<IBaseResource> )"); } } else { if (!isResourceInterface(returnTypeFromMethod) && !verifyIsValidResourceReturnType(returnTypeFromMethod)) { throw new ConfigurationException( "Method '" + theMethod.getName() + "' from " + IResourceProvider.class.getSimpleName() + " type " + theMethod.getDeclaringClass().getCanonicalName() + " returns " + toLogString(returnTypeFromMethod) + " - Must return a resource type (eg Patient, " + Bundle.class.getSimpleName() + ", " + IBundleProvider.class.getSimpleName() + ", etc., see the documentation for more details)"); } } Class<? extends IBaseResource> returnTypeFromAnnotation = IBaseResource.class; if (read != null) { returnTypeFromAnnotation = read.type(); } else if (search != null) { returnTypeFromAnnotation = search.type(); } else if (history != null) { returnTypeFromAnnotation = history.type(); } else if (delete != null) { returnTypeFromAnnotation = delete.type(); } else if (patch != null) { returnTypeFromAnnotation = patch.type(); } else if (create != null) { returnTypeFromAnnotation = create.type(); } else if (update != null) { returnTypeFromAnnotation = update.type(); } else if (validate != null) { returnTypeFromAnnotation = validate.type(); } else if (getTags != null) { returnTypeFromAnnotation = getTags.type(); } else if (addTags != null) { returnTypeFromAnnotation = addTags.type(); } else if (deleteTags != null) { returnTypeFromAnnotation = deleteTags.type(); } if (returnTypeFromRp != null) { if (returnTypeFromAnnotation != null && !isResourceInterface(returnTypeFromAnnotation)) { if (!returnTypeFromRp.isAssignableFrom(returnTypeFromAnnotation)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " returns type " + returnTypeFromMethod.getCanonicalName() + " - Must return " + returnTypeFromRp.getCanonicalName() + " (or a subclass of it) per IResourceProvider contract"); } if (!returnTypeFromRp.isAssignableFrom(returnTypeFromAnnotation)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " claims to return type " + returnTypeFromAnnotation.getCanonicalName() + " per method annotation - Must return " + returnTypeFromRp.getCanonicalName() + " (or a subclass of it) per IResourceProvider contract"); } returnType = returnTypeFromAnnotation; } else { returnType = returnTypeFromRp; } } else { if (!isResourceInterface(returnTypeFromAnnotation)) { if (!verifyIsValidResourceReturnType(returnTypeFromAnnotation)) { throw new ConfigurationException( "Method '" + theMethod.getName() + "' from " + IResourceProvider.class.getSimpleName() + " type " + theMethod.getDeclaringClass().getCanonicalName() + " returns " + toLogString(returnTypeFromAnnotation) + " according to annotation - Must return a resource type"); } returnType = returnTypeFromAnnotation; } else { // if (IRestfulClient.class.isAssignableFrom(theMethod.getDeclaringClass())) { // Clients don't define their methods in resource specific types, so they can // infer their resource type from the method return type. returnType = (Class<? extends IBaseResource>) returnTypeFromMethod; // } else { // This is a plain provider method returning a resource, so it should be // an operation or global search presumably // returnType = null; } } if (read != null) { return new ReadMethodBinding(returnType, theMethod, theContext, theProvider); } else if (search != null) { if (search.dynamic()) { IDynamicSearchResourceProvider provider = (IDynamicSearchResourceProvider) theProvider; return new DynamicSearchMethodBinding(returnType, theMethod, theContext, provider); } else { return new SearchMethodBinding(returnType, theMethod, theContext, theProvider); } } else if (conformance != null) { return new ConformanceMethodBinding(theMethod, theContext, theProvider); } else if (create != null) { return new CreateMethodBinding(theMethod, theContext, theProvider); } else if (update != null) { return new UpdateMethodBinding(theMethod, theContext, theProvider); } else if (delete != null) { return new DeleteMethodBinding(theMethod, theContext, theProvider); } else if (patch != null) { return new PatchMethodBinding(theMethod, theContext, theProvider); } else if (history != null) { return new HistoryMethodBinding(theMethod, theContext, theProvider); } else if (validate != null) { if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { return new ValidateMethodBindingDstu1(theMethod, theContext, theProvider); } else { return new ValidateMethodBindingDstu2Plus(returnType, returnTypeFromRp, theMethod, theContext, theProvider, validate); } } else if (getTags != null) { return new GetTagsMethodBinding(theMethod, theContext, theProvider, getTags); } else if (addTags != null) { return new AddTagsMethodBinding(theMethod, theContext, theProvider, addTags); } else if (deleteTags != null) { return new DeleteTagsMethodBinding(theMethod, theContext, theProvider, deleteTags); } else if (transaction != null) { return new TransactionMethodBinding(theMethod, theContext, theProvider); } else if (operation != null) { return new OperationMethodBinding(returnType, returnTypeFromRp, theMethod, theContext, theProvider, operation); } else { throw new ConfigurationException("Did not detect any FHIR annotations on method '" + theMethod.getName() + "' on type: " + theMethod.getDeclaringClass().getCanonicalName()); } // // each operation name must have a request type annotation and be // unique // if (null != read) { // return rm; // } // // SearchMethodBinding sm = new SearchMethodBinding(); // if (null != search) { // sm.setRequestType(SearchMethodBinding.RequestType.GET); // } else if (null != theMethod.getAnnotation(PUT.class)) { // sm.setRequestType(SearchMethodBinding.RequestType.PUT); // } else if (null != theMethod.getAnnotation(POST.class)) { // sm.setRequestType(SearchMethodBinding.RequestType.POST); // } else if (null != theMethod.getAnnotation(DELETE.class)) { // sm.setRequestType(SearchMethodBinding.RequestType.DELETE); // } else { // return null; // } // // return sm; }
From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java
public static RPCAPIInfo getAPIInfo(String realPath, Method method) { RPCAPIInfo apiInfo = new RPCAPIInfo(); ClassInfo classInfo = RPCAPIDocletUtil.getClassInfo(method.getDeclaringClass().getName()); MethodInfo methodInfo = null;// ww w . j a v a2s .c o m if (classInfo != null) { methodInfo = classInfo.getMethodInfo(method.getName()); } if (methodInfo != null) { apiInfo.setComment(methodInfo.getComment()); } Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Security securityAnnotation = method.getAnnotation(Security.class); ResourceMapping resourceMapping = method.getAnnotation(ResourceMapping.class); Object returnType = null; returnType = buildTypeStructure(method.getReturnType(), method.getGenericReturnType(), null); boolean checkCSRF = false; if (securityAnnotation != null) { checkCSRF = securityAnnotation.checkCSRF(); } apiInfo.setPattern(realPath.replaceAll("///", "/")); apiInfo.setCheckCSRF(checkCSRF); apiInfo.setResponseMimes(StringUtils.arrayToDelimitedString(resourceMapping.produces(), ",")); apiInfo.setHttpMethod(StringUtils.arrayToDelimitedString(resourceMapping.method(), ",")); List<RPCAPIInfo.Parameter> parameters = new ArrayList<RPCAPIInfo.Parameter>(); RPCAPIInfo.Parameter parameter = null; LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); String[] paramNames = nameDiscoverer.getParameterNames(method); int i = 0; Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Class<?> paramType = null; Type genericType; for (int k = 0; k < parameterTypes.length; k++) { paramType = parameterTypes[k]; genericType = genericParameterTypes[k]; Annotation[] pAnnotations = parameterAnnotations[i]; if (HttpServletRequest.class.isAssignableFrom(paramType) || HttpServletResponse.class.isAssignableFrom(paramType) || ErrorContext.class.isAssignableFrom(paramType)) { continue; } // end if String realParamName = paramNames[k]; if (pAnnotations.length == 0) { parameter = apiInfo.new Parameter(); parameter.setName(realParamName); parameter.setType(buildTypeStructure(paramType, genericType, null)); parameters.add(parameter); setParameterComment(parameter, realParamName, methodInfo); continue; } // end if for (Annotation annotation : pAnnotations) { parameter = apiInfo.new Parameter(); setParameterComment(parameter, realParamName, methodInfo); if (annotation instanceof RequestParam) { RequestParam requestParam = (RequestParam) annotation; parameter.setName(requestParam.name()); parameter.setType(buildTypeStructure(paramType, genericType, null)); if (!StringUtil.isBlank(requestParam.defaultValue())) { parameter.setDefaultValue(requestParam.defaultValue().trim()); } parameters.add(parameter); } else if (annotation instanceof PathParam) { PathParam pathParam = (PathParam) annotation; parameter.setName(pathParam.name()); parameter.setType(buildTypeStructure(paramType, genericType, null)); if (!StringUtil.isBlank(pathParam.defaultValue())) { parameter.setDefaultValue(pathParam.defaultValue().trim()); } parameters.add(parameter); } else if (annotation instanceof JsonParam) { JsonParam pathParam = (JsonParam) annotation; parameter.setName(pathParam.value()); parameter.setType(buildTypeStructure(paramType, genericType, null)); parameters.add(parameter); } else if (annotation instanceof RequestParams) { parameter.setName(realParamName); parameter.setType(buildTypeStructure(paramType, genericType, null)); parameters.add(parameter); } else if (annotation instanceof File) { File file = (File) annotation; parameter.setName(file.value()); parameter.setType(""); parameters.add(parameter); } // end if } // end for i++; } // end for apiInfo.setParmeters(parameters); apiInfo.setReturnType(returnType); return apiInfo; }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static ColumnMetadata determineForeignReference(Method method) { final String name; final Class<?> entityType; if (method.isAnnotationPresent(OneToOne.class)) { final OneToOne annotation = method.getAnnotation(OneToOne.class); name = ""; entityType = annotation.targetEntity().equals(void.class) ? method.getReturnType() : annotation.targetEntity(); } else if (method.isAnnotationPresent(ManyToOne.class)) { final ManyToOne annotation = method.getAnnotation(ManyToOne.class); name = ""; entityType = annotation.targetEntity().equals(void.class) ? method.getReturnType() : annotation.targetEntity(); } else {//from w w w. ja v a 2s . c o m throw new UnsupportedOperationException(); } //noinspection unchecked return new UnresolvedColumnMetadata(name, new UnresolvedTableMetadata<Object>((Class<Object>) entityType)); }
From source file:com.cloudera.api.model.ApiModelTest.java
/** * Compares two objects by recursively comparing all of the fields that have * JAX-B annotations (@XmlElement and @XmlElementWrapper). This check assumes * that all getters are annotated and public, as is our convention. * <p/>/*from www . jav a 2 s .c o m*/ * The test requires that all non-API-object properties of the instances * being compared are properly set. The assumption is that there is at least * one test for each API type (explicitly or implicitly through another * object's test), so that in the end everything is covered. */ private static void compareObjects(Object expected, Object deserialized) { try { for (Method m : expected.getClass().getMethods()) { String methodName = getMethodName(m); XmlElement elem = m.getAnnotation(XmlElement.class); if (elem != null) { compareChildObjects(m, m.getReturnType(), m.invoke(expected), m.invoke(deserialized)); continue; } XmlElementWrapper wrapper = m.getAnnotation(XmlElementWrapper.class); if (wrapper != null) { assertTrue(Collection.class.isAssignableFrom(m.getReturnType())); assertTrue("Unexpected generic return in " + methodName, m.getGenericReturnType() instanceof ParameterizedType); Type memberType = ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments()[0]; assertTrue("Unexpected generic argument in " + methodName, memberType instanceof Class); Collection<?> expectedItems = (Collection<?>) m.invoke(expected); Collection<?> deserializedItems = (Collection<?>) m.invoke(deserialized); if (!isApiType((Class<?>) memberType)) { assertNotNull("No expected items for getter " + m.getName(), expectedItems); } if (expectedItems != null) { assertNotNull("No deserialized items for getter " + methodName, deserializedItems); assertEquals("Mismatched item count in values for getter " + methodName, expectedItems.size(), deserializedItems.size()); Iterator<?> ex = expectedItems.iterator(); Iterator<?> ds = deserializedItems.iterator(); while (ex.hasNext()) { compareChildObjects(m, (Class<?>) memberType, ex.next(), ds.next()); } } } } } catch (Exception e) { throw Throwables.propagate(e); } }