List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:net.solarnetwork.web.support.JSONView.java
private void generateJavaBeanObject(JsonGenerator json, String key, Object bean, PropertyEditorRegistrar registrar) throws JsonGenerationException, IOException { if (key != null) { json.writeFieldName(key);// w w w. j a v a 2 s . co m } if (bean == null) { json.writeNull(); return; } BeanWrapper wrapper = getPropertyAccessor(bean, registrar); PropertyDescriptor[] props = wrapper.getPropertyDescriptors(); json.writeStartObject(); for (PropertyDescriptor prop : props) { String name = prop.getName(); if (this.getJavaBeanIgnoreProperties() != null && this.getJavaBeanIgnoreProperties().contains(name)) { continue; } if (wrapper.isReadableProperty(name)) { Object propVal = wrapper.getPropertyValue(name); if (propVal != null) { // test for SerializeIgnore Method getter = prop.getReadMethod(); if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) { continue; } if (getPropertySerializerRegistrar() != null) { propVal = getPropertySerializerRegistrar().serializeProperty(name, propVal.getClass(), bean, propVal); } else { // Spring does not apply PropertyEditors on read methods, so manually handle PropertyEditor editor = wrapper.findCustomEditor(null, name); if (editor != null) { editor.setValue(propVal); propVal = editor.getAsText(); } } if (propVal instanceof Enum<?> || getJavaBeanTreatAsStringValues() != null && getJavaBeanTreatAsStringValues().contains(propVal.getClass())) { propVal = propVal.toString(); } writeJsonValue(json, name, propVal, registrar); } } } json.writeEndObject(); }
From source file:net.officefloor.plugin.web.http.template.PropertyHttpTemplateWriter.java
/** * Initiate.//from ww w . j ava 2 s. c o m * * @param content * {@link PropertyHttpTemplateSectionContent}. * @param valueRetriever * {@link ValueRetriever}. * @param beanType * Bean type for the property. * @throws Exception * If {@link Method} to obtain the value to write is not * available on the bean type. */ public PropertyHttpTemplateWriter(PropertyHttpTemplateSectionContent content, ValueRetriever<Object> valueRetriever, Class<?> beanType) throws Exception { this.valueRetriever = valueRetriever; this.propertyName = content.getPropertyName(); // Ensure the property is retrievable Method method = this.valueRetriever.getTypeMethod(this.propertyName); if (method == null) { throw new Exception( "Property '" + this.propertyName + "' can not be sourced from bean type " + beanType.getName()); } // Determine if should be escaped this.isEscaped = !(method.isAnnotationPresent(UnescapedHtml.class)); }
From source file:com.khs.sherpa.servlet.SherpaRequest.java
public void run() { // see if there's a json call back function specified String callback = this.servletRequest.getParameter("callback"); if (isAuthRequest(servletRequest)) { String userid = servletRequest.getParameter("userid"); String password = servletRequest.getParameter("password"); try {//from w ww . j ava 2 s . co m SessionToken token = this.service.authenticate(userid, password); this.service.getTokenService().activate(userid, token); // load the sherpa admin user if (this.service.getTokenService().hasRole(userid, token.getToken(), SettingsContext.getSettings().sherpaAdmin)) { String[] roles = token.getRoles(); token.setRoles(append(roles, "SHERPA_ADMIN")); } log(msg("authenticated"), userid, "*****"); if (SettingsContext.getSettings().jsonpSupport && callback != null) { servletResponse.setContentType("text/javascript"); this.service.mapJsonp(this.getResponseOutputStream(), token, callback); } else { this.service.map(this.getResponseOutputStream(), token); } } catch (AuthenticationException e) { this.service.error("Authentication Error Invalid Credentials", this.getResponseOutputStream()); log(msg("invalid authentication"), userid, "*****"); } return; } else { sessionStatus = this.service.validToken(getToken(), getUserId()); } if (target == null) { throw new SherpaRuntimeException("@Endpoint not found initialized"); } Method method = this.findMethod(action); ContentType type = ContentType.JSON; if (method.isAnnotationPresent(Action.class)) { type = method.getAnnotation(Action.class).contentType(); } servletResponse.setContentType(type.type); try { this.validateMethod(method); if (SettingsContext.getSettings().jsonpSupport && callback != null) { servletResponse.setContentType("text/javascript"); this.service.mapJsonp(this.getResponseOutputStream(), this.invokeMethod(method), callback); } else { this.service.map(this.getResponseOutputStream(), this.invokeMethod(method)); } } catch (SherpaRuntimeException e) { //this.service.error(e,this.getResponseOutputStream()); throw e; } }
From source file:com.opengamma.language.external.ExternalFunctionHandler.java
/** * Creates a handler wrapper for a given class. * /* ww w. j a va 2 s .c o m*/ * @param clazz the class containing external function methods */ public ExternalFunctionHandler(final Class<?> clazz) { final Constructor<?>[] constructors = clazz.getConstructors(); final Method[] methods = clazz.getMethods(); final ArrayList<PublishedFunction> functions = new ArrayList<PublishedFunction>( constructors.length + methods.length); // Only need an instance of the class if one or more annotated methods are not static. In this case, the same // instance will be re-used for each non-static method. If instantiation fails (e.g. no default constructor), just // skip instance methods and log warnings. Object sharedInstance = null; boolean instantiateFailed = false; for (Constructor<?> constructor : constructors) { if (!constructor.isAnnotationPresent(ExternalFunction.class)) { continue; } s_logger.debug("Found constructor {}", constructor); // If there is a constructor method, can only have static declarations instantiateFailed = true; functions.add(new ConstructorWrapper(constructor)); } for (Method method : methods) { if (!method.isAnnotationPresent(ExternalFunction.class)) { continue; } s_logger.debug("Found method {}", method); final Object instance; if (Modifier.isStatic(method.getModifiers())) { instance = null; } else { if (instantiateFailed) { s_logger.warn("Skipping method {}", method); continue; } else if (sharedInstance == null) { sharedInstance = tryGetInstance(clazz); if (sharedInstance == null) { s_logger.warn("Default instantiation failed for {}", clazz); s_logger.warn("Skipping method {}", method); instantiateFailed = true; continue; } } instance = sharedInstance; } functions.add(new MethodWrapper(method, instance)); } functions.trimToSize(); _functions = functions; }
From source file:org.b3log.latke.servlet.RequestProcessors.java
/** * getRendererId from mark {@link Render},using"-" as split:class_method_PARAMETER. * @param processorClass class/*from w w w . j av a 2s . co m*/ * @param processorMethod method * @param i the index of the * @return string */ private static String getRendererId(final Class<?> processorClass, final Method processorMethod, final int i) { final StringBuilder sb = new StringBuilder(); if (processorClass.isAnnotationPresent(Render.class)) { final String v = processorClass.getAnnotation(Render.class).value(); if (StringUtils.isNotBlank(v)) { sb.append(v).append(v); } } if (processorMethod.isAnnotationPresent(Render.class)) { final String v = processorClass.getAnnotation(Render.class).value(); if (StringUtils.isNotBlank(v)) { if (sb.length() > 0) { sb.append("-"); } sb.append(v).append(v); } } for (java.lang.annotation.Annotation annotation : processorMethod.getParameterAnnotations()[i]) { if (annotation instanceof Render) { final String v = ((PathVariable) annotation).value(); if (sb.length() > 0) { sb.append("-"); } sb.append(v).append(v); } } return sb.toString(); }
From source file:net.zcarioca.zcommons.config.util.ConfigurationUtilities.java
/** * Searches the bean for any methods annotated with @PostConstruct for * immediate invocation.//from w ww . ja v a2 s .co m * * @param bean The bean to process */ void invokePostConstruct(Object bean) throws ConfigurationException { Class<?> beanClass = bean.getClass(); do { for (Method method : beanClass.getDeclaredMethods()) { if (method.isAnnotationPresent(PostConstruct.class)) { Type[] types = method.getGenericParameterTypes(); if (types.length == 0) { // cannot be called on method that takes arguments try { method.invoke(bean, (Object[]) null); } catch (Exception exc) { throw new ConfigurationException( String.format("Could not call method %s on the class %s", method.getName(), bean.getClass().getName()), exc); } } } } } while ((beanClass = beanClass.getSuperclass()) != null); }
From source file:org.apache.nifi.web.security.spring.LoginIdentityProviderFactoryBean.java
private void performMethodInjection(final LoginIdentityProvider instance, final Class loginIdentityProviderClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (final Method method : loginIdentityProviderClass.getMethods()) { if (method.isAnnotationPresent(LoginIdentityProviderContext.class)) { // make the method accessible final boolean isAccessible = method.isAccessible(); method.setAccessible(true);/*from w w w. j a v a 2 s . c o m*/ try { final Class<?>[] argumentTypes = method.getParameterTypes(); // look for setters (single argument) if (argumentTypes.length == 1) { final Class<?> argumentType = argumentTypes[0]; // look for well known types if (NiFiProperties.class.isAssignableFrom(argumentType)) { // nifi properties injection method.invoke(instance, properties); } } } finally { method.setAccessible(isAccessible); } } } final Class parentClass = loginIdentityProviderClass.getSuperclass(); if (parentClass != null && LoginIdentityProvider.class.isAssignableFrom(parentClass)) { performMethodInjection(instance, parentClass); } }
From source file:org.silverpeas.core.test.extention.SilverTestEnv.java
private void invokePostConstruction(final Object bean) { try {// www .j a v a 2 s .c o m Method[] methods = bean.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(PostConstruct.class)) { method.setAccessible(true); method.invoke(bean); break; } } } catch (InvocationTargetException | IllegalAccessException e) { throw new SilverpeasRuntimeException(e); } }
From source file:org.apache.tuscany.sca.binding.rest.provider.RESTBindingInvoker.java
public Message invoke(Message msg) { Object entity = null;/*ww w . ja va 2 s . c o m*/ Object[] args = msg.getBody(); URI uri = URI.create(endpointReference.getDeployedURI()); UriBuilder uriBuilder = UriBuilder.fromUri(uri); Method method = ((JavaOperation) operation).getJavaMethod(); if (method.isAnnotationPresent(Path.class)) { // Only for resource method uriBuilder.path(method); } if (!JAXRSHelper.isResourceMethod(method)) { // This is RPC over GET uriBuilder.replaceQueryParam("method", method.getName()); } Map<String, Object> pathParams = new HashMap<String, Object>(); Map<String, Object> matrixParams = new HashMap<String, Object>(); Map<String, Object> queryParams = new HashMap<String, Object>(); Map<String, Object> headerParams = new HashMap<String, Object>(); Map<String, Object> formParams = new HashMap<String, Object>(); Map<String, Object> cookieParams = new HashMap<String, Object>(); for (int i = 0; i < method.getParameterTypes().length; i++) { boolean isEntity = true; Annotation[] annotations = method.getParameterAnnotations()[i]; PathParam pathParam = getAnnotation(annotations, PathParam.class); if (pathParam != null) { isEntity = false; pathParams.put(pathParam.value(), args[i]); } MatrixParam matrixParam = getAnnotation(annotations, MatrixParam.class); if (matrixParam != null) { isEntity = false; matrixParams.put(matrixParam.value(), args[i]); } QueryParam queryParam = getAnnotation(annotations, QueryParam.class); if (queryParam != null) { isEntity = false; queryParams.put(queryParam.value(), args[i]); } HeaderParam headerParam = getAnnotation(annotations, HeaderParam.class); if (headerParam != null) { isEntity = false; headerParams.put(headerParam.value(), args[i]); } FormParam formParam = getAnnotation(annotations, FormParam.class); if (formParam != null) { isEntity = false; formParams.put(formParam.value(), args[i]); } CookieParam cookieParam = getAnnotation(annotations, CookieParam.class); if (cookieParam != null) { isEntity = false; cookieParams.put(cookieParam.value(), args[i]); } isEntity = (getAnnotation(annotations, Context.class) == null); if (isEntity) { entity = args[i]; } } for (Map.Entry<String, Object> p : queryParams.entrySet()) { uriBuilder.replaceQueryParam(p.getKey(), p.getValue()); } for (Map.Entry<String, Object> p : matrixParams.entrySet()) { uriBuilder.replaceMatrixParam(p.getKey(), p.getValue()); } uri = uriBuilder.buildFromMap(pathParams); Resource resource = restClient.resource(uri); for (Map.Entry<String, Object> p : headerParams.entrySet()) { resource.header(p.getKey(), String.valueOf(p.getValue())); } for (Map.Entry<String, Object> p : cookieParams.entrySet()) { Cookie cookie = new Cookie(p.getKey(), String.valueOf(p.getValue())); resource.cookie(cookie); } resource.contentType(getContentType()); resource.accept(getAccepts()); //handles declarative headers configured on the composite for (HTTPHeader header : binding.getHttpHeaders()) { //treat special headers that need to be calculated if (header.getName().equalsIgnoreCase("Expires")) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(new Date()); calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue())); resource.header("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime())); } else { //default behaviour to pass the header value to HTTP response resource.header(header.getName(), header.getValue()); } } Object result = resource.invoke(httpMethod, responseType, entity); msg.setBody(result); return msg; }
From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java
private TypeConverterHolder buildFallbackTypeConverterFromFallbackConverterAnnotatedClass(final Class<?> type, final Method method) throws IllegalArgumentException { ensureFallbackConverterMethodIsValid(type, method); this.log.trace("Building Fallback TypeConverter from method [{}] ...", method); final TypeConverter typeConverter; final boolean canPromote = method.isAnnotationPresent(FallbackConverter.class) ? method.getAnnotation(FallbackConverter.class).canPromote() : false;//ww w. j av a 2 s .c o m if (isStatic(method.getModifiers())) { typeConverter = new StaticMethodFallbackTypeConverter(method, this.typeConverterRegistry); } else { typeConverter = new CdiInstanceMethodFallbackTypeConverter(new CdiInjector(this.beanManager), method, this.typeConverterRegistry); } this.log.trace("Built Fallback TypeConverter [{}]", typeConverter, method); return TypeConverterHolder.newFallbackTypeConverterHolder(typeConverter, canPromote); }