Example usage for java.lang.reflect Field isAnnotationPresent

List of usage examples for java.lang.reflect Field isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Field isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.blstream.hooks.springframework.mongodb.event.CollectionCascadingMongoEventListener.java

public void onBeforeConvert(final Object source) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*w w  w .ja  v  a  2 s  .c  om*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(DBRef.class)
                    && field.isAnnotationPresent(DBRefCollectionCascade.class)) {
                final Object fieldValue = field.get(source);

                if (fieldValue instanceof Collection<?>) {
                    Collection<?> collection = (Collection<?>) fieldValue;

                    for (Object collectionElement : collection) {
                        DbRefFieldCallback callback = new DbRefFieldCallback();

                        ReflectionUtils.doWithFields(collectionElement.getClass(), callback);

                        if (!callback.isIdFound()) {
                            throw new MappingException(
                                    "Cannot perform cascade save on child object without id set");
                        }

                        mongoOperations.save(collectionElement);
                    }
                }
            }
        }
    });
}

From source file:gr.abiss.calipso.tiers.controller.IFilesModelController.java

@ApiOperation(value = "Update files", notes = "The files are saved using the parameter names of the multipart files contained in this request. "
        + "These are the field names of the form (like with normal parameters), not the original file names.")
@RequestMapping(value = "{id}/files", method = {
        RequestMethod.POST }, headers = ("content-type=multipart/*"), produces = { "application/json",
                "application/xml" })
public default @ResponseBody T updateFiles(@PathVariable ID id, MultipartHttpServletRequest request,
        HttpServletResponse response) {//w  w  w . j ava 2 s  .  co m
    Logger logger = LoggerFactory.getLogger(IFilesModelController.class);

    T entity = this.getService().findById(id);
    try {
        String basePath = new StringBuffer(this.getService().getDomainClass().getSimpleName()).append('/')
                .append(id).append('/').toString();
        String propertyName;
        for (Iterator<String> iterator = request.getFileNames(); iterator.hasNext();) {
            // get the property name
            propertyName = iterator.next();

            // verify the property exists
            Field fileField = GenericSpecifications.getField(this.getService().getDomainClass(), propertyName);
            if (fileField == null || !fileField.isAnnotationPresent(FilePersistence.class)) {
                throw new IllegalArgumentException(
                        "No FilePersistence annotation found for member: " + propertyName);
            }

            // store the file and update the property URL
            String url = this.getFilePersistenceService().saveFile(fileField, request.getFile(propertyName),
                    basePath + propertyName);
            BeanUtils.setProperty(entity, propertyName, url);

        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to update files", e);
    }
    // return the updated entity
    return this.getService().update(entity);
}

From source file:py.una.pol.karaku.business.KarakuBaseLogic.java

@Override
@SuppressWarnings("unchecked")
public K getIdValue(T obj) {

    try {/*from w w  w.jav  a 2s.com*/
        for (Field field : obj.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(Id.class)) {
                field.setAccessible(true);
                K data = (K) field.get(obj);
                field.setAccessible(false);
                return data;
            }
        }
        return null;
    } catch (Exception ex) {
        log.error("Error al obtener el Id", ex);
        return null;
    }
}

From source file:com.blstream.hooks.springframework.mongodb.event.ListCascadingMongoEventListener.java

public void onBeforeConvert(final Object source) {
    ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*from   w  w  w  . j  a  v a 2  s  . c o  m*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(DBRefListCascade.class)) {
                final Object fieldValue = field.get(source);

                if (fieldValue instanceof Collection<?>) {
                    Collection<?> collectionField = (Collection<?>) fieldValue;

                    for (Object collectionFieldElement : collectionField) {
                        DbRefFieldCallback callback = new DbRefFieldCallback();

                        ReflectionUtils.doWithFields(collectionFieldElement.getClass(), callback);

                        if (!callback.isIdFound()) {
                            throw new MappingException(
                                    "Cannot perform cascade save on child object without id set");
                        }

                        mongoOperations.save(fieldValue);
                    }

                } else {
                    throw new MappingException(
                            "Cannot perform cascade save using DBRefListCascade annotation on not collection bean.");
                }
            }
        }
    });
}

From source file:com.cognifide.slice.mapper.impl.processor.SliceReferenceFieldProcessor.java

@Override
public boolean accepts(final Resource resource, final Field field) {
    Class<?> type = field.getType();
    // additional checks of type for performance sake
    return type != String.class && !type.isPrimitive() && field.isAnnotationPresent(SliceReference.class);
}

From source file:net.eledge.android.toolkit.db.abstracts.Dao.java

private List<E> mapToEntities(Cursor cursor) {
    List<E> list = new ArrayList<>();
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {//from  w w  w .j a v a2s  .c  o  m
                try {
                    E instance = clazz.newInstance();
                    for (Field field : clazz.getFields()) {
                        if (field.isAnnotationPresent(Column.class)) {
                            int columnIndex = cursor.getColumnIndex(SQLBuilder.getFieldName(field));
                            if (!cursor.isNull(columnIndex)) {
                                FieldType fieldType = FieldType.getType(field.getType());
                                fieldType.convertToField(instance, field, cursor, columnIndex);
                            }
                        }
                    }
                    list.add(instance);
                } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
                    Log.e(this.getClass().getName(), e.getMessage(), e);
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
    }
    return list;
}

From source file:me.henrytao.observableorm.orm.ObservableModel.java

public Map<String, Object> serialize() throws IllegalAccessException {
    Map<String, Object> map = new HashMap<>();
    Field[] fields = getDeclaredFields();
    for (Field f : fields) {
        if (!f.isAnnotationPresent(Column.class)) {
            continue;
        }//from  ww  w.j a v  a2 s.co m
        Column column = f.getAnnotation(Column.class);
        if (!column.serialize()) {
            continue;
        }
        f.setAccessible(true);
        String name = column.name();
        Object value = f.get(this);
        Class type = f.getType();
        Serializer serializer = serializerMap.get(type);
        if (value == null) {
            continue;
        } else if (serializer != null) {
            map.put(name, serializer.serialize(value));
        } else if (ObservableModel.class.isAssignableFrom(type)) {
            // todo: need to test
            map.put(name, ((ObservableModel) value).serialize());
        } else {
            map.put(name, value);
        }
    }
    return map;
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

private void lookupClass(Class<?> clazz, List<Field> parents) {
    for (Field f : clazz.getDeclaredFields()) {
        if (f.isAnnotationPresent(FilterCriteria.class)) {
            boolean dynamicNestedFields = isDynamicInnerFields(f);
            String searchCriteria;
            String queryCriteria;
            if (of(f.getType().getDeclaredFields()).anyMatch(df -> df.isAnnotationPresent(FilterCriteria.class))
                    || (f.getType().isAnnotationPresent(Document.class)
                            && !f.isAnnotationPresent(DBRef.class))) {
                List<Field> currentParents = new ArrayList<>(parents);
                searchCriteria = parents.isEmpty() ? getSearchCriteria(f)
                        : getSearchCriteria(f, currentParents);
                queryCriteria = parents.isEmpty() ? getQueryCriteria(f) : getQueryCriteria(f, currentParents);
                classCriteria.put(searchCriteria, new CriteriaHolder(searchCriteria, queryCriteria,
                        getDataType(f), f.isAnnotationPresent(DBRef.class), dynamicNestedFields));
                currentParents.add(f);//  w  w w  . j av  a  2  s  . co  m
                lookupClass(f.getType(), currentParents);
            } else {
                searchCriteria = getSearchCriteria(f);
                queryCriteria = getQueryCriteria(f);
                if (parents.isEmpty()) {
                    classCriteria.put(searchCriteria, new CriteriaHolder(searchCriteria, queryCriteria,
                            getDataType(f), f.isAnnotationPresent(DBRef.class), dynamicNestedFields));
                } else {
                    searchCriteria = getSearchCriteria(f, parents);
                    queryCriteria = getQueryCriteria(f, parents);
                    classCriteria.put(getSearchCriteria(f, parents), new CriteriaHolder(searchCriteria,
                            queryCriteria, getDataType(f), false, dynamicNestedFields));
                }
            }
        }
    }
}

From source file:com.CodeSeance.JSeance2.CodeGenXML.TemplateElements.Node.java

public void loadAttributes(Context context) {
    StringBuilder missingParameters = new StringBuilder();
    try {// w  w w  .j  av a 2 s  . c  o m
        Object[] params = evaluateParams(context, arguments);
        int paramNumber = 0;
        for (Field field : this.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(TagParameter.class)) {
                TagParameter annotation = field.getAnnotation(TagParameter.class);

                if (paramNumber < params.length) {
                    Object paramValue = params[paramNumber++];
                    setFieldValue(field, paramValue == null ? annotation.defaultValue() : paramValue);
                } else if (!annotation.required()) {
                    setFieldValue(field, annotation.defaultValue());
                } else {
                    missingParameters
                            .append(missingParameters.length() > 0 ? ", " + field.getName() : field.getName());
                }
            }

        }
    } catch (Exception ex) {
        throw new RuntimeException(ExecutionError.INVALID_TAG_ARGUMENTS.getMessage(arguments,
                position.getLine(), position.getCol(), ex.getMessage()));
    }

    if (missingParameters.length() > 0) {
        throw new RuntimeException(ExecutionError.MISSING_TAG_ARGUMENTS.getMessage(missingParameters,
                position.getLine(), position.getCol()));
    }
}

From source file:com.beetle.framework.web.controller.UploadController.java

private void serviceInject(IUpload upload) throws ControllerException {
    // ?/* w  ww  .  j a va  2 s . co m*/
    if (!this.injectFlag) {
        this.injectFlag = true;// ??
        Field[] fields = upload.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field f : fields) {
                if (f.isAnnotationPresent(ServiceField.class)) {
                    try {
                        ObjectUtil.setFieldValue(upload, f.getName(), this.serviceLookup(f.getType()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new ControllerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                AppLogger.getErrStackTraceInfo(e));
                    }
                } else if (f.isAnnotationPresent(DaoField.class)) {
                    throw new ControllerException("The [" + upload.getClass().getName()
                            + "] cannot use daoField annotation, do not conform to the programming paradigm!");
                }
            }
        }
    }
    //
}