Example usage for java.lang.reflect Field getAnnotations

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

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * @param beanPk le bean  qui on doit vrifier l'existance.
 * @return return true si il existe sinon false.
 *///ww w .j ava 2s .c  o  m
public final boolean isExist(final P beanPk) {
    boolean returnValue = false;
    if (beanPk == null) {
        return returnValue;
    }

    try {
        Connection connection = getConnection();
        try {
            if (null == sql_exist) {
                sql_exist = loadSqlExist(usualTable, fields);
            }

            PreparedStatement pstmt = connection.prepareStatement(sql_exist);
            try {
                int i = 1;
                for (Field field : fields) {
                    Annotation[] annotations = field.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof DaoField) {
                            if (((DaoField) annotation).isPrimary()) {
                                Object obj = BeanUtils.getProperty(beanPk, field.getName());
                                if (obj == null) {
                                    pstmt.setNull(i++, ((DaoField) annotation).type());
                                } else {
                                    setAll(pstmt, i++, obj);
                                }
                            }
                            break;
                        }
                    }
                }

                ResultSet rs = pstmt.executeQuery();
                try {
                    rs.next();
                    returnValue = rs.getInt(1) == 1;
                } finally {
                    rs.close();
                }
                rs = null;
            } finally {
                pstmt.close();
            }
            pstmt = null;
        } finally {
            connection.close();
        }
        connection = null;
    } catch (Exception sqle) {
        log.error("Exist error TrsProduitProfformBean : " + beanPk, sqle);
    }
    return returnValue;
}

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * Persistance du bean annot avec DaoTable ainsi que DaoField. Si pour une
 * raison quelconque une problme survient, l'exception CreateException sera
 * leve.//from  www .  j a v  a  2 s  .c o  m
 * @param bean Le bean d'un type quelconque comportant des annotations daoTable et
 *          DaoField
 * @return Un bean de mme type que celui pass en paramtre. Les donnes du
 *         bean sont rafraichi  partir de la base au cas o celle-ci aurait
 *         modifi les donnes grace  des trigger ou autre.
 * @throws CreateException
 *           Exception leve au sur problme de persistance.
 */
public final T create(final T bean) throws CreateException {
    T returnValue = null;
    try {
        String msg = "Cannot create " + entityClass.getCanonicalName() + " : "
                + ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE);

        if (null == sql_create) {
            sql_create = loadSqlCreate(usualTable, fields);
        }

        returnValue = entityClass.newInstance();
        try {
            Connection connection = getConnection();
            try {
                PreparedStatement pstmt = connection.prepareStatement(sql_create);
                try {
                    int i = 1;
                    for (Field field : fields) {
                        Annotation[] annotations = field.getAnnotations();
                        for (Annotation annotation : annotations) {
                            if (annotation instanceof DaoField) {
                                Object obj = BeanUtils.getProperty(bean, field.getName());
                                if (obj == null) {
                                    pstmt.setNull(i++, ((DaoField) annotation).type());
                                } else {
                                    setAll(pstmt, i++, obj);
                                }
                                break;
                            }
                        }
                    }
                    pstmt.executeUpdate();
                } finally {
                    pstmt.close();
                }
                pstmt = null;
            } finally {
                connection.close();
            }
            connection = null;
        } catch (SQLException sqle) {
            log.error(msg, sqle);
            throw new CreateException(msg, sqle);
        }
        try {
            returnValue = load(bean);
        } catch (FinderException le) {
            log.error(msg, le);
            throw new CreateException(msg, le);
        }
    } catch (Exception e) {
        throw new CreateException(e);
    }
    return returnValue;
}

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * Sauvegarde le bean dans la base. Une exception SaveException peut tre
 * leve si un problme survient.//from   www.  j av a2  s.c o m
 * @param bean le bean  sauvegarder
 * @return Un boolean positif si la mise en jour s'est relement pass.
 * @throws SaveException Problme de persistance
 */
private boolean saveReal(final T bean) throws SaveException {
    boolean returnValue = true;

    String msg = "Cannot save " + entityClass.getCanonicalName() + " : "
            + ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE);
    try {
        Connection connection = getConnection();
        try {
            if (null == sql_save) {
                sql_save = loadSqlSave(usualTable, fields);
            }
            PreparedStatement pstmt = connection.prepareStatement(sql_save);
            try {
                int i = 1;

                for (Field field : fields) {
                    Annotation[] annotations = field.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof DaoField) {
                            if (!((DaoField) annotation).isPrimary()) {
                                Object obj = BeanUtils.getProperty(bean, field.getName());
                                if (obj == null) {
                                    pstmt.setNull(i++, ((DaoField) annotation).type());
                                } else {
                                    setAll(pstmt, i++, obj);
                                }
                            }
                            break;
                        }
                    }
                }

                for (Field field : fields) {
                    Annotation[] annotations = field.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof DaoField) {
                            if (((DaoField) annotation).isPrimary()) {
                                Object obj = BeanUtils.getProperty(bean, field.getName());
                                if (obj == null) {
                                    pstmt.setNull(i++, ((DaoField) annotation).type());
                                } else {
                                    setAll(pstmt, i++, obj);
                                }
                            }
                            break;
                        }
                    }
                }
                returnValue = pstmt.executeUpdate() == 1;
            } finally {
                pstmt.close();
            }
            pstmt = null;
        } finally {
            connection.close();
        }
        connection = null;
    } catch (Exception sqle) {
        log.error(msg, sqle);
        throw new SaveException(msg, sqle);
    }
    return returnValue;
}

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * @param min Numero de ligne minimum/*w  w w .  j a va2s .  co  m*/
 * @param max Numero de ligne maximum
 * @param wherefields Filtre
 * @param orderfields Ordonancement
 * @return la liste des beans
 * @throws FinderException retourne un exception si il y a une erreur.
 * La liste peut tre vide.
 */
public final List<T> findAll(final int min, final int max, final WhereFields wherefields,
        final OrderFields orderfields) throws FinderException {
    List<T> returnValue = null;
    try {
        returnValue = new ArrayList<T>(); // 26.375

        if (null == sql_findAll) {
            sql_findAll = loadSqlFindAll(usualTable, fields);
        }

        String sql = sql_findAll + getSqlWhereAndOrder(wherefields, orderfields);
        // sql = "SELECT * FROM (SELECT ROWNUM N, P.* FROM (" + sql;
        // sql += ") P WHERE ROWNUM < " + max + ")";
        // sql += "WHERE (N>" + min + ")AND(N<" + max + ")";
        try {
            Connection connection = getConnection();
            try {
                Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                try {
                    ResultSet rs = stmt.executeQuery(sql);
                    rs.absolute(min);
                    stmt.setMaxRows(max);
                    try {
                        while (rs.next()) {
                            T data = entityClass.newInstance();
                            int i = 1;

                            for (Field field : fields) {
                                Annotation[] annotations = field.getAnnotations();
                                for (Annotation annotation : annotations) {
                                    if (annotation instanceof DaoField) {
                                        BeanUtils.setProperty(returnValue, field.getName(), rs.getObject(i++));
                                        break;
                                    }
                                }
                            }

                            returnValue.add(data);
                        }
                    } finally {
                        rs.close();
                    }
                    rs = null;
                } finally {
                    stmt.close();
                }
                stmt = null;
            } finally {
                connection.close();
            }
            connection = null;
        } catch (SQLException sqle) {
            log.error(sql, sqle);
            throw new FinderException(sql, sqle);
        }
    } catch (Exception e) {
        throw new FinderException(e);
    }
    return returnValue;

}

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * Retourne le bean  partir de la clef primaire. Si la ligne n'existe pas
 * dans la base alors une exception FinderException est leve.
 * @param beanPk Le bean d'un type quelconque comportant des annotations daoTable et
 *          DaoField. Il represente la clef primaire de la table.
 * @return Un bean de mme type que celui pass en paramtre. Les donnes du
 *         bean sont rafraichi  partir de la base au cas o celle-ci aurait
 *         modifi les donnes grace  des trigger ou autre.
 * @throws FinderException Returne un exception si le bean n'existe pas.
 *//*from  w w  w. j a  va 2s  .  co m*/
public final T load(final P beanPk) throws FinderException {
    T returnValue = null;
    try {

        String msg = "Load error  " + entityClass.getCanonicalName() + " : "
                + ToStringBuilder.reflectionToString(beanPk, ToStringStyle.MULTI_LINE_STYLE);

        try {
            Connection connection = getConnection();
            try {
                if (null == sql_load) {
                    sql_load = loadSqlLoad(usualTable, fields);
                }
                PreparedStatement pstmt = connection.prepareStatement(sql_load);
                try {
                    int i = 1;

                    for (Field field : fields) {
                        Annotation[] annotations = field.getAnnotations();
                        for (Annotation annotation : annotations) {
                            if (annotation instanceof DaoField) {
                                if (((DaoField) annotation).isPrimary()) {
                                    Object obj = BeanUtils.getProperty(beanPk, field.getName());
                                    if (obj == null) {
                                        pstmt.setNull(i++, ((DaoField) annotation).type());
                                    } else {
                                        setAll(pstmt, i++, obj);
                                    }
                                }
                                break;
                            }
                        }
                    }

                    ResultSet rs = pstmt.executeQuery();
                    try {
                        if (!rs.next()) {
                            throw new FinderException(msg);
                        }

                        returnValue = entityClass.newInstance();

                        int j = 1;
                        for (Field field : fields) {
                            Annotation[] annotations = field.getAnnotations();
                            for (Annotation annotation : annotations) {
                                if (annotation instanceof DaoField) {
                                    // field.set(returnValue,
                                    // rs.getObject(j++));
                                    BeanUtils.setProperty(returnValue, field.getName(), rs.getObject(j++));
                                    break;
                                }
                            }
                        }

                    } finally {
                        rs.close();
                    }
                    rs = null;
                } finally {
                    pstmt.close();
                }
                pstmt = null;
            } finally {
                connection.close();
            }
            connection = null;
        } catch (SQLException sqle) {
            log.error(msg, sqle);
            throw new FinderException(msg, sqle);
        }
    } catch (Exception e) {
        throw new FinderException(e);
    }
    return returnValue;
}

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, final Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;
    sharded = ConfigurationProperties.isSharded(configuration);
    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);
    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();/*from www  .j  a va  2  s. co m*/

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }
    assistant.setCurrentNamespace(namespace);
    Collection<String> cacheNames = configuration.getCacheNames();
    for (String name : cacheNames)
        if (namespace.equals(name)) {
            assistant.useCacheRef(name);
            break;
        }

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);
    if (!sharded && (this.idField.isAnnotationPresent(GeneratedValue.class))
            && (((GeneratedValue) this.idField.getAnnotation(GeneratedValue.class))
                    .strategy() == GenerationType.UUID))
        columnFields.add(idField);
    else
        columnFields.add(idField);
    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.isAnnotationPresent(Column.class))
                columnFields.add(field);
            if (field.isAnnotationPresent(Sn.class))
                containSn = true;

        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlFindAll(String usualTable, Field[] fields) {
    String sql = "SELECT ";
    boolean first = true;
    for (Field field : fields) {
        if (first) {
            first = false;/*from   w ww .ja  v  a 2s  . c o m*/
        } else {
            sql += ", ";
        }
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                sql += ((DaoField) annotation).fieldName();
                break;
            }
        }
    }
    sql += " FROM " + usualTable + " ";
    return sql;
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlLoad(String usualTable, Field[] fields) {
    String sql = "SELECT ";

    boolean first = true;
    for (Field field : fields) {
        if (first) {
            first = false;/*from w  w  w .j a va2 s. c o  m*/
        } else {
            sql += ", ";
        }
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                sql += ((DaoField) annotation).fieldName();
                break;
            }
        }
    }

    sql += " FROM " + usualTable + " WHERE ";

    first = true;
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                if (((DaoField) annotation).isPrimary()) {
                    if (first) {
                        first = false;
                    } else {
                        sql += " AND ";
                    }
                    sql += ((DaoField) annotation).fieldName() + "=?";
                }
                break;
            }
        }
    }
    return sql;
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlCreate(String usualTable, Field[] fields) {
    String sql = "INSERT INTO " + usualTable + " ( ";
    String buffer = StringUtils.EMPTY;

    boolean first = true;
    for (Field field : fields) {
        if (first) {
            first = false;/*from  ww w . j a v a 2  s  .co m*/
        } else {
            sql += ", ";
            buffer += ", ";
        }
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                sql += ((DaoField) annotation).fieldName();
                buffer += "?";
                break;
            }
        }
    }
    sql += ") VALUES (";
    sql += buffer;
    sql += ")";
    return sql;
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Build the FieldInfo for a Field.//from   w  ww  . j  a v  a 2  s .  c  om
 * 
 * @param classInfo
 *            the ClassInfo to check if this field already exists
 * @param field
 *            the Field to describe
 * @return the ClassInfo containing the FieldInfo build
 */
private void buildFieldInfo(final ClassInfo classInfo, final Field field) {
    if (classInfo == null) {
        String message = "Argument classInfo must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    if (field == null) {
        String message = "Argument field must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    String fieldName = javaNaming.extractFieldNameFromField(field);
    FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
    if (fieldInfo == null) {
        fieldInfo = createFieldInfo(fieldName);
        classInfo.addFieldInfo(fieldInfo);
        fieldInfo.setParentClassInfo(classInfo);
    }
    JaxbFieldNature jaxbFieldNature = new JaxbFieldNature(fieldInfo);
    jaxbFieldNature.setField(field);
    Class<?> fieldType = field.getDeclaringClass();
    if (fieldType.isArray() || fieldType.isAssignableFrom(Collection.class)) {
        jaxbFieldNature.setMultivalued(true);
    }
    jaxbFieldNature.setGenericType(field.getGenericType());
    fieldAnnotationProcessingService.processAnnotations(jaxbFieldNature, field.getAnnotations());
}