List of usage examples for java.lang.reflect Method getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java
public final BasicDBObject resolveToBasicDBObject() { BasicDBObject bDBObject = new BasicDBObject(); try {// ww w.j a v a2s. c om Class<? extends AbstractDocument> currClass = getClass(); while (currClass != null) { for (Method method : currClass.getMethods()) { IDocumentKeyValue dkv = method.getAnnotation(IDocumentKeyValue.class); String mName = method.getName(); if (dkv != null && mName.startsWith(JPAConstants.GETTER_PREFIX)) { try { Object returnValue = method.invoke(this, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST); char[] propertyChars = mName.substring(3).toCharArray(); String property = String.valueOf(propertyChars[0]).toLowerCase() + String.valueOf(propertyChars, 1, propertyChars.length - 1); if (returnValue == null) { continue; } if (returnValue instanceof AbstractDocument) { Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD.invoke(returnValue, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST); bDBObject.put(property, subReturnValue); } else if (returnValue instanceof Enum) { Enum<?> enumClass = Enum.class.cast(returnValue); BasicDBObject enumObject = new BasicDBObject(); enumObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(), enumClass.getClass().getName()); enumObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), enumClass.name()); bDBObject.put(property, enumObject); } else if (returnValue instanceof Collection) { Collection<?> collectionContent = (Collection<?>) returnValue; BasicDBObject collectionObject = new BasicDBObject(); collectionObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(), collectionContent.getClass().getName()); BasicDBList bDBList = new BasicDBList(); if (collectionContent.iterator().next() instanceof AbstractDocument) { for (Object content : collectionContent) { if (content instanceof AbstractDocument) { Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD .invoke(returnValue, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST); bDBList.add(subReturnValue); } } } else { bDBList.addAll(collectionContent); } collectionObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), bDBList); bDBObject.put(property, collectionObject); } else if (returnValue instanceof Map) { Map<?, ?> mapContent = (Map<?, ?>) returnValue; BasicDBObject mapObject = new BasicDBObject(); mapObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(), mapContent.getClass().getName()); Set<?> keys = mapContent.keySet(); if (keys.iterator().next() instanceof AbstractDocument) { Map<Object, Object> convertedMap = new HashMap<Object, Object>(); for (Object key : keys) { Object value = mapContent.get(key); Object subReturnValue = RESOLVE_TO_BASIC_DB_OBJECT_METHOD.invoke(value, JPAConstants.EMPTY_OBJECT_ARGUMENT_LIST); convertedMap.put(key, subReturnValue); } mapContent = convertedMap; } mapObject.put(JPAConstants.CONVERTER_CLASS.CONTENT.name(), mapContent); bDBObject.put(property, mapObject); } else { bDBObject.put(property, returnValue); } } catch (Exception e) { } } } currClass = currClass.getSuperclass().asSubclass(AbstractDocument.class); } } catch (ClassCastException castException) { } bDBObject.put(JPAConstants.CONVERTER_CLASS.CLASS.name(), getClass().getName()); _log.info("BdBObject " + bDBObject); return bDBObject; }
From source file:com.wso2telco.core.authfilter.impl.authorization.BasicAuthenticationFilter.java
@Override public boolean isAuthorized(ContainerRequestContext requestContext, Method method) { boolean isAuthorized = false; requestContext.getHeaders().add(HeaderParam.USER_NAME.getTObject(), userName); // validate user authorization by using user roles if (method.isAnnotationPresent(RolesAllowed.class)) { RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class); Set<String> allowedRolesSet = new HashSet<>(Arrays.asList(rolesAnnotation.value())); isAuthorized = userAuthorizationValidator.isAuthorizedRole(userName, allowedRolesSet); if (!isAuthorized) { requestContext.abortWith(accessDenied); return false; }//from w ww. j a va 2 s . c o m } return true; }
From source file:com.alta189.beaker.CommonEventManager.java
/** * Registers all the {@link EventHandler}s contained in the * Listener/* www. j a v a2s.co m*/ * * @param listener registration, not null * @param owner owner of the listener, not null * @throws com.alta189.beaker.exceptions.EventRegistrationException */ @Override public void registerListener(Listener listener, Named owner) throws EventRegistrationException { try { Validate.notNull(listener, "Listener cannot be null"); Validate.notNull(owner, "Owner cannot be null"); Validate.notNull(owner.getName(), "Owner's name cannot be null"); Validate.notEmpty(owner.getName(), "Owner's name cannot be empty"); for (Method method : listener.getClass().getDeclaredMethods()) { if (!method.isAnnotationPresent(EventHandler.class)) { continue; } EventHandler handler = method.getAnnotation(EventHandler.class); Validate.notNull(handler.ignoreCancelled(), "ignoredCancelled cannot be null"); Validate.notNull(handler.priority(), "Priority cannot be null"); if (!Modifier.isPublic(method.getModifiers())) { throw new EventRegistrationException("Method has to be public"); } if (Modifier.isStatic(method.getModifiers())) { throw new EventRegistrationException("Method cannot be static"); } if (method.getParameterTypes().length != 1) { throw new EventRegistrationException("Method cannot have more than one parameter"); } if (!Event.class.isAssignableFrom(method.getParameterTypes()[0])) { throw new EventRegistrationException("Method's parameter type has to extend class"); } EventExecutor executor = new AnnotatedEventExecutor(listener, method); HandlerRegistration registration = new HandlerRegistration(executor, handler.priority(), handler.ignoreCancelled(), owner); List<HandlerRegistration> list = getRegistrationList( (Class<? extends Event>) method.getParameterTypes()[0], true); list.add(registration); sortList(list); } } catch (EventRegistrationException e) { throw e; } catch (Exception e) { throw new EventRegistrationException(e); } }
From source file:net.navasoft.madcoin.backend.services.vo.request.SuccessRequestVOWrapper.java
/** * Gets the processing values./*w w w. j a v a 2 s. c o m*/ * * @param service * the service * @since 27/07/2014, 06:49:08 PM */ @Override public void processValues(IService service) { if (isValidService(service)) { for (ProcessedField annotatedField : getTarget(service)) { for (Method accessor : filterMethods()) { Annotation annot = accessor.getAnnotation(ProcessingField.class); if (annot != null) { ProcessingField expectedReal = ((ProcessingField) annot); if (!ArrayUtils.contains(alreadyProcessed, expectedReal.expectedVariable())) { try { if (validateProcessAnnotations(annotatedField, expectedReal)) { Object requestValue = null; switch (expectedReal.precedence()) { case BASIC_OPTIONAL: requestValue = accessor.invoke(hidden, ArrayUtils.EMPTY_OBJECT_ARRAY); processed.put(expectedReal.expectedVariable(), requestValue); alreadyProcessed = (String[]) ArrayUtils.add(alreadyProcessed, expectedReal.expectedVariable()); break; case BASIC_REQUIRED: requestValue = accessor.invoke(this.hidden, ArrayUtils.EMPTY_OBJECT_ARRAY); processed.put(expectedReal.expectedVariable(), requestValue); alreadyProcessed = (String[]) ArrayUtils.add(alreadyProcessed, expectedReal.expectedVariable()); break; case COMPLEX_OPTIONAL: requestValue = expectedReal.helperClass().newInstance(); processed.put(expectedReal.expectedVariable(), expectedReal.helperClass() .getMethod(expectedReal.converterMethod(), ArrayUtils.EMPTY_CLASS_ARRAY) .invoke(requestValue, ArrayUtils.EMPTY_OBJECT_ARRAY)); alreadyProcessed = (String[]) ArrayUtils.add(alreadyProcessed, expectedReal.expectedVariable()); break; case COMPLEX_REQUIRED: requestValue = expectedReal.helperClass().newInstance(); processed.put(expectedReal.expectedVariable(), expectedReal.helperClass() .getMethod(expectedReal.converterMethod(), ArrayUtils.EMPTY_CLASS_ARRAY) .invoke(requestValue, ArrayUtils.EMPTY_OBJECT_ARRAY)); alreadyProcessed = (String[]) ArrayUtils.add(alreadyProcessed, expectedReal.expectedVariable()); break; default: break; } } } catch (IllegalAccessException e1) { } catch (IllegalArgumentException e1) { } catch (InvocationTargetException e1) { } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (InstantiationException e) { } } } } } } }
From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java
private boolean scanDetail(SubResource subResource, Method method) { Detail detail = method.getAnnotation(Detail.class); if (detail != null) { subResource.setDetail(detail.value()); return true; }/*from w w w . java 2s. c o m*/ return false; }
From source file:org.jsonschema2pojo.integration.config.CustomAnnotatorIT.java
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile( "/schema/properties/primitiveProperties.json", "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
From source file:org.lansir.beautifulgirls.proxy.ProxyInvocationHandler.java
/** * Dynamic proxy invoke// www . j a v a2s.c om */ public Object invoke(Object proxy, Method method, Object[] args) throws AkInvokeException, AkServerStatusException, AkException, Exception { AkPOST akPost = method.getAnnotation(AkPOST.class); AkGET akGet = method.getAnnotation(AkGET.class); AkAPI akApi = method.getAnnotation(AkAPI.class); Annotation[][] annosArr = method.getParameterAnnotations(); String invokeUrl = akApi.url(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // AkApiParams to hashmap, filter out of null-value HashMap<String, File> filesToSend = new HashMap<String, File>(); HashMap<String, String> paramsMapOri = new HashMap<String, String>(); HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri); // Record this invocation ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo(); apiInvokeInfo.apiName = method.getName(); apiInvokeInfo.paramsMap.putAll(paramsMap); apiInvokeInfo.url = invokeUrl; // parse '{}'s in url invokeUrl = parseUrlbyParams(invokeUrl, paramsMap); // cleared hashmap to params, and filter out of the null value Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // get the signature string if using AkSignature akSig = method.getAnnotation(AkSignature.class); if (akSig != null) { Class<?> clazzSignature = akSig.using(); if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) { InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance(); String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri); String sigParamName = is.getSignatureParamName(); if (sigValue != null && sigParamName != null && sigValue.length() > 0 && sigParamName.length() > 0) { params.add(new BasicNameValuePair(sigParamName, sigValue)); } } } // choose POST GET PUT DELETE to use for this invoke String retString = ""; if (akGet != null) { StringBuilder sbUrl = new StringBuilder(invokeUrl); if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) { sbUrl.append("?"); } for (NameValuePair nvp : params) { sbUrl.append(nvp.getName()); sbUrl.append("="); sbUrl.append(nvp.getValue()); sbUrl.append("&"); } // now default using UTF-8, maybe improved later retString = HttpInvoker.get(sbUrl.toString()); } else if (akPost != null) { if (filesToSend.isEmpty()) { retString = HttpInvoker.post(invokeUrl, params); } else { retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend); } } else { // use POST for default retString = HttpInvoker.post(invokeUrl, params); } // invoked, then add to history //ApiStats.addApiInvocation(apiInvokeInfo); //Log.d(TAG, retString); // parse the return-string Class<?> returnType = method.getReturnType(); try { if (String.class.equals(returnType)) { // the result return raw string return retString; } else { // return object using json decode return JsonMapper.json2pojo(retString, returnType); } } catch (IOException e) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, e.getMessage(), e); } /* * also can use gson like this eg. * Gson gson = new Gson(); * return gson.fromJson(HttpInvoker.post(url, params), returnType); */ }
From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java
private boolean scanConsume(SubResource subResource, Method method) { Consumes consume = method.getAnnotation(Consumes.class); if (consume != null) { subResource.setConsume(consume.value()); return true; }/*from w w w. j a va2s . co m*/ return false; }
From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java
private boolean scanProduce(SubResource subResource, Method method) { Produces produce = method.getAnnotation(Produces.class); if (produce != null) { subResource.setProduce(produce.value()); return true; }/*from ww w. j a v a 2 s.co m*/ return false; }
From source file:com.newtranx.util.monitoring.MonitorAspect.java
@Around("@annotation(com.newtranx.util.monitoring.Monitoring)") public Object around(final ProceedingJoinPoint pjp) throws Throwable { final MethodSignature signature = (MethodSignature) pjp.getSignature(); final Method method = getMethod(signature, pjp); final long begin = System.currentTimeMillis(); MonitorContext monitorContext = new MonitorContext() { @Override/*w w w .j a v a 2 s .c o m*/ public void doReport() { long end = System.currentTimeMillis(); String name = method.getAnnotation(Monitoring.class).value().trim(); Optional<String> optName = StringUtils.isEmpty(name) ? Optional.empty() : Optional.of(name); for (Reporter r : reporters) { try { r.report(method, end - begin, optName); } catch (Throwable t) { t.printStackTrace(System.err); } } } }; Object[] args = pjp.getArgs(); AsyncHandler asyncHandler = null; for (AsyncHandler a : getAsyncHandlers()) { Object[] processedArgs = a.preProcess(method, args, monitorContext); if (monitorContext.isAsync()) { args = processedArgs; asyncHandler = a; break; } } Object result = pjp.proceed(args); if (monitorContext.isAsync()) { return asyncHandler.postProcess(result, monitorContext); } else { monitorContext.doReport(); return result; } }