List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:message.mybatis.common.mapper.MapperHelper.java
/** * Mapper??MapperTemplate//w w w . ja v a 2s . co m * * @param mapperClass * @return * @throws Exception */ private MapperTemplate fromMapperClass(Class<?> mapperClass) { Method[] methods = mapperClass.getDeclaredMethods(); Class<?> templateClass = null; Class<?> tempClass = null; Set<String> methodSet = new HashSet<String>(); for (Method method : methods) { if (method.isAnnotationPresent(SelectProvider.class)) { SelectProvider provider = method.getAnnotation(SelectProvider.class); tempClass = provider.type(); methodSet.add(method.getName()); } else if (method.isAnnotationPresent(InsertProvider.class)) { InsertProvider provider = method.getAnnotation(InsertProvider.class); tempClass = provider.type(); methodSet.add(method.getName()); } else if (method.isAnnotationPresent(DeleteProvider.class)) { DeleteProvider provider = method.getAnnotation(DeleteProvider.class); tempClass = provider.type(); methodSet.add(method.getName()); } else if (method.isAnnotationPresent(UpdateProvider.class)) { UpdateProvider provider = method.getAnnotation(UpdateProvider.class); tempClass = provider.type(); methodSet.add(method.getName()); } if (templateClass == null) { templateClass = tempClass; } else if (templateClass != tempClass) { throw new RuntimeException("Mapper??MapperTemplate?!"); } } if (templateClass == null || !MapperTemplate.class.isAssignableFrom(templateClass)) { templateClass = EmptyMapperProvider.class; } MapperTemplate mapperTemplate = null; try { mapperTemplate = (MapperTemplate) templateClass.getConstructor(Class.class, MapperHelper.class) .newInstance(mapperClass, this); } catch (Exception e) { throw new RuntimeException("MapperTemplate:" + e.getMessage()); } // for (String methodName : methodSet) { try { mapperTemplate.addMethodMap(methodName, templateClass.getMethod(methodName, MappedStatement.class)); } catch (NoSuchMethodException e) { throw new RuntimeException(templateClass.getCanonicalName() + "" + methodName + "!"); } } return mapperTemplate; }
From source file:org.mulesoft.restx.component.BaseComponent.java
protected void initialiseComponentDescriptor() throws RestxException { if (annotationsHaveBeenParsed || componentDescriptor != null) { return;/* ww w . j a v a2 s. c om*/ } final Class<? extends BaseComponent> myclass = this.getClass(); /* * Examine the class annotations to get information about the component. */ final ComponentInfo ci = this.getClass().getAnnotation(ComponentInfo.class); if (ci == null) { throw new RestxException("Component does not have a ComponentInfo annotation"); } componentDescriptor = new ComponentDescriptor(ci.name(), ci.desc(), ci.doc()); /* * Examine field annotations to identify resource creation time parameters. */ for (final Field f : myclass.getFields()) { final Parameter fa = f.getAnnotation(Parameter.class); if (fa != null) { final String paramName = fa.name(); final String paramDesc = fa.desc(); String defaultVal = null; boolean required = true; String[] choices = null; // Check if we have a default value and set that one as well final Default fad = f.getAnnotation(Default.class); if (fad != null) { defaultVal = fad.value(); required = false; } // Check if we have a list of choices final Choices cad = f.getAnnotation(Choices.class); if (cad != null) { choices = cad.value(); } final Class<?> ftype = f.getType(); componentDescriptor.addParameter(paramName, createParamDefType(ftype, paramDesc, required, defaultVal, choices)); } } /* * Examine the method annotations to identify service methods and their * parameters. */ paramOrder = new HashMap<String, ArrayList<String>>(); paramTypes = new HashMap<String, ArrayList<Class<?>>>(); for (final Method m : myclass.getMethods()) { if (m.isAnnotationPresent(Service.class)) { final String serviceName = m.getName(); final Service at = m.getAnnotation(Service.class); boolean pinreq = false; if (m.isAnnotationPresent(ParamsInReqBody.class)) { pinreq = true; } // Looking for output type annotations ArrayList<String> outputTypes = null; if (m.isAnnotationPresent(OutputType.class)) { final OutputType ot = m.getAnnotation(OutputType.class); outputTypes = new ArrayList<String>(); outputTypes.add(ot.value()); } if (m.isAnnotationPresent(OutputTypes.class)) { final OutputTypes ots = m.getAnnotation(OutputTypes.class); final String[] otsSpecs = ots.value(); if (otsSpecs.length > 0) { if (outputTypes == null) { outputTypes = new ArrayList<String>(); } for (final String ts : otsSpecs) { outputTypes.add(ts); } } } // Looking for output type annotations ArrayList<String> inputTypes = null; if (m.isAnnotationPresent(InputType.class)) { final InputType it = m.getAnnotation(InputType.class); inputTypes = new ArrayList<String>(); final String it_val = it.value(); if (!it_val.equals(InputType.NO_INPUT)) { inputTypes.add(it_val); } else { inputTypes.add(null); } } if (m.isAnnotationPresent(InputTypes.class)) { final InputTypes its = m.getAnnotation(InputTypes.class); final String[] itsSpecs = its.value(); if (itsSpecs.length > 0) { if (inputTypes == null) { inputTypes = new ArrayList<String>(); } for (final String ts : itsSpecs) { if (!ts.equals(InputType.NO_INPUT)) { inputTypes.add(ts); } else { inputTypes.add(null); } } } } final ServiceDescriptor sd = new ServiceDescriptor(at.desc(), pinreq, outputTypes, inputTypes); final Class<?>[] types = m.getParameterTypes(); final Annotation[][] allParamAnnotations = m.getParameterAnnotations(); int i = 0; final ArrayList<String> positionalParams = new ArrayList<String>(); for (final Annotation[] pa : allParamAnnotations) { String name = null; String desc = null; boolean required = true; String defaultVal = null; for (final Annotation a : pa) { if (a.annotationType() == Parameter.class) { name = ((Parameter) a).name(); desc = ((Parameter) a).desc(); if (!paramOrder.containsKey(serviceName)) { paramOrder.put(serviceName, new ArrayList<String>()); paramTypes.put(serviceName, new ArrayList<Class<?>>()); } if (((Parameter) a).positional()) { positionalParams.add(name); } paramOrder.get(serviceName).add(name); paramTypes.get(serviceName).add(types[i]); } else if (a.annotationType() == Default.class) { defaultVal = ((Default) a).value(); required = false; } } if (name != null) { sd.addParameter(name, createParamDefType(types[i], desc, required, defaultVal, null)); } ++i; } if (!positionalParams.isEmpty()) { sd.setPositionalParameters(positionalParams); } componentDescriptor.addService(m.getName(), sd); } } annotationsHaveBeenParsed = true; }
From source file:com.sdm.core.filter.AuthorizationRequestFilter.java
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Method method = resourceInfo.getResourceMethod(); Class<?> resourceClass = resourceInfo.getResourceClass(); //Skip Data Permission if Resource Permission is public or there is no AccessManager if (resourceClass.isAnnotationPresent(PermitAll.class) || accessManager == null) { //Auth Success requestContext.setProperty(Constants.REQUEST_TOKEN, new AuthInfo(0, "public-token", "unknown")); return;/*from w ww. j av a2s . c om*/ } if (!method.isAnnotationPresent(PermitAll.class)) { if (method.isAnnotationPresent(DenyAll.class)) { //Deny all Auth requestContext.abortWith(errorResponse(403)); return; } final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final List<String> authorization = headers.get(HttpHeaders.AUTHORIZATION); final List<String> userAgents = headers.get(HttpHeaders.USER_AGENT); if (authorization == null || authorization.isEmpty() || userAgents == null || userAgents.isEmpty()) { //There is not Auth requestContext.abortWith(errorResponse(401)); return; } try { // Clean Token String settingKey = Setting.getInstance().get(Setting.JWT_KEY); String tokenString = authorization.get(0).substring(Constants.AUTH_TYPE.length()).trim(); byte[] jwtKey = Base64.getDecoder().decode(settingKey); try { Claims authorizeToken = Jwts.parser().setSigningKey(jwtKey).requireIssuer(userAgents.get(0)) .parseClaimsJws(tokenString).getBody(); if (!accessManager.validateToken(authorizeToken)) { //Auth Failed requestContext.abortWith(errorResponse(403)); return; } String token = authorizeToken.getId(); String device = authorizeToken.get("device_id").toString() + ":" + authorizeToken.get("device_os").toString(); long userId = Long.parseLong( authorizeToken.getSubject().substring(Constants.USER_PREFIX.length()).trim()); AuthInfo authInfo = new AuthInfo(userId, token, device); //Check @UserAllowed in Class UserAllowed userAllowed = resourceClass.getAnnotation(UserAllowed.class); if (userAllowed != null && userAllowed.value()) { //Skip Permission for User Allowed Class requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); return; } //Check @UserAllowed in Method userAllowed = resourceClass.getAnnotation(UserAllowed.class); if (userAllowed != null && userAllowed.value()) { //Skip Permission for User Allowed Method requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); return; } //Check permission from DB if (!accessManager.checkPermission(authorizeToken, method, requestContext.getMethod(), resourceClass)) { //Validate dynamic Permission failed requestContext.abortWith(errorResponse(403)); return; } requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); } catch (ClaimJwtException ex) { requestContext.abortWith(buildResponse(403, ex.getLocalizedMessage())); } } catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { LOG.error(e); requestContext.abortWith(buildResponse(500, e.getLocalizedMessage())); } } }
From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java
/** * Loads the set of output properties for the specified operation. * * @param op The operation./*from w ww . j av a2 s . co m*/ * @return The output properties. */ protected OperationBeanInfo getResponseInfo(OperationInfo op) throws XFireFault { Method method = op.getMethod(); Class ei = method.getDeclaringClass(); Package pckg = ei.getPackage(); SOAPBinding.ParameterStyle paramStyle = SOAPBinding.ParameterStyle.WRAPPED; if (method.isAnnotationPresent(SOAPBinding.class)) { SOAPBinding annotation = method.getAnnotation(SOAPBinding.class); paramStyle = annotation.parameterStyle(); } else if (ei.isAnnotationPresent(SOAPBinding.class)) { SOAPBinding annotation = ((SOAPBinding) ei.getAnnotation(SOAPBinding.class)); paramStyle = annotation.parameterStyle(); } if (paramStyle == SOAPBinding.ParameterStyle.BARE) { //bare return type. //todo: it's not necessarily the return type! it could be an OUT parameter... return new OperationBeanInfo(method.getReturnType(), null, op.getOutputMessage()); } else { String responseWrapperClassName; ResponseWrapper responseWrapperInfo = method.getAnnotation(ResponseWrapper.class); if ((responseWrapperInfo != null) && (responseWrapperInfo.className() != null) && (responseWrapperInfo.className().length() > 0)) { responseWrapperClassName = responseWrapperInfo.className(); } else { StringBuilder builder = new StringBuilder(pckg == null ? "" : pckg.getName()); if (builder.length() > 0) { builder.append("."); } builder.append("jaxws."); String methodName = method.getName(); builder.append(capitalize(methodName)).append("Response"); responseWrapperClassName = builder.toString(); } Class wrapperClass; try { wrapperClass = ClassLoaderUtils.loadClass(responseWrapperClassName, getClass()); } catch (ClassNotFoundException e) { LOG.debug("Unabled to find request wrapper class " + responseWrapperClassName + "... Operation " + op.getQName() + " will not be able to send..."); return null; } return new OperationBeanInfo(wrapperClass, loadOrderedProperties(wrapperClass), op.getOutputMessage()); } }
From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java
private List<String> getPropOrderUncached(Class<?> beanClass) { List<String> propOrder; // Superclass first! Class superclass = beanClass.getSuperclass(); if (superclass == null || superclass.equals(Object.class) || superclass.getAnnotation(XmlType.class) == null) { propOrder = new ArrayList<>(); } else {/* ww w.j ava 2 s . c o m*/ propOrder = new ArrayList<>(getPropOrder(superclass)); } XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { throw new IllegalArgumentException( "Cannot marshall " + beanClass + " it does not have @XmlType annotation"); } String[] myPropOrder = xmlType.propOrder(); for (String myProp : myPropOrder) { if (StringUtils.isNotBlank(myProp)) { // some properties starts with underscore..we don't want to serialize them with underscore, so remove it.. if (myProp.startsWith("_")) { myProp = myProp.replace("_", ""); } propOrder.add(myProp); } } Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(XmlAttribute.class)) { propOrder.add(field.getName()); } } Method[] methods = beanClass.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(XmlAttribute.class)) { propOrder.add(getPropertyNameFromGetter(method.getName())); } } return propOrder; }
From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java
private Method[] getInitMethods(FlagClassHolder holder) { Class<? extends AbstractFlag<?>> clazz = holder.flagClass; List<Method> methods = Lists.newArrayList(); for (Method method : clazz.getDeclaredMethods()) { if (!method.isAnnotationPresent(FlagInit.class)) { continue; }/*from ww w. j a v a2s . c o m*/ if ((method.getModifiers() & Modifier.STATIC) == 0) { continue; } method.setAccessible(true); methods.add(method); } return methods.toArray(new Method[methods.size()]); }
From source file:org.projectforge.database.XmlDump.java
/** * @param obj/*from w w w . ja v a2 s .c o m*/ * @param compareObj Only need for @Transient (because Javassist proxy doesn't have this annotion). * @param field * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ private Object getValue(final Object obj, final Object compareObj, final Field field) throws IllegalArgumentException, IllegalAccessException { Object val = null; final Method getter = BeanHelper.determineGetter(obj.getClass(), field.getName()); final Method getter2 = BeanHelper.determineGetter(compareObj.getClass(), field.getName()); if (getter != null && getter.isAnnotationPresent(Transient.class) == false && getter2 != null && getter2.isAnnotationPresent(Transient.class) == false) { val = BeanHelper.invoke(obj, getter); } if (val == null) { val = field.get(obj); } return val; }
From source file:org.apache.shindig.protocol.DefaultHandlerRegistry.java
/** * Add handlers to the registry//w w w. ja va 2 s . c o m * * @param handlers */ @Override public void addHandlers(Set<Object> handlers) { for (final Object handler : handlers) { Class<?> handlerType; Provider<?> handlerProvider; if (handler instanceof Class<?>) { handlerType = (Class<?>) handler; handlerProvider = injector.getProvider(handlerType); } else { handlerType = handler.getClass(); handlerProvider = new Provider<Object>() { @Override public Object get() { return handler; } }; } Preconditions.checkState(handlerType.isAnnotationPresent(Service.class), "Attempt to bind unannotated service implementation %s", handlerType.getName()); Service service = handlerType.getAnnotation(Service.class); for (Method m : handlerType.getMethods()) { if (m.isAnnotationPresent(Operation.class)) { Operation op = m.getAnnotation(Operation.class); createRpcHandler(handlerProvider, service, op, m); createRestHandler(handlerProvider, service, op, m); } } } }
From source file:org.pepstock.jem.jbpm.tasks.JemWorkItemHandler.java
@Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { // gets the java class for workitem String className = (String) workItem.getParameter(CLASS_NAME_KEY); // must be defined if (className == null) { throw new JemRuntimeException(JBpmMessage.JEMM001E.toMessage().getFormattedMessage(CLASS_NAME_KEY)); }/*from w ww . jav a 2s . c o m*/ // removes all blank className = className.trim(); // if it still has got blanks, exception if (className.contains(" ")) { throw new JemRuntimeException(JBpmMessage.JEMM056E.toMessage().getFormattedMessage(className)); } // loads parameters as list of properties for substitutions JobsProperties.getInstance().loadParameters(workItem.getParameters()); // checks if there a method to call String methodName = null; if (className.contains(METHOD_DELIMITER)) { methodName = StringUtils.substringAfter(className, METHOD_DELIMITER); className = StringUtils.substringBefore(className, METHOD_DELIMITER); } // sets security manager internal action JBpmBatchSecurityManager batchSM = (JBpmBatchSecurityManager) System.getSecurityManager(); batchSM.setInternalAction(true); // defines the wrapper JemWorkItem wrapper = null; // load class Class<?> clazz; try { clazz = Class.forName(className); // if not method has been set (and ONLY if there isn't) // scans method to see if there the annotation // on the method to call if (methodName == null) { for (Method m : clazz.getDeclaredMethods()) { // checks if there is the annotation // and not already set if (m.isAnnotationPresent(ToBeExecuted.class) && methodName == null) { //set method name methodName = m.getName(); } } } } catch (ClassNotFoundException e) { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM006E, e, className); throw new JemRuntimeException(JBpmMessage.JEMM006E.toMessage().getFormattedMessage(className), e); } // if it has got the method instantiated if (methodName != null) { try { wrapper = new CustomMethodWorkItem(clazz, methodName); } catch (InstantiationException e) { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM006E, e, className); throw new JemRuntimeException(JBpmMessage.JEMM006E.toMessage().getFormattedMessage(className), e); } catch (IllegalAccessException e) { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM006E, e, className); throw new JemRuntimeException(JBpmMessage.JEMM006E.toMessage().getFormattedMessage(className), e); } } else if (MainClassWorkItem.hasMainMethod(clazz)) { wrapper = new MainClassWorkItem(clazz); } else { try { // load by Class.forName of workItem Object instance = clazz.newInstance(); // check if it's a JemWorkItem. if not, // exception occurs. if (instance instanceof JemWorkItem) { wrapper = new DelegatedWorkItem(instance); } else { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM004E, className); throw new JemRuntimeException(JBpmMessage.JEMM004E.toMessage().getFormattedMessage(className)); } } catch (InstantiationException e) { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM006E, e, className); throw new JemRuntimeException(JBpmMessage.JEMM006E.toMessage().getFormattedMessage(className), e); } catch (IllegalAccessException e) { batchSM.setInternalAction(false); LogAppl.getInstance().emit(JBpmMessage.JEMM006E, e, className); throw new JemRuntimeException(JBpmMessage.JEMM006E.toMessage().getFormattedMessage(className), e); } } // gets the current task Task currentTask = CompleteTasksList.getInstance().getTaskByWorkItemID(workItem.getId()); if (currentTask == null) { batchSM.setInternalAction(false); throw new JemRuntimeException(JBpmMessage.JEMM002E.toMessage().getFormattedMessage(workItem.getId())); } // initialize the listener passing parameters // properties try { int returnCode = execute(currentTask, wrapper, workItem.getParameters()); LogAppl.getInstance().emit(JBpmMessage.JEMM057I, currentTask.getId(), returnCode); currentTask.setReturnCode(returnCode); Map<String, Object> output = new HashMap<String, Object>(); output.put(RESULT_KEY, returnCode); manager.completeWorkItem(workItem.getId(), output); } catch (Exception e) { currentTask.setReturnCode(Result.ERROR); throw new JemRuntimeException(e); } }
From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java
/** * Loads the set of input properties for the specified operation. * * @param op The operation.//from ww w . ja va2s. c o m * @return The input properties, or null if none were found. */ protected OperationBeanInfo getRequestInfo(OperationInfo op) throws XFireFault { Method method = op.getMethod(); Class ei = method.getDeclaringClass(); Package pckg = ei.getPackage(); SOAPBinding.ParameterStyle paramStyle = SOAPBinding.ParameterStyle.WRAPPED; if (method.isAnnotationPresent(SOAPBinding.class)) { SOAPBinding annotation = method.getAnnotation(SOAPBinding.class); paramStyle = annotation.parameterStyle(); } else if (ei.isAnnotationPresent(SOAPBinding.class)) { SOAPBinding annotation = ((SOAPBinding) ei.getAnnotation(SOAPBinding.class)); paramStyle = annotation.parameterStyle(); } boolean schemaValidate = method.isAnnotationPresent(SchemaValidate.class) || ei.isAnnotationPresent(SchemaValidate.class) || pckg.isAnnotationPresent(SchemaValidate.class); if (paramStyle == SOAPBinding.ParameterStyle.BARE) { //return a bare operation info. //it's not necessarily the first parameter type! there could be a header or OUT parameter... int paramIndex; WebParam annotation = null; Annotation[][] parameterAnnotations = method.getParameterAnnotations(); if (parameterAnnotations.length == 0) { throw new IllegalStateException("A BARE web service must have input parameters."); } PARAM_ANNOTATIONS: for (paramIndex = 0; paramIndex < parameterAnnotations.length; paramIndex++) { Annotation[] annotations = parameterAnnotations[paramIndex]; for (Annotation candidate : annotations) { if (candidate instanceof WebParam && !((WebParam) candidate).header()) { WebParam.Mode mode = ((WebParam) candidate).mode(); switch (mode) { case OUT: case INOUT: annotation = (WebParam) candidate; break PARAM_ANNOTATIONS; } } } } if (annotation == null) { paramIndex = 0; } return new OperationBeanInfo(method.getParameterTypes()[paramIndex], null, op.getInputMessage(), schemaValidate); } else { String requestWrapperClassName; RequestWrapper requestWrapperInfo = method.getAnnotation(RequestWrapper.class); if ((requestWrapperInfo != null) && (requestWrapperInfo.className() != null) && (requestWrapperInfo.className().length() > 0)) { requestWrapperClassName = requestWrapperInfo.className(); } else { StringBuilder builder = new StringBuilder(pckg == null ? "" : pckg.getName()); if (builder.length() > 0) { builder.append("."); } builder.append("jaxws."); String methodName = method.getName(); builder.append(capitalize(methodName)); requestWrapperClassName = builder.toString(); } Class wrapperClass; try { wrapperClass = ClassLoaderUtils.loadClass(requestWrapperClassName, getClass()); } catch (ClassNotFoundException e) { LOG.error("Unabled to find request wrapper class " + requestWrapperClassName + "... Operation " + op.getQName() + " will not be able to recieve..."); return null; } return new OperationBeanInfo(wrapperClass, loadOrderedProperties(wrapperClass), op.getInputMessage(), schemaValidate); } }