List of usage examples for java.lang Class getAnnotation
@SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
From source file:org.jaqpot.core.elastic.ElasticIndexer.java
public String index(ObjectMapper mapper) { try {//from w ww . java 2s . c om JaqpotEntity strippedEntity = entity; Class<? extends JaqpotEntity> entityClass = entity.getClass(); String entityName = entityClass.getAnnotation(XmlRootElement.class).name(); if ("##default".equals(entityName)) { entityName = entityClass.getSimpleName().toLowerCase(); } Class<? extends AbstractMetaStripper> stripperClass = STRIP_CLUB.get(entityClass); if (stripperClass != null) { try { AbstractMetaStripper stripper = stripperClass.getConstructor(entityClass).newInstance(entity); strippedEntity = stripper.strip(); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(ElasticIndexer.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Impossible! A MetaStripper doesn't have a necessary constructor!"); } } String jsonString = mapper.writeValueAsString(strippedEntity); IndexResponse response = ElasticClient.getClient().prepareIndex("jaqpot", entityName, entity.getId()) .setSource(jsonString).execute().actionGet(); return response.getId(); } catch (JsonProcessingException ex) { Logger.getLogger(ElasticIndexer.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Incredible! JAKSON Couldn't serialize an entity!"); } }
From source file:mitm.djigzo.web.services.security.RoleFilterImpl.java
private void checkRequiredRoles(Page page) throws ClassNotFoundException { String className = componentClassResolver.resolvePageNameToClassName(page.getLogicalName()); Class<?> clazz = Class.forName(className); Secured securedAnnotation = clazz.getAnnotation(Secured.class); if (securedAnnotation != null) { List<ConfigAttribute> configAttributes = new LinkedList<ConfigAttribute>(); for (String auth : securedAnnotation.value()) { configAttributes.add(new SecurityConfig(auth)); }/* www .j a v a2 s .co m*/ ConfigAttributeDefinition configAttributeDefinition = new ConfigAttributeDefinition(configAttributes); InterceptorStatusToken token = null; try { token = securityChecker.checkBefore(configAttributeDefinition); } finally { securityChecker.checkAfter(token, null); } } }
From source file:cn.lambdalib.s11n.SerializationHelper.java
private List<Field> buildExposedFields(Class<?> type) { return FieldUtils.getAllFieldsList(type).stream().filter(f -> { Class<?> declaringClass = f.getDeclaringClass(); SerializeStrategy anno = declaringClass.getAnnotation(SerializeStrategy.class); ExposeStrategy strategy = anno == null ? ExposeStrategy.PUBLIC : anno.strategy(); boolean serializeAll = anno == null ? false : anno.all(); if (f.isAnnotationPresent(SerializeIncluded.class)) { return true; } else if (f.isAnnotationPresent(SerializeExcluded.class)) { return false; } else {//from w w w.j ava 2s . c o m if (!serializeAll && !isS11nType(f.getType())) { return false; } else { int mod = f.getModifiers(); switch (strategy) { case PUBLIC: return Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod); case ALL: return !Modifier.isStatic(mod) && !Modifier.isFinal(mod); default: return false; } } } }).map(f -> { f.setAccessible(true); return f; }).collect(Collectors.toList()); }
From source file:com.bacoder.parser.core.DumpVisitor.java
@Override public void visitBefore(Node node) { String tag = String.format("%s<%s sl=\"%d\" sc=\"%d\" el=\"%d\" ec=\"%d\">\n", Strings.repeat(indent, level), node.getClass().getSimpleName(), node.getStartLine(), node.getStartColumn(), node.getEndLine(), node.getEndColumn()); try {/*from w w w . ja va 2s. c om*/ outputStream.write(tag.getBytes()); Class<? extends Node> clazz = node.getClass(); if (clazz.getAnnotation(DumpTextWithToString.class) != null) { String property = String.format("%s<text>%s</text>\n", Strings.repeat(indent, level + 1), node.toString()); try { outputStream.write(property.getBytes()); } catch (IOException e) { throw new RuntimeException("Unable to write \'" + property + "\'", e); } } else { Field[] fields = node.getClass().getDeclaredFields(); for (Field field : fields) { Class<?> type = field.getType(); if (type.isPrimitive() || type.isEnum() || String.class.isAssignableFrom(type)) { String propertyName = field.getName(); Object value; try { value = PropertyUtils.getSimpleProperty(node, propertyName); String property = String.format("%s<%s>%s</%s>\n", Strings.repeat(indent, level + 1), propertyName, value == null ? "" : StringEscapeUtils.escapeXml(value.toString()), propertyName); try { outputStream.write(property.getBytes()); } catch (IOException e) { throw new RuntimeException("Unable to write \'" + property + "\'", e); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // Ignore the field. } } } } } catch (IOException e) { throw new RuntimeException("Unable to write \'" + tag + "\'", e); } level++; }
From source file:com.cloudera.nav.sdk.model.MetadataModelFactory.java
/** * Create a MetadataModel from entity subclasses and a given namespace. * For now we're assuming the given namespace is used for both the * package of the meta-classes and the custom properties * * @param classes//from www. ja v a2s . c o m * @param namespace */ public MetadataModel newModel(Collection<? extends Class<? extends Entity>> classes, String namespace) { MetadataModel model = new MetadataModel(); MetaClassPackage pkg = MetaClassPackage.newPackage(namespace); model.setPackages(Sets.newHashSet(pkg)); Namespace ns = Namespace.newNamespace(namespace); model.setNamespaces(Sets.newHashSet(ns)); Set<MetaClass> metaClasses = Sets.newHashSet(); Map<String, CustomProperty> mPropertyMap = Maps.newHashMap(); Map<String, Set<String>> mappings = Maps.newHashMap(); MetaClass mClass; for (Class<? extends Entity> aClass : classes) { MClass ann = aClass.getAnnotation(MClass.class); mClass = MetaClass.newClass(pkg.getName(), ann.model()); metaClasses.add(mClass); // get all @MProperty's (including inherited ones) Map<Field, Method> properties = MClassUtil.getAnnotatedProperties(aClass, MProperty.class); Class<?> valueType; Set<String> classMappings = Sets.newHashSet(); for (Map.Entry<Field, Method> entry : properties.entrySet()) { valueType = entry.getKey().getType(); MProperty pAnn = entry.getKey().getAnnotation(MProperty.class); if (valueType != UDPChangeSet.class && valueType != TagChangeSet.class && pAnn.register()) { String pName = StringUtils.isEmpty(pAnn.attribute()) ? entry.getKey().getName() : pAnn.attribute(); boolean multiValued = Collection.class.isAssignableFrom(valueType); if (checkExitingProperties(pName, pAnn, multiValued, mPropertyMap)) { mPropertyMap.put(pName, CustomProperty.newProperty(ns.getName(), pName, pAnn.fieldType(), multiValued, pAnn.values())); classMappings.add(ns.getName() + "." + pName); } } } mappings.put(pkg.getName() + "." + mClass.getName(), classMappings); } model.setClasses(metaClasses); model.setProperties(Sets.newHashSet(mPropertyMap.values())); model.setMappings(mappings); return model; }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
public static APIResourceModel processRestClass(Class resource, String rootPath) { APIResourceModel resourceModel = new APIResourceModel(); resourceModel.setClassName(resource.getName()); resourceModel.setResourceName(/* w w w . ja va 2s . c o m*/ String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName()))); APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class); if (aPIDescription != null) { resourceModel.setResourceDescription(aPIDescription.value()); } Path path = (Path) resource.getAnnotation(Path.class); if (path != null) { resourceModel.setResourcePath(rootPath + "/" + path.value()); } RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { resourceModel.setRequireAdmin(true); } //class parameters mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields()); //methods ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); int methodId = 0; for (Method method : resource.getDeclaredMethods()) { APIMethodModel methodModel = new APIMethodModel(); methodModel.setId(methodId++); //rest method List<String> restMethods = new ArrayList<>(); GET getMethod = (GET) method.getAnnotation(GET.class); POST postMethod = (POST) method.getAnnotation(POST.class); PUT putMethod = (PUT) method.getAnnotation(PUT.class); DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class); if (getMethod != null) { restMethods.add("GET"); } if (postMethod != null) { restMethods.add("POST"); } if (putMethod != null) { restMethods.add("PUT"); } if (deleteMethod != null) { restMethods.add("DELETE"); } methodModel.setRestMethod(String.join(",", restMethods)); if (restMethods.isEmpty()) { //skip non-rest methods continue; } //produces Produces produces = (Produces) method.getAnnotation(Produces.class); if (produces != null) { methodModel.setProducesTypes(String.join(",", produces.value())); } //consumes Consumes consumes = (Consumes) method.getAnnotation(Consumes.class); if (consumes != null) { methodModel.setConsumesTypes(String.join(",", consumes.value())); } aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class); if (aPIDescription != null) { methodModel.setDescription(aPIDescription.value()); } path = (Path) method.getAnnotation(Path.class); if (path != null) { methodModel.setMethodPath(path.value()); } requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { methodModel.setRequireAdmin(true); } try { if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) { APIValueModel valueModel = new APIValueModel(); DataType dataType = (DataType) method.getAnnotation(DataType.class); boolean addResponseObject = true; if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) { addResponseObject = false; } if (addResponseObject) { valueModel.setValueObjectName(method.getReturnType().getSimpleName()); ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class); Class returnTypeClass; if (returnType != null) { returnTypeClass = returnType.value(); } else { returnTypeClass = method.getReturnType(); } if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) { if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) { try { valueModel.setValueObject( objectMapper.writeValueAsString(returnTypeClass.newInstance())); mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]), false); aPIDescription = (APIDescription) returnTypeClass .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setValueDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", returnTypeClass)); } } } if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel.setTypeObject( objectMapper.writeValueAsString(dataType.value().newInstance())); mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false); aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", dataType.value())); } } methodModel.setResponseObject(valueModel); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //method parameters mapMethodParameters(methodModel.getMethodParams(), method.getParameters()); //Handle Consumed Objects mapConsumedObjects(methodModel, method.getParameters()); resourceModel.getMethods().add(methodModel); } Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>()); return resourceModel; }
From source file:org.craftercms.commons.security.permissions.annotations.HasPermissionAnnotationHandler.java
protected HasPermission getHasPermissionAnnotation(Method method, ProceedingJoinPoint pjp) { HasPermission hasPermission = method.getAnnotation(HasPermission.class); if (hasPermission == null) { Class<?> targetClass = pjp.getTarget().getClass(); hasPermission = targetClass.getAnnotation(HasPermission.class); }//from w ww. ja v a2s . co m return hasPermission; }
From source file:com.esofthead.mycollab.common.interceptor.aspect.TraceableCreateAspect.java
@AfterReturning("execution(public * com.esofthead.mycollab..service..*.saveWithSession(..)) && args(bean, username)") public void traceSaveActivity(JoinPoint joinPoint, Object bean, String username) { Advised advised = (Advised) joinPoint.getThis(); Class<?> cls = advised.getTargetSource().getTargetClass(); Traceable traceableAnnotation = cls.getAnnotation(Traceable.class); if (traceableAnnotation != null) { try {//www . j av a2 s.c o m ActivityStreamWithBLOBs activity = constructActivity(cls, traceableAnnotation, bean, username, ActivityStreamConstants.ACTION_CREATE); activityStreamService.save(activity); } catch (Exception e) { LOG.error("Error when save activity for save action of service " + cls.getName(), e); } } }
From source file:com.esofthead.mycollab.common.interceptor.aspect.TraceableCreateAspect.java
@AfterReturning("execution(public * com.esofthead.mycollab..service..*.removeWithSession(..)) && args(bean, username, sAccountId)") public void traceDeleteActivity(JoinPoint joinPoint, Object bean, String username, Integer sAccountId) { Advised advised = (Advised) joinPoint.getThis(); Class<?> cls = advised.getTargetSource().getTargetClass(); Traceable traceableAnnotation = cls.getAnnotation(Traceable.class); if (traceableAnnotation != null) { try {/*from ww w . jav a 2s . c o m*/ ActivityStreamWithBLOBs activity = constructActivity(cls, traceableAnnotation, bean, username, ActivityStreamConstants.ACTION_DELETE); activityStreamService.save(activity); } catch (Exception e) { LOG.error("Error when save activity for save action of service " + cls.getName(), e); } } }
From source file:org.bitsofinfo.util.address.usps.ais.DefaultIdGenerator.java
private synchronized void buildCaches() throws Exception { if (typeCache.size() == 0) { Set<Class> clazzes = uspsUtils.getUSPSRecordClasses(); for (Class clazz : clazzes) { USPSRecordContext context = (USPSRecordContext) clazz.getAnnotation(USPSRecordContext.class); StringBuffer tmp = new StringBuffer(); for (USPSProductType pt : context.productTypes()) { tmp.append(pt.getId());//from w ww . j av a 2s . c om } String prefix = tmp.toString() + context.copyrightDetailCode(); typeCache.put(clazz, prefix); prefixCache.put(prefix, clazz); } } }