List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java
@Override protected Set<Class> findActions() { Set<Class> classes = new HashSet<Class>(); final ApplicationContext ac = this.applicationContext; String[] beanNames = ac.getBeanDefinitionNames(); for (String beanName : beanNames) { // don't care for the bean itself right now, just it's class Class beanClass = ac.getType(beanName); // first of all, check for the @Controller annotation... // then, if it's inside the right package (base controllers package) if (beanClass.isAnnotationPresent(Controller.class) && beanClass.getPackage().getName().startsWith(this.packageLocatorsBasePackage)) { // we must warn in case of a singleton scoped controller if (ac.isSingleton(beanName)) { LOG.warn(""); // TODO }// w ww. j a v a 2 s .c om classes.add(beanClass); } } return classes; }
From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java
@SuppressWarnings("unchecked") public static BigInteger findNumericType(final Class<? extends Node> type) { Class<?> currentType = type; int depth = 0; while (currentType != null) { if (!Node.class.isAssignableFrom(currentType)) { throw logAndReturn(new IllegalStateException( "No SLNode inherited type found with annotation " + DefineHierarchy.class.getSimpleName())); }/*from w w w . j av a2 s.c om*/ if (currentType.isAnnotationPresent(DefineHierarchy.class)) { return numericTypeFromClass((Class<? extends Node>) currentType).add(BigInteger.valueOf(depth)); } currentType = currentType.getSuperclass(); depth++; } throw logAndReturn(new IllegalStateException("No SLNode inherited type found with annotation " + DefineHierarchy.class.getSimpleName() + " for type" + type)); }
From source file:org.apache.syncope.core.logic.LoggerLogic.java
@PreAuthorize("hasRole('" + StandardEntitlement.AUDIT_LIST + "') or hasRole('" + StandardEntitlement.NOTIFICATION_LIST + "')") public List<EventCategoryTO> listAuditEvents() { // use set to avoid duplications or null elements Set<EventCategoryTO> events = new HashSet<>(); try {/*from ww w .java 2s .c o m*/ ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath( SystemPropertyUtils.resolvePlaceholders(this.getClass().getPackage().getName())) + "/**/*.class"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); final Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName()); if (clazz.isAnnotationPresent(Component.class) && AbstractLogic.class.isAssignableFrom(clazz)) { EventCategoryTO eventCategoryTO = new EventCategoryTO(); eventCategoryTO.setCategory(clazz.getSimpleName()); for (Method method : clazz.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers())) { eventCategoryTO.getEvents().add(method.getName()); } } events.add(eventCategoryTO); } } } // SYNCOPE-608 EventCategoryTO authenticationControllerEvents = new EventCategoryTO(); authenticationControllerEvents.setCategory(AuditElements.AUTHENTICATION_CATEGORY); authenticationControllerEvents.getEvents().add(AuditElements.LOGIN_EVENT); events.add(authenticationControllerEvents); events.add(new EventCategoryTO(EventCategoryType.PROPAGATION)); events.add(new EventCategoryTO(EventCategoryType.PULL)); events.add(new EventCategoryTO(EventCategoryType.PUSH)); for (AnyTypeKind anyTypeKind : AnyTypeKind.values()) { for (ExternalResource resource : resourceDAO.findAll()) { EventCategoryTO propEventCategoryTO = new EventCategoryTO(EventCategoryType.PROPAGATION); EventCategoryTO syncEventCategoryTO = new EventCategoryTO(EventCategoryType.PULL); EventCategoryTO pushEventCategoryTO = new EventCategoryTO(EventCategoryType.PUSH); propEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); propEventCategoryTO.setSubcategory(resource.getKey()); syncEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); pushEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase()); syncEventCategoryTO.setSubcategory(resource.getKey()); pushEventCategoryTO.setSubcategory(resource.getKey()); for (ResourceOperation resourceOperation : ResourceOperation.values()) { propEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); syncEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); pushEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase()); } for (UnmatchingRule unmatching : UnmatchingRule.values()) { String event = UnmatchingRule.toEventName(unmatching); syncEventCategoryTO.getEvents().add(event); pushEventCategoryTO.getEvents().add(event); } for (MatchingRule matching : MatchingRule.values()) { String event = MatchingRule.toEventName(matching); syncEventCategoryTO.getEvents().add(event); pushEventCategoryTO.getEvents().add(event); } events.add(propEventCategoryTO); events.add(syncEventCategoryTO); events.add(pushEventCategoryTO); } } for (SchedTask task : taskDAO.<SchedTask>findAll(TaskType.SCHEDULED)) { EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(Class.forName(task.getJobDelegateClassName()).getSimpleName()); events.add(eventCategoryTO); } EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(PullJobDelegate.class.getSimpleName()); events.add(eventCategoryTO); eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK); eventCategoryTO.setCategory(PushJobDelegate.class.getSimpleName()); events.add(eventCategoryTO); } catch (Exception e) { LOG.error("Failure retrieving audit/notification events", e); } return new ArrayList<>(events); }
From source file:org.grycap.gpf4med.ext.GraphConnectorManager.java
public ImmutableList<GraphConnectorInformation> getConnectorsInformation() { final ImmutableList.Builder<GraphConnectorInformation> builder = new ImmutableList.Builder<GraphConnectorInformation>(); // get connectors for (final Map.Entry<String, GraphConnector> connector : connectors().entrySet()) { try {//from w ww .j a v a2 s.c o m // resource classes final Class<?> resourceDefinition = connector.getValue().restResourceDefinition(); final Class<?> resourceImplementation = connector.getValue().restResourceImplementation(); checkArgument(resourceDefinition.isAnnotationPresent(Path.class), "No @Path annotation found, resource definition must be a REST resource"); checkArgument(resourceDefinition.isInterface(), "Resource definition is not an interface"); checkArgument(resourceDefinition.isAssignableFrom(resourceImplementation), "Resource does not implements the definition"); // path final String path = connector.getKey(); checkArgument(path.equals(resourceDefinition.getAnnotation(Path.class).value()), "Path does not coincide with with @Path annotation"); checkArgument(path.matches(".*/v\\d+$"), "Path does not contain API version (e.g. resource/v1)"); // version String version = null; List<String> items = new ArrayList<String>( pluginInformation.getInformation(Information.VERSION, connector.getValue())); if (items != null && items.size() == 1) { version = formatVersion(items.get(0)); } else { throw new IllegalStateException("Cannot find version"); } // author String author = null; items = new ArrayList<String>( pluginInformation.getInformation(Information.AUTHORS, connector.getValue())); if (items != null && items.size() > 0) { String authors = ""; int i = 0; for (; i < items.size() - 1; i++) { authors += items.get(i) + "; "; } authors += items.get(i); author = authors; } // package name String packageName = getPluginPackagename(connector.getValue()); if (StringUtils.isNotBlank(packageName)) { packageName = FilenameUtils.getName(new URI(packageName).getPath()); } // description String description = null; if (StringUtils.isNotBlank(connector.getValue().getDescription())) { description = connector.getValue().getDescription(); } builder.add(new GraphConnectorInformation(path, resourceDefinition, resourceImplementation, version, author, packageName, description)); } catch (Exception e) { LOGGER.warn( "Incomplete information found in the connector: " + connector.getClass().getCanonicalName(), e); } } return builder.build(); }
From source file:org.eclipse.skalli.core.persistence.XStreamPersistence.java
public void saveEntity(EntityService<?> entityService, EntityBase entity, String userId, Map<String, Class<?>> aliases, Set<Converter> converters) throws StorageException, MigrationException { Class<? extends EntityBase> entityClass = entity.getClass(); String category = entityClass.getSimpleName(); String key = entity.getUuid().toString(); if (entityClass.isAnnotationPresent(Historized.class)) { storageService.archive(category, key); }//from ww w.j a va 2s . c om Document newDoc = entityToDom(entity, aliases, converters); mapInheritedExtensions(newDoc, byClassNames(aliases)); Document oldDoc = getEntityAsDom(entityClass, entity.getUuid().toString()); postProcessXML(newDoc, oldDoc, aliases, userId, entityService.getModelVersion()); InputStream is; try { is = XMLUtils.documentToStream(newDoc); } catch (TransformerException e) { throw new StorageException(MessageFormat.format("Failed to transform entity {0} to XML", entity), e); } storageService.write(category, key, is); }
From source file:io.hummer.util.ws.AbstractNode.java
protected boolean isRESTfulService() { Class<?> c = getClass(); do {//from w ww . j a v a2 s .co m if (c.isAnnotationPresent(Path.class)) return true; for (Method m : c.getDeclaredMethods()) { if (m.isAnnotationPresent(Path.class)) return true; } c = c.getSuperclass(); } while (c != null && c != Object.class); return false; }
From source file:org.eclipse.scada.configuration.recipe.lib.internal.DefaultExecutableFactory.java
private Executable lookupByUri(final String name, final Execute execute, final RunnerContext ctx) { logger.debug("Looking up by uri - name: {}, execute: {}", name, execute); try {//www . java2s.co m final URI uri = new URI(name); if (!"bundle-class".equals(uri.getScheme())) { logger.debug("Wrong URI scheme: {}", uri.getScheme()); return null; } final String host = uri.getHost(); String clazzName = uri.getPath(); if (clazzName.startsWith("/")) { // cut of first slash clazzName = clazzName.substring(1); } if (clazzName.startsWith(".")) { clazzName = host + clazzName; } final Class<?> clazz = findBundle(host, clazzName); if (Executable.class.isAssignableFrom(clazz)) { logger.debug("Return by Executable interface"); if (clazz.isAnnotationPresent(Singleton.class)) { if (!ctx.getSingletons().containsKey(clazz)) { ctx.getSingletons().put(clazz, clazz.newInstance()); } return (Executable) ctx.getSingletons().get(clazz); } else { return (Executable) clazz.newInstance(); } } else { String fragment = uri.getFragment(); if (fragment == null) { fragment = "execute"; } logger.debug("Return by call wrapper: #{}", fragment); return createCallWrapper(name, clazz, fragment, execute, ctx); } } catch (final Exception e) { logger.info("Failed to lookup", e); return null; } }
From source file:de.unijena.bioinf.FragmentationTreeConstruction.computation.FragmentationPatternAnalysis.java
private static String getScoringMethodName(Object instance) { Class<? extends Object> someClass = instance.getClass(); if (someClass.isAnnotationPresent(Called.class)) { return someClass.getAnnotation(Called.class).value(); } else/*from ww w . j a va2s .c o m*/ return parameterHelper.toClassName(someClass); }
From source file:de.bund.bva.pliscommon.ueberwachung.common.jmx.ServiceStatistikMBean.java
/** * Durchsucht eine Klasse nach Fehlerobjekten, die nicht null sind, oder Fehlercollections, die nicht leer * sind. Fehlerobjekten sind mit {link FachlicherFehler} annotiert. * * Durchsucht Oberklassen & untergeordnete Objektstrukturen ebenfalls rekursiv. * * @param result//from ww w. j a va2 s. co m * Das Objekt * @param clazz * Die Klasse des Objekts durchsucht werden soll (optional). Kann leergelassen werden beim * Start, kann aber genutzt werden um auf Oberklassen eines Objekts zu prfen. * @param tiefe * tiefe Gibt die aktuelle Tiefe des Aufrufs an. Muss erhht werden wenn man die * Klassenstruktur nach unten durchluft. * @return <code>true</code> wenn Fehler gefunden, ansonsten <code>false</code> */ boolean pruefeObjektAufFehler(final Object result, Class<?> clazz, int tiefe) { boolean fehlerGefunden = false; Class<?> clazzToScan = clazz; // Wenn keine Klasse bergeben, selber ermitteln if (clazzToScan == null) { clazzToScan = result.getClass(); } // Wenn max. Tiefe erreicht, nicht weiter prfen if (tiefe > MAXTIEFE) { LOGISY.trace("Max. Tiefe erreicht, prfe nicht weiter auf fachliche Fehler"); return false; } Field[] fields = clazzToScan.getDeclaredFields(); LOGISY.trace("{} Analysiere Objekt {} (Klasse {}) {} Felder gefunden.", StringUtils.repeat("-", tiefe), result.toString(), clazzToScan.getSimpleName(), fields.length); for (Field field : fields) { if (!ClassUtils.isPrimitiveOrWrapper(field.getType()) && !field.getType().isEnum()) { LOGISY.trace("{} {}.{}, Type {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(), field.getName(), field.getType().getSimpleName()); field.setAccessible(true); try { // Prfe einzelne Klassenfelder (non-Collection) auf annotierten Typ und Vorhandensein if (!Collection.class.isAssignableFrom(field.getType())) { if (field.get(result) != null) { Object fieldObject = field.get(result); if (fieldObject.getClass().isAnnotationPresent(FachlicherFehler.class)) { // Fachliches Fehlerobjekt gefunden return true; } // Wenn kein String, dann prfe rekursiv Objektstruktur if (fieldObject.getClass() != String.class) { fehlerGefunden = pruefeObjektAufFehler(fieldObject, null, tiefe + 1) ? true : fehlerGefunden; } } } else { // Collection, prfen ob fachliche Fehlerliste ParameterizedType type = (ParameterizedType) field.getGenericType(); Class<?> collectionTypeArgument = (Class<?>) type.getActualTypeArguments()[0]; if (collectionTypeArgument.isAnnotationPresent(FachlicherFehler.class)) { // Ist Fehlerliste, prfen ob nicht leer Collection<?> collection = (Collection<?>) field.get(result); if (collection != null && !collection.isEmpty()) { // Fachliche Fehler in Fehlerliste gefunden return true; } } } } catch (IllegalAccessException e) { // Nichts tun, Feld wird ignoriert LOGISY.debug("Feldzugriffsfehler: {}", e.getMessage()); } } } // Die Klassen-Hierachie rekursiv nach oben prfen if (clazzToScan.getSuperclass() != null && !clazzToScan.getSuperclass().equals(Object.class)) { LOGISY.trace("{}> Climb up class hierarchy! Source {}, Target {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(), clazzToScan.getSuperclass()); fehlerGefunden = // Aufruf mit gleicher Tiefe, da Vererbung nach oben durchlaufen wird pruefeObjektAufFehler(result, clazzToScan.getSuperclass(), tiefe) ? true : fehlerGefunden; } return fehlerGefunden; }
From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java
/** * Bean?CSV?// w w w. j a v a 2 s .c o m * Bean@CsvPropAnno(index = ?) * @param objList * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static String bean2Csv(List<?> objList) throws Exception { if (objList == null || objList.size() == 0) { return ""; } TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>(); Object bean0 = objList.get(0); Class<?> clazz = bean0.getClass(); PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor p : arr) { String fieldName = p.getName(); Field field = FieldUtils.getDeclaredField(clazz, fieldName, true); if (field == null) { continue; } boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class); if (isAnno) { CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class); int idx = anno.index(); map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName)); } } // CSVBuffer StringBuffer buff = new StringBuffer(); // ??? boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class); // ??csv if (withTitle) { StringBuffer titleBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE); titleBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(titleBuff.toString())); buff.append(Letters.LF); titleBuff.setLength(0); } for (Object o : objList) { StringBuffer tmpBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); Object val = BeanUtils.getProperty(o, fieldBean.getFieldName()); if (val != null) { tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE); } else { tmpBuff.append(StringUtils.EMPTY); } tmpBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(tmpBuff.toString())); buff.append(Letters.LF); tmpBuff.setLength(0); } return buff.toString(); }