List of usage examples for java.lang.reflect Field isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.zodiark.server.ZodiarkObjectFactory.java
@Override public <T, U extends T> T newClassInstance(final AtmosphereFramework framework, Class<T> classType, Class<U> tClass) throws InstantiationException, IllegalAccessException { logger.debug("About to create {}", tClass.getName()); if (!added.getAndSet(true) && framework != null) { framework.getAtmosphereConfig().shutdownHook(new AtmosphereConfig.ShutdownHook() { @Override/*from w ww.j a v a 2s . c o m*/ public void shutdown() { timer.shutdown(); } }); framework.getAtmosphereConfig().startupHook(new AtmosphereConfig.StartupHook() { @Override public void started(AtmosphereFramework framework) { injectRepository.clear(); implementationRepository.clear(); instanceRepository.clear(); } }); } Class<? extends T> impl = implement(classType); boolean needsPostConstruct = (impl == null || instanceRepository.get(impl) == null); T instance = impl != null ? newInstance(impl) : tClass.newInstance(); Field[] fields = tClass.equals(instance.getClass()) ? tClass.getDeclaredFields() : impl.getFields(); for (Field field : fields) { if (field.isAnnotationPresent(Inject.class)) { if (field.getType().isAssignableFrom(ObjectMapper.class)) { field.set(instance, inject(ObjectMapper.class)); } else if (field.getType().isAssignableFrom(EventBus.class)) { field.set(instance, inject(EventBus.class)); } else if (field.getType().isAssignableFrom(RestService.class)) { field.set(instance, newClassInstance(framework, RestService.class, RestService.class)); } else if (field.getType().isAssignableFrom(WowzaEndpointManager.class)) { field.set(instance, inject(WowzaEndpointManager.class)); } else if (field.getType().isAssignableFrom(Context.class)) { field.set(instance, new Context() { @Override public <T> T newInstance(Class<T> t) { try { return newClassInstance(framework, t, t); } catch (Exception e) { throw new RuntimeException(e); } } }); } else if (field.getType().isAssignableFrom(AuthConfig.class)) { field.set(instance, newClassInstance(framework, Result.class, AuthConfig.class)); } else if (field.getType().isAssignableFrom(EndpointState.class)) { field.set(instance, newClassInstance(framework, EndpointState.class, EndpointState.class)); } else if (field.getType().isAssignableFrom(StreamingRequest.class)) { field.set(instance, inject(StreamingRequest.class)); } else if (field.getType().isAssignableFrom(ScheduledExecutorService.class)) { field.set(instance, timer); } else if (field.getType().isAssignableFrom(RestClient.class)) { field.set(instance, newClassInstance(framework, RestClient.class, RestClient.class)); } else if (field.getType().isAssignableFrom(URI.class)) { field.set(instance, inject(URI.class)); } } } if (needsPostConstruct) { Method[] methods = tClass.equals(instance.getClass()) ? tClass.getMethods() : instance.getClass().getMethods(); for (Method m : methods) { if (m.isAnnotationPresent(PostConstruct.class)) { try { m.invoke(instance); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } } return instance; }
From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java
/** * Utility method that checks if a field should be excluded from being populated. * * @param field the field to check/*from ww w.j av a 2s.com*/ * @param context the populator context * @return true if the field should be excluded, false otherwise */ private boolean shouldExcludeField(final Field field, final PopulatorContext context) { if (field.isAnnotationPresent(Exclude.class)) { return true; } if (context.getExcludedFields().length == 0) { return false; } String fieldFullName = context.getFieldFullName(field.getName()); for (String excludedFieldName : context.getExcludedFields()) { if (fieldFullName.equalsIgnoreCase(excludedFieldName)) { return true; } } return false; }
From source file:de.cubeisland.engine.module.stats.StatsManager.java
/** * Register a statistic./*from w w w. j av a 2 s . co m*/ * This will make this StatsManager handle the statistic's database connection * and register it as a listener. * * @param statType The stat class to register */ public void register(Class<? extends Stat> statType) { if (!this.started) { throw new IllegalStateException("StatsManager not started!"); } try { // Get the Constructor, and construct a new instance of the Stat. Constructor<? extends Stat> constructor = statType.getConstructor(); Stat stat = constructor.newInstance(); Method init = statType.getMethod("init", this.getClass(), Module.class); init.invoke(stat, this, this.module); // Get or register the stat in the database if (!registeredStats.contains(statType)) { synchronized (this.dsl) { StatsModel model = this.dsl.newRecord(TABLE_STATS).newStatsModel(statType.getName()); model.insert(); registeredStats.add(statType); } } this.stats.put(statType, stat); // Load configured fields for (Field field : statType.getFields()) { if (!field.isAnnotationPresent(Configured.class)) { return; } String name = field.getName(); String[] comment = {}; if (field.isAnnotationPresent(Name.class)) { Name nameAnnotation = field.getAnnotation(Name.class); name = nameAnnotation.value(); } if (field.isAnnotationPresent(Comment.class)) { Comment commentAnnotation = field.getAnnotation(Comment.class); comment = commentAnnotation.value(); } if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (section.hasKey(name)) { section.getNode(name).setComments(comment); field.set(stat, section.get(name)); } else { section.put(name, field.get(stat), comment); } } // Activate hook in the stat stat.activate(); // Register Schedulers for (Method method : stat.getClass().getMethods()) { if (!method.isAnnotationPresent(Scheduled.class)) { continue; } Scheduled annotation = method.getAnnotation(Scheduled.class); long interval; if (annotation.periodFinal()) { interval = annotation.interval(); } else { if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (!section.hasKey("tasks")) { section.put("tasks", new DynamicSection(converterManager), "Intervals for the tasks this statistic schedules"); } else { section.getNode("tasks") .setComments(new String[] { "Intervals for the tasks this statistic schedules" }); } DynamicSection tasks = (DynamicSection) section.get("tasks", DynamicSection.class); if (!tasks.hasKey(annotation.name())) { tasks.put(annotation.name(), annotation.interval(), annotation.comment()); } else { tasks.getNode(annotation.name()).setComments(annotation.comment()); } interval = (Long) tasks.get(annotation.name(), Long.class); } if (!this.tasks.containsKey(statType)) { this.tasks.put(statType, new HashSet<Integer>()); } Set<Integer> tasks = this.tasks.get(statType); Runnable wrapper = new ScheduledMethod(this.module.getLog(), stat, method); TaskManager taskManager = module.getCore().getTaskManager(); if (annotation.async()) { tasks.add(taskManager.runAsynchronousTimer(module, wrapper, 1, interval)); } else { tasks.add(taskManager.runTimer(module, wrapper, 1, interval)); } this.module.getLog().debug("Scheduled method {} at interval {}", annotation.name(), interval); } } catch (ReflectiveOperationException | ConversionException ex) { this.module.getLog().error(ex, "An error occurred while registering statistic"); } this.module.getLog().debug("Registered statistic {}.", statType.getSimpleName()); }
From source file:net.nan21.dnet.core.presenter.converter.ReflookupResolver.java
/** * Do the actual work, update the reference field in the entity based on the * ref-lookup rule.//ww w. j av a 2s . c o m * * @param m * @param e * @param refLookup * @param isInsert * @throws Exception */ private void doRefLookup1(M ds, E e, RefLookup refLookup, boolean isInsert, EntityManager em) throws Exception { String refIdDsFieldName = refLookup.refId(); Object refIdDsFieldValue = this._getDsFieldValue(refIdDsFieldName, ds); String refEntityFieldName = null; Field refIdDsField = this._getDsField(refIdDsFieldName); if (!refIdDsField.isAnnotationPresent(DsField.class)) { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as it is not marked as @DsField "); } else { DsField dsFieldAnnotation = refIdDsField.getAnnotation(DsField.class); /* Obey the noInsert and noUpdate rules. */ if ((isInsert && dsFieldAnnotation.noInsert()) || (!isInsert && dsFieldAnnotation.noUpdate())) { return; } String path = dsFieldAnnotation.path(); if (path.indexOf('.') > 0) { // TODO: handle the deep references also ( a.b.c.id ) refEntityFieldName = path.substring(0, path.indexOf('.')); } else { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as its path(`" + path + "`) in @DsField is not a reference path."); } } Class<?> refClass = this._getEntityField(refEntityFieldName).getType(); Object ref = this._getEntityFieldValue(refEntityFieldName, e); Method setter = this._getEntitySetter(refEntityFieldName); if (refIdDsFieldValue != null && !"".equals(refIdDsFieldValue)) { /* * if there is an ID now in DS which points to a different reference * as the one in the original entity then update it to the new one */ if (ref == null || !((IModelWithId) ref).getId().equals(refIdDsFieldValue)) { setter.invoke(e, em.find(refClass, refIdDsFieldValue)); } } else { /* * If there is no ID given in DS for the reference, try to lookup an * entity based on the given named query which must be a query based * on an unique-key. The given fields as parameters for the * named-query must uniquely identify an entity. */ boolean shouldTryToFindReference = true; String namedQueryName = refLookup.namedQuery(); Map<String, Object> values = new HashMap<String, Object>(); Map<String, Object> namedQueryParams = new HashMap<String, Object>(); if (namedQueryName == null || namedQueryName.equals("")) { shouldTryToFindReference = false; } else { for (Param p : refLookup.params()) { String paramName = p.name(); String fieldName = p.field(); String staticValue = p.value(); Object fieldValue = null; if (staticValue != null && !"".equals(staticValue)) { fieldValue = staticValue; } else { fieldValue = this._getDsFieldValue(fieldName, ds); } if (fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equals(""))) { shouldTryToFindReference = false; break; } else { values.put(fieldName, fieldValue); namedQueryParams.put(paramName, fieldValue); } } } if (shouldTryToFindReference) { Object theReference = null; try { theReference = (findEntityService(refClass)).findByUk(namedQueryName, namedQueryParams); } catch (javax.persistence.NoResultException exception) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, Object> entry : values.entrySet()) { sb.append(" `" + entry.getKey() + "` = `" + entry.getValue() + "`"); } throw new BusinessException("Cannot find `" + refClass.getSimpleName() + "` reference using " + sb.toString() + " for data-source `" + ds.getClass().getSimpleName() + "`"); } setter.invoke(e, theReference); Method refIdFieldInDsSetter = this._getDsSetter(refIdDsFieldName); refIdFieldInDsSetter.invoke(ds, ((IModelWithId) theReference).getId()); } else { setter.invoke(e, (Object) null); } } }
From source file:seava.j4e.presenter.converter.ReflookupResolver.java
/** * Do the actual work, update the reference field in the entity based on the * ref-lookup rule./*from www . j ava 2 s. co m*/ * * @param m * @param e * @param refLookup * @param isInsert * @throws Exception */ private void doRefLookup1(M ds, E e, RefLookup refLookup, boolean isInsert, EntityManager em) throws Exception { String refIdDsFieldName = refLookup.refId(); Object refIdDsFieldValue = this._getDsFieldValue(refIdDsFieldName, ds); String refEntityFieldName = null; Field refIdDsField = this._getDsField(refIdDsFieldName); if (!refIdDsField.isAnnotationPresent(DsField.class)) { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as it is not marked as @DsField "); } else { DsField dsFieldAnnotation = refIdDsField.getAnnotation(DsField.class); /* Obey the noInsert and noUpdate rules. */ if ((isInsert && dsFieldAnnotation.noInsert()) || (!isInsert && dsFieldAnnotation.noUpdate())) { return; } String path = dsFieldAnnotation.path(); if (path.indexOf('.') > 0) { // TODO: handle the deep references also ( a.b.c.id ) refEntityFieldName = path.substring(0, path.indexOf('.')); } else { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as its path(`" + path + "`) in @DsField is not a reference path."); } } Class<?> refClass = this._getEntityField(refEntityFieldName).getType(); Object ref = this._getEntityFieldValue(refEntityFieldName, e); Method setter = this._getEntitySetter(refEntityFieldName); if (refIdDsFieldValue != null && !"".equals(refIdDsFieldValue)) { /* * if there is an ID now in DS which points to a different reference * as the one in the original entity then update it to the new one */ if (ref == null || !((IModelWithId<?>) ref).getId().equals(refIdDsFieldValue)) { setter.invoke(e, em.find(refClass, refIdDsFieldValue)); } } else { /* * If there is no ID given in DS for the reference, try to lookup an * entity based on the given named query which must be a query based * on an unique-key. The given fields as parameters for the * named-query must uniquely identify an entity. */ boolean shouldTryToFindReference = true; String namedQueryName = refLookup.namedQuery(); Map<String, Object> values = new HashMap<String, Object>(); Map<String, Object> namedQueryParams = new HashMap<String, Object>(); if (namedQueryName == null || namedQueryName.equals("")) { shouldTryToFindReference = false; } else { for (Param p : refLookup.params()) { String paramName = p.name(); String fieldName = p.field(); String staticValue = p.value(); Object fieldValue = null; if (staticValue != null && !"".equals(staticValue)) { fieldValue = staticValue; } else { fieldValue = this._getDsFieldValue(fieldName, ds); } if (fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equals(""))) { shouldTryToFindReference = false; break; } else { values.put(fieldName, fieldValue); namedQueryParams.put(paramName, fieldValue); } } } if (shouldTryToFindReference) { Object theReference = null; try { theReference = (findEntityService(refClass)).findByUk(namedQueryName, namedQueryParams); } catch (javax.persistence.NoResultException exception) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, Object> entry : values.entrySet()) { sb.append(" `" + entry.getKey() + "` = `" + entry.getValue() + "`"); } throw new BusinessException(ErrorCode.G_RUNTIME_ERROR, "Cannot find `" + refClass.getSimpleName() + "` reference using " + sb.toString() + " for data-source `" + ds.getClass().getSimpleName() + "`"); } setter.invoke(e, theReference); Method refIdFieldInDsSetter = this._getDsSetter(refIdDsFieldName); refIdFieldInDsSetter.invoke(ds, ((IModelWithId<?>) theReference).getId()); } else { setter.invoke(e, (Object) null); } } }
From source file:cz.zcu.kiv.eegdatabase.logic.indexing.PojoIndexer.java
/** * Creates a document for indexing. The document consists of values of fields having indexing annotations. * Depending on the annotation type, fields are either put to the document or traversed recursively to pick * property values of nested objects.//from www .jav a2 s . co m * @param instance Parent object to be indexed, * @param level Current level of traversal. Can be either parent or child level. In case of the parent level, the * algorithm can continue indexing the child elements located in the child level. In both levels * indexing of String and primitive types is allowed. * @return Field-value pairs representing a document to be indexed. * @throws IllegalAccessException * @throws NoSuchMethodException * @throws InvocationTargetException */ private Map<String, Object> getDocumentFromAnnotatedFields(Object instance, int level) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Map<String, Object> solrFields = new HashMap<String, Object>(); Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { // check presence of the SolrField annotation for each field if (field.isAnnotationPresent(SolrField.class)) { field.setAccessible(true); // necessary since all fields are private Object fieldValue = field.get(instance); // actual value of the annotated field log.debug(instance.getClass().getName()); // null values are skipped if (fieldValue == null) { continue; } String fieldName = field.getAnnotation(SolrField.class).name().getValue(); if (level == LEVEL_CHILD) { fieldName = "child_" + fieldName; } log.debug("Indexing - field: " + fieldName + " value: " + fieldValue.toString()); // POJO has more fields having the same annotation parameter if (solrFields.containsKey(fieldName)) { solrFields.put(fieldName, solrFields.get(fieldName) + " " + fieldValue); } // the annotated value is being read for the first time else { solrFields.put(fieldName, fieldValue); } } // traverse collections and objects of the parent object else if (level == LEVEL_PARENT) { // check if it is a collection if (field.isAnnotationPresent(Indexed.class) && Collection.class.isAssignableFrom(field.getType())) { field.setAccessible(true); // necessary since all fields are private Object collectionInstance = field.get(instance); if (collectionInstance == null) { continue; } // convert the collection to an array to enable transparent manipulation independent // on the specific collection subclass Method objectToArray = field.getType().getMethod("toArray"); Object array = objectToArray.invoke(collectionInstance); // get array size int length = Array.getLength(array); Map<String, List<Object>> solrFieldsChildren = new HashMap<String, List<Object>>(); for (int i = 0; i < length; i++) { Object element = Array.get(array, i); // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(element, LEVEL_CHILD); // add all field-value pairs of each object of the collection to the map of the whole collection for (Map.Entry<String, Object> entry : solrFieldsChild.entrySet()) { if (solrFieldsChildren.containsKey(entry.getKey())) { List<Object> list = solrFieldsChildren.get(entry.getKey()); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } else { List<Object> list = new ArrayList<Object>(); list.add(entry.getValue()); solrFieldsChildren.put(entry.getKey(), list); } } } // add the index values of the children from the collection to the parent fields solrFields.putAll(solrFieldsChildren); } // check if it's an object else if (field.isAnnotationPresent(Indexed.class) && field.getType().isInstance(Object.class)) { // scan only the @SolrField-annotated fields of the child objects Map<String, Object> solrFieldsChild = getDocumentFromAnnotatedFields(field.get(instance), LEVEL_CHILD); solrFields.putAll(solrFieldsChild); } } } return solrFields; }
From source file:net.bafeimao.umbrella.support.data.entity.AbstractEntityParser.java
/** * ????????/* ww w . ja va2 s . c om*/ * * @param field * @return ?? */ protected Converter<String, ?> getConverter(Field field) { Class<?> fieldType = field.getType(); if (field.getName().equals("id")) { // TODO ??? fieldType = Long.class; } Converter<?, ?> converter = convertersByType.get(fieldType); if (converter == null && field.isAnnotationPresent(DataConverter.class)) { DataConverter anno = field.getAnnotation(DataConverter.class); Class<?> converterClass = anno.value(); try { converter = (Converter<?, ?>) converterClass.newInstance(); convertersByType.put(field.getType(), converter); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return (Converter<String, ?>) converter; }
From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java
private boolean isFieldPersistable(Field field) { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(Column.class)) { return true; }/* w w w . j a va 2 s . c o m*/ return false; }
From source file:net.ymate.framework.commons.XPathHelper.java
private <T> T __doWrapperValues(Object parentNode, ClassUtils.BeanWrapper<T> _beanWrapper) throws XPathExpressionException, IllegalAccessException { for (Field _field : _beanWrapper.getFields()) { if (_field.isAnnotationPresent(XPathNode.class)) { XPathNode _fieldNodeAnno = _field.getAnnotation(XPathNode.class); if (_fieldNodeAnno.child()) { Object _childNode = StringUtils.isNotBlank(_fieldNodeAnno.value()) ? getNode(parentNode, _fieldNodeAnno.value()) : parentNode;/*from w ww.ja va2 s .c o m*/ if (_childNode != null) { Object _childObject = null; Object _fieldValue = _beanWrapper.getValue(_field); // if (!INodeValueParser.class.equals(_fieldNodeAnno.parser())) { try { INodeValueParser _parser = _fieldNodeAnno.parser().newInstance(); _childObject = _parser.parse(this, parentNode, _field.getType(), _fieldValue); } catch (InstantiationException e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } else { if (_fieldValue != null) { _childObject = __toObject(_childNode, _fieldValue); } else { _childObject = __toObject(_childNode, Void.class.equals(_fieldNodeAnno.implClass()) ? _field.getType() : _fieldNodeAnno.implClass()); } } _beanWrapper.setValue(_field, _childObject); } } else { String _value = StringUtils.defaultIfBlank(StringUtils.isNotBlank(_fieldNodeAnno.value()) ? getStringValue(parentNode, _fieldNodeAnno.value()) : null, StringUtils.trimToNull(_fieldNodeAnno.defaultValue())); if (!INodeValueParser.class.equals(_fieldNodeAnno.parser())) { try { INodeValueParser _parser = _fieldNodeAnno.parser().newInstance(); _beanWrapper.setValue(_field, BlurObject.bind(_parser.parse(this, parentNode, _field.getType(), _value)) .toObjectValue(_field.getType())); } catch (InstantiationException e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } else { _beanWrapper.setValue(_field, BlurObject.bind(_value).toObjectValue(_field.getType())); } } } } return _beanWrapper.getTargetObject(); }
From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java
/** * This tests the class generated when formatDateTimes config option is set to FALSE * The field should not have @JsonFormat annotation * //from w w w .j a va2 s . c o m * @throws Exception */ @Test public void testDefaultWhenFormatDateTimesConfigIsFalse() throws Exception { Field field = classWhenConfigIsFalse.getDeclaredField("defaultFormat"); // Verify that no annotation is generated assertEquals(Boolean.FALSE, field.isAnnotationPresent(JsonFormat.class)); }