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:adalid.core.AbstractDataArtifact.java

private void annotateBigDecimalField(Field field) {
    Class<? extends Annotation> annotationClass = BigDecimalField.class;
    Class<?>[] validTypes = new Class<?>[] { BigDecimalParameter.class, BigDecimalProperty.class };
    boolean log = isParameter() || depth() == 0;
    _annotatedWithBigDecimalField = field.isAnnotationPresent(annotationClass)
            && XS1.checkFieldAnnotation(log, field, annotationClass, validTypes);
    /**//*from  ww  w .  j a  va 2 s  .  c o m*/
    if (_annotatedWithBigDecimalField) {
        BigDecimalField annotation = field.getAnnotation(BigDecimalField.class);
        int precision = annotation.precision();
        int scale = annotation.scale();
        BigDecimalData data = (BigDecimalData) this;
        if (precision >= 1 && precision <= Constants.MAX_DECIMAL_PRECISION) {
            data.setPrecision(precision);
            if (scale <= precision) {
                data.setScale(scale > 0 ? scale : 0);
            } else if (log) {
                logger.error(getDeclaringArtifactClassName() + "." + field.getName()
                        + " has an invalid decimal scale");
                TLC.getProject().getParser().increaseErrorCount();
            }
        } else if (log) {
            logger.error(getDeclaringArtifactClassName() + "." + field.getName()
                    + " has an invalid decimal precision");
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:com.sos.JSHelper.Options.JSOptionsClass.java

public StringBuffer IterateAllDataElementsByAnnotation(final Class<?> objC, final Object objP,
        final IterationTypes enuIterate4What, StringBuffer pstrBuffer) {
    final String conMethodName = conClassName + "::IterateAllDataElementsByAnnotation";
    String strCommandLineOptions = "";
    if (objC == null) {
        throw new JobSchedulerException(conMethodName + ": objSegment is null, but must be not null");
    }//from w w w .j  a  v  a2s .c o m
    Field objField = null;
    SOSOptionElement.gflgProcessHashMap = true;
    try {
        final Field objFields[] = objC.getFields();
        final StringBuffer strXML = new StringBuffer("");
        final String strT = objC.getName();
        if (enuIterate4What == IterationTypes.createXML) {
            strXML.append("<" + strT + " id=" + XmlId.QuotedValue() + ">");
        }
        for (final Field objField2 : objFields) {
            objField = objField2;
            try {
                if (objField.isAnnotationPresent(JSOptionDefinition.class)) {
                    final SOSOptionElement objDE = (SOSOptionElement) objField.get(objP);
                    if (objDE == null) {
                        // final JSOptionsClass objO = (JSOptionsClass) objField.get(objField);
                        // if (objO != null) {
                        // System.out.println("oooooooField : " + objField.getName());
                        //
                        // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                        // else {
                        // System.out.println("*******Field : " + objField.getName());
                        // final Object objO2 = objField.getDeclaringClass();
                        // System.out.println(objField.getType().toString());
                        // // objField.Iterate(enuIterate4What);
                        // // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                    } else {
                        if (enuIterate4What == IterationTypes.setPrefix) {
                            objDE.setPrefix(strAlternativePrefix);
                        }
                        if (enuIterate4What == IterationTypes.setRecord) {
                            SOSOptionElement.gflgProcessHashMap = true;
                            objDE.gflgProcessHashMap = true;
                            objDE.MapValue();
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getRecord) {
                            // objDE.BuildRecord(pstrBuffer);
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.CheckMandatory) {
                            objDE.CheckMandatory();
                        }
                        if (enuIterate4What == IterationTypes.toOut) {
                            System.out.println(objDE.toString());
                        }
                        if (enuIterate4What == IterationTypes.toString) {
                            pstrBuffer.append(objDE.toString() + "\n");
                        }
                        if (enuIterate4What == IterationTypes.DirtyToString) {
                            if (objDE.isDirty() == true) {
                                pstrBuffer.append(objDE.DirtyToString() + "\n");
                            }
                        }
                        if (enuIterate4What == IterationTypes.createXML) {
                            strXML.append(objDE.toXml());
                        }
                        if (enuIterate4What == IterationTypes.setDefaultValues) {
                            final String strV = objDE.Value();
                            if (strV.length() <= 0) {
                                objDE.Value(objDE.DefaultValue());
                            }
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.clearAllValues) {
                            objDE.Value("");
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getCommandLine) {
                            pstrBuffer.append(objDE.toCommandLine());
                        }

                        if (enuIterate4What == IterationTypes.countSegmentFields) {
                            // System.out.println("+++++Field : " + objField.getName());
                        }
                        /**
                         * hier versuchen wir herauszubekommen, ob es
                         * in dieser Instanz (weitere) geschachtelte Optionen gibt.
                         * Falls ja, wird die geforderte Funktion auch fr alle diese
                         * Instanzen ausgefhrt.
                         */
                        IterateAllDataElementsByAnnotation(objDE.getClass(), objDE, enuIterate4What,
                                pstrBuffer);
                    }
                } // if (objField.isAnnotationPresent(IDocSegmentField.class))
            } // try
            catch (final ClassCastException objException) {
            } catch (final Exception objE) {
                objE.printStackTrace();
                throw new RuntimeException(objE);
            } finally {
                //
            } // finally
        }
        if (enuIterate4What == IterationTypes.createXML) { // CreateXML
            strXML.append("</" + strT + ">");
            pstrBuffer = strXML;
        }
    } catch (final Exception objException) {
        objException.printStackTrace();
        throw new RuntimeException(objException);
    } finally {
        SOSOptionElement.gflgProcessHashMap = false;
        //
    } // finally
    return pstrBuffer;
}

From source file:adalid.core.AbstractDataArtifact.java

private void annotateParentProperty(Field field) {
    //      Class<?> declaringClass = getDeclaringEntity().getDataClass();
    Class<?> declaringClass = field.getDeclaringClass();
    Class<? extends Annotation> annotationClass = ParentProperty.class;
    Class<?>[] validTypes = new Class<?>[] { declaringClass };
    boolean log = depth() == 1;
    boolean aye = field.isAnnotationPresent(annotationClass)
            && XS1.checkKeyPropertyFieldAnnotation(log, field, KeyProperty.PARENT, validTypes);
    /**//*w  w  w.ja  v a2 s .  com*/
    if (aye) {
        Field previous = getDeclaringArtifact().put(annotationClass, field);
        if (previous == null) {
            _annotatedWithParentProperty = true;
        } else if (log) {
            XS1.logDuplicateAnnotation(field, annotationClass, previous);
        }
    }
}

From source file:adalid.core.AbstractDataArtifact.java

private void annotateNumericDataGen(Field field) {
    Class<? extends Annotation> annotationClass = NumericDataGen.class;
    Class<?>[] validTypes = new Class<?>[] { BigDecimalProperty.class, BigIntegerProperty.class,
            ByteProperty.class, ShortProperty.class, IntegerProperty.class, LongProperty.class,
            FloatProperty.class, DoubleProperty.class };
    boolean log = depth() == 0;
    boolean annotated = field.isAnnotationPresent(annotationClass)
            && XS1.checkFieldAnnotation(log, field, annotationClass, validTypes);
    /**//*from www  . ja v a2s .c o m*/
    if (annotated) {
        NumericDataGen annotation = field.getAnnotation(NumericDataGen.class);
        _dataGenType = annotation.type();
        //          _dataGenSeriesStart = annotation.start();
        //          _dataGenSeriesStop = annotation.stop();
        //          _dataGenSeriesStep = annotation.step();
        _dataGenSeriesStart = Math.min(10000, Math.max(1, annotation.start()));
        _dataGenSeriesStop = Math.min(10000, Math.max(1, annotation.stop()));
        _dataGenSeriesStep = Math.min(10000, Math.max(1, annotation.step()));
        _dataGenFunction = StringUtils.trimToNull(annotation.function());
        _dataGenNullable = Math.min(100, Math.max(0, annotation.nullable()));
        _dataGenMin = someIntegerValue(field, annotation.min());
        _dataGenMax = someIntegerValue(field, annotation.max());
        _dataGenNumericAction = annotation.action();
        _dataGenFactor = someBigDecimalValue(field, annotation.factor());
        _annotatedWithDataGen = true;
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void refreshManyToOneLinkedWithId(INakedObject o, com.hiperf.common.ui.shared.util.Id id,
        EntityManager em)//from  w  ww . j a  va  2s . c om
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    Class<? extends INakedObject> clazz = o.getClass();
    Field f = clazz.getDeclaredField(id.getFieldNames().get(0));
    if (f.isAnnotationPresent(Id.class)) {
        int i = 0;
        for (String name : id.getFieldNames()) {
            f = clazz.getDeclaredField(id.getFieldNames().get(i));
            String columnName = name;
            if (f.isAnnotationPresent(Column.class)) {
                columnName = f.getAnnotation(Column.class).name();
            }
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(ManyToOne.class) && field.isAnnotationPresent(JoinColumn.class)
                        && field.getAnnotation(JoinColumn.class).name().equalsIgnoreCase(columnName)) {
                    boolean acc = field.isAccessible();
                    try {
                        if (!acc)
                            field.setAccessible(true);
                        Object pk = id.getFieldValues().get(i);
                        if (PersistenceManager.isLocal(pk)) {
                            boolean acc2 = f.isAccessible();
                            try {
                                if (!acc2) {
                                    f.setAccessible(true);
                                }
                                pk = f.get(o);
                            } finally {
                                if (!acc2) {
                                    f.setAccessible(false);
                                }
                            }
                            if (!PersistenceManager.isLocal(pk))
                                field.set(o, em.find(field.getType(), pk));
                        } else
                            field.set(o, em.find(field.getType(), pk));
                    } finally {
                        field.setAccessible(acc);
                    }
                    break;
                }

            }
            i++;
        }
    } else {
        //TODO
    }

}

From source file:adalid.core.AbstractDataArtifact.java

private void annotateInstanceReference(Field field) {
    Operation declaringOperation = getDeclaringOperation();
    //      Class<?> declaringClass = declaringOperation.getDeclaringEntity().getDataType();
    //      Class<?> declaringClass = field.getDeclaringClass().getDeclaringClass();
    Class<?> declaringClass = declaringOperation.getDeclaringField().getDeclaringClass();
    Class<? extends Annotation> annotationClass = InstanceReference.class;
    Class<?>[] validTypes = new Class<?>[] { declaringClass };
    boolean log = true;
    boolean aye = field.isAnnotationPresent(annotationClass)
            && XS1.checkFieldAnnotation(log, field, annotationClass, validTypes);
    /**///from  w w  w.jav a 2s . co m
    if (aye) {
        Field previous = getDeclaringArtifact().put(annotationClass, field);
        if (previous == null) {
            _annotatedWithInstanceReference = true;
            declaringOperation.setOperationKind(OperationKind.INSTANCE);
        } else if (log) {
            XS1.logDuplicateAnnotation(field, annotationClass, previous);
        }
    }
    /**/
    if (_annotatedWithInstanceReference) {
        _required = true;
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private boolean doPersist(ObjectsToPersist toPersist, String userName,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em, boolean validateBefore, Locale locale, boolean processExceptions)
        throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    try {/* w w w. j a v  a  2  s .c o  m*/
        Validator validator = validatorFactory.getValidator();
        List<INakedObject> toInsert = toPersist.getInsertedObjects();
        if (toInsert != null) {
            int max = 100 * toInsert.size();
            int idx = -1;
            int k = -1;
            int s = toInsert.size();
            int prevSize = s;
            while (!toInsert.isEmpty()) {

                if (s == toInsert.size()) {
                    k++;
                } else
                    k = 0;
                if (k == 1) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list");
                    return false;
                }

                if (prevSize == toInsert.size()) {
                    idx++;
                } else {
                    idx = 0;
                    prevSize = toInsert.size();
                }
                if (idx > max) {
                    logger.log(Level.FINE,
                            "Impossible to persist data : one linked object not found in toInsert list...");
                    return false;
                }
                Iterator<INakedObject> it = toInsert.iterator();
                while (it.hasNext()) {
                    INakedObject o = (INakedObject) it.next();
                    String className = o.getClass().getName();
                    if (o instanceof IAuditable) {
                        IAuditable aud = (IAuditable) o;
                        aud.setCreateUser(userName);
                        aud.setCreateDate(new Date());
                    }

                    Set<PropertyDescriptor> ids = idsByClassName.get(className);

                    processLinkedCollectionsBeforePersist(o, collectionsByClassName.get(className));

                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o, lazysByClassName.get(className),
                            toPersist))
                        continue;
                    if (!processLinkedObjectsBeforePersist(newIdByOldId, o,
                            eagerObjectsByClassName.get(className), toPersist))
                        continue;

                    if (generatedIdClasses.contains(className)) {
                        PropertyDescriptor idPd = ids.iterator().next();
                        Object oldId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        Object[] args = new Object[1];
                        if (!idPd.getPropertyType().isPrimitive())
                            args[0] = null;
                        else
                            args[0] = 0L;
                        idPd.getWriteMethod().invoke(o, args);

                        if (validateBefore) {
                            Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                            if (errors != null && !errors.isEmpty()) {
                                it.remove();
                                continue;
                            }
                            try {
                                em.persist(o);
                            } catch (Exception e) {
                                it.remove();
                                continue;
                            }
                        } else
                            em.persist(o);
                        Object newId = idPd.getReadMethod().invoke(o, StorageService.emptyArg);
                        newIdByOldId.put(oldId, new IdHolder(newId, className));
                        List<Object> idVals = new ArrayList<Object>(1);
                        idVals.add(oldId);
                        List<String> idFields = new ArrayList<String>(1);
                        idFields.add(idPd.getName());
                        res.put(new com.hiperf.common.ui.shared.util.Id(idFields, idVals), o);

                        it.remove();
                    } else {
                        com.hiperf.common.ui.shared.util.Id id = getId(o, ids);
                        int i = 0;
                        boolean toProcess = true;
                        for (Object idVal : id.getFieldValues()) {
                            if ((idVal instanceof Long && ((Long) idVal).longValue() < 0)
                                    || (idVal instanceof String
                                            && ((String) idVal).startsWith(PersistenceManager.SEQ_PREFIX))) {
                                IdHolder newIds = newIdByOldId.get(idVal);
                                if (newIds != null) {
                                    String att = id.getFieldNames().get(i);
                                    for (PropertyDescriptor idPd : ids) {
                                        if (idPd.getName().equals(att)) {
                                            Object[] args = new Object[1];
                                            args[0] = newIds.getId();
                                            idPd.getWriteMethod().invoke(o, args);
                                            break;
                                        }
                                    }
                                } else {
                                    toProcess = false;
                                    break;
                                }
                            }
                            i++;
                        }
                        if (toProcess) {
                            if (validateBefore) {
                                Set<ConstraintViolation<INakedObject>> errors = validator.validate(o);
                                if (errors != null && !errors.isEmpty()) {
                                    it.remove();
                                    continue;
                                }
                                try {
                                    refreshManyToOneLinkedWithId(o, id, em);
                                    em.persist(o);
                                } catch (Exception e) {
                                    it.remove();
                                    continue;
                                }
                            } else {
                                refreshManyToOneLinkedWithId(o, id, em);
                                em.persist(o);
                            }
                            id = getId(o, ids);
                            res.put(id, o);
                            it.remove();
                        }
                    }
                }
            }
        }
        Map<String, Set<com.hiperf.common.ui.shared.util.Id>> toDelete = toPersist
                .getRemovedObjectsIdsByClassName();
        if (toDelete != null) {
            for (String className : toDelete.keySet()) {
                Set<com.hiperf.common.ui.shared.util.Id> ids = toDelete.get(className);
                Class<?> clazz = Class.forName(className);
                Map<Field, Field> toRemove = null;
                if (ids != null && !ids.isEmpty()) {
                    com.hiperf.common.ui.shared.util.Id id = ids.iterator().next();
                    if (id.getFieldValues().size() > 1) {
                        toRemove = new HashMap<Field, Field>();
                        Field[] fields = clazz.getDeclaredFields();
                        for (Field f : fields) {
                            if (f.isAnnotationPresent(ManyToOne.class)) {
                                Field[] ff = f.getType().getDeclaredFields();
                                for (Field lf : ff) {
                                    OneToMany ann = lf.getAnnotation(OneToMany.class);
                                    if (ann != null && ann.targetEntity() != null
                                            && ann.targetEntity().equals(clazz)) {
                                        toRemove.put(f, lf);
                                    }
                                }
                            }
                        }
                        // TODO : manage annotations on the getters...
                    }
                }
                for (com.hiperf.common.ui.shared.util.Id id : ids) {
                    INakedObject no = getObject(clazz, id, em);
                    if (no != null) {
                        if (toRemove != null && !toRemove.isEmpty()) {
                            for (Entry<Field, Field> e : toRemove.entrySet()) {
                                Field f = e.getKey();
                                Field ff = e.getValue();
                                boolean b1 = false;
                                boolean b2 = false;
                                if (!f.isAccessible()) {
                                    f.setAccessible(true);
                                    b1 = true;
                                }
                                if (!ff.isAccessible()) {
                                    ff.setAccessible(true);
                                    b2 = true;
                                }
                                ((Collection) ff.get(f.get(no))).remove(no);
                                if (b1)
                                    f.setAccessible(false);
                                if (b2)
                                    ff.setAccessible(false);
                            }
                        } else {
                            // TODO : manage annotations on the getters...
                        }
                        em.remove(no);
                    }
                }
            }
        }
        Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> toUpdate = toPersist
                .getUpdatedObjects();
        if (toUpdate != null) {
            for (String className : toUpdate.keySet()) {
                Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> map = toUpdate
                        .get(className);
                Class<?> clazz = Class.forName(className);
                Iterator<Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> iterator = map
                        .entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> entry = iterator
                            .next();
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    INakedObject original = getObject(clazz, id, em);
                    Map<String, Serializable> updateMap = entry.getValue();
                    for (String att : updateMap.keySet()) {
                        Object object = updateMap.get(att);
                        if (object != null && object instanceof NakedObjectHandler) {
                            NakedObjectHandler oo = (NakedObjectHandler) object;
                            com.hiperf.common.ui.shared.util.Id objId = oo.getId();
                            if (generatedIdClasses.contains(oo.getClassName())
                                    && newIdByOldId.containsKey(objId.getFieldValues().get(0))) {
                                IdHolder newIds = newIdByOldId.get(objId.getFieldValues().get(0));
                                List<Object> idVals = new ArrayList<Object>(1);
                                idVals.add(newIds.getId());
                                List<String> idFields = new ArrayList<String>(1);
                                idFields.add(idsByClassName.get(oo.getClassName()).iterator().next().getName());
                                com.hiperf.common.ui.shared.util.Id newObjId = new com.hiperf.common.ui.shared.util.Id(
                                        idFields, idVals);
                                object = getObject(Class.forName(oo.getClassName()), newObjId, em);
                            } else {
                                object = getObject(Class.forName(oo.getClassName()), oo.getId(), em);
                            }
                        }
                        updateAttributeValue(className, original, att, object);
                    }
                    if (original instanceof IAuditable) {
                        IAuditable aud = (IAuditable) original;
                        aud.setModifyUser(userName);
                        aud.setModifyDate(new Date());
                    }
                    INakedObject o = null;
                    if (validateBefore) {
                        Set<ConstraintViolation<INakedObject>> errors = validator.validate(original);
                        if (errors != null && !errors.isEmpty()) {
                            iterator.remove();
                            continue;
                        }
                        try {
                            o = em.merge(original);
                            em.flush();
                        } catch (Exception e) {
                            iterator.remove();
                            continue;
                        }
                    } else
                        o = em.merge(original);

                    res.put(id, o);
                }
            }
        }
        processAddedManyToMany(toPersist, res, newIdByOldId, em);
        processRemovedManyToMany(toPersist, res, newIdByOldId, em);
        em.flush();
        return true;
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception", e);
        if (processExceptions) {
            processDbExceptions(locale, e);
            return false;
        } else
            throw new PersistenceException(e);
    }

}

From source file:adalid.core.AbstractEntity.java

private void annotateFilter(Field field) {
    _annotatedWithFilter = field.isAnnotationPresent(Filter.class);
    if (_annotatedWithFilter) {
        Filter annotation = field.getAnnotation(Filter.class);
        _filterInactiveIndicatorProperty = annotation.inactive().toBoolean(_filterInactiveIndicatorProperty);
        _filterOwnerProperty = annotation.owner().toBoolean(_filterOwnerProperty);
        _filterSegmentProperty = annotation.segment().toBoolean(_filterSegmentProperty);
    }/*from   ww w .ja  v a2s.c o m*/
}