Example usage for java.lang Class isAnnotationPresent

List of usage examples for java.lang Class isAnnotationPresent

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java

@SuppressWarnings("unchecked")
public static <T extends Link> T createLink(final PartitionFactory factory, final StorageSession session,
        final Class<T> clazz, final Node rawOrigin, final Node rawTarget, final LinkDirection direction,
        final boolean createIfDontExists) {
    final Map<String, Class<? extends Serializable>> propertyTypes = newHashMap();
    final Map<String, Serializable> propertyValues = newHashMap();
    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);

    StorageLink linkEntry = null;//from w w  w .j  ava  2  s .  c o  m
    Node origin, target;

    if (rawOrigin.compareTo(rawTarget) == 0) {
        throw new IllegalStateException();
    }

    if (LinkDirection.BIDIRECTIONAL.equals(direction) && rawOrigin.compareTo(rawTarget) < 0) {
        origin = rawTarget;
        target = rawOrigin;
    } else {
        origin = rawOrigin;
        target = rawTarget;
    }
    String linkId = null;
    if (session != null) {
        final StorageNode originAsSTNode = session.getNode(origin.getId());
        final StorageNode targetAsSTNode = session.getNode(target.getId());
        if (originAsSTNode == null && createIfDontExists) {
            throw new IllegalStateException();
        }
        if (originAsSTNode != null) {
            if (clazz.isAnnotationPresent(LinkAutoBidirectional.class)
                    && LinkDirection.UNIDIRECTIONAL.equals(direction)) {

                final StorageLink possibleLink = session.getLink(targetAsSTNode, originAsSTNode,
                        clazz.getName());
                final StorageLink anotherPossibleLink = session.getLink(originAsSTNode, targetAsSTNode,
                        clazz.getName());
                if (possibleLink != null && anotherPossibleLink != null) {
                    throw new IllegalStateException();
                }
                if (possibleLink != null && possibleLink.getPropertyValueAsString(session, LINK_DIRECTION)
                        .equals(LinkDirection.BIDIRECTIONAL.name())) {
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                } else if (anotherPossibleLink != null
                        && anotherPossibleLink.getPropertyValueAsString(session, LINK_DIRECTION)
                                .equals(LinkDirection.BIDIRECTIONAL.name())) {
                    return createLink(factory, session, clazz, rawTarget, rawOrigin,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                } else if (possibleLink != null) {
                    if (createIfDontExists) {
                        session.removeLink(possibleLink);
                    }
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);

                } else if (anotherPossibleLink != null) {
                    if (createIfDontExists) {
                        session.removeLink(anotherPossibleLink);
                    }
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                }
            }
            linkEntry = session.getLink(originAsSTNode, targetAsSTNode, clazz.getName());
            if (linkEntry == null) {
                if (createIfDontExists) {
                    linkEntry = session.addLink(originAsSTNode, targetAsSTNode, clazz.getName());
                }
                if (linkEntry != null) {
                    if (LinkDirection.BIDIRECTIONAL.equals(direction)) {
                        final InputStream objectAsStream = targetAsSTNode.getPropertyValueAsStream(session,
                                BIDIRECTIONAL_LINK_IDS);
                        List<String> linkIds;
                        if (objectAsStream != null) {
                            linkIds = SerializationUtil.deserialize(objectAsStream);
                        } else {
                            linkIds = new ArrayList<String>();
                        }
                        linkIds.add(linkEntry.getKeyAsString());
                        targetAsSTNode.setSimpleProperty(session, BIDIRECTIONAL_LINK_IDS,
                                SerializationUtil.serialize(linkIds));
                        targetAsSTNode.setSimpleProperty(session, LINK_DIRECTION,
                                LinkDirection.BIDIRECTIONAL.name());
                    }
                }
            }
        }
        linkId = StringKeysSupport.buildLinkKeyAsString(clazz.getName(), origin.getId(), target.getId());
    }

    for (final PropertyDescriptor d : descriptors) {
        if (d.getName().equals("class")) {
            continue;
        }
        propertyTypes.put(d.getName(),
                (Class<? extends Serializable>) Reflection.findClassWithoutPrimitives(d.getPropertyType()));
        final Object rawValue = linkEntry != null ? linkEntry.getPropertyValueAsString(session, d.getName())
                : null;
        final Serializable value = (Serializable) (rawValue != null
                ? Conversion.convert(rawValue, d.getPropertyType())
                : null);
        propertyValues.put(d.getName(), value);
    }
    int weigthValue;
    final Set<String> stNodeProperties = linkEntry != null ? linkEntry.getPropertyNames(session)
            : Collections.<String>emptySet();
    if (stNodeProperties.contains(WEIGTH_VALUE)) {
        weigthValue = Conversion.convert(linkEntry.getPropertyValueAsString(session, WEIGTH_VALUE),
                Integer.class);
    } else {
        weigthValue = findInitialWeight(clazz);
    }
    final LinkImpl internalLink = new LinkImpl(linkId, clazz.getName(), clazz, propertyTypes, propertyValues,
            findInitialWeight(clazz), weigthValue, origin, target, direction);
    if (linkEntry != null) {
        internalLink.setCached(linkEntry);
        internalLink.linkDirection = direction;
    }
    final Enhancer e = new Enhancer();
    e.setSuperclass(clazz);
    e.setInterfaces(new Class<?>[] { PropertyContainerMetadata.class });
    e.setCallback(new PropertyContainerInterceptor(internalLink));
    return (T) e.create(new Class[0], new Object[0]);
}

From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java

@Override
public <O> int executeUpdate(O sample) {
    final Class<?> resultType = sample.getClass();
    if (!resultType.isAnnotationPresent(Partial.class)) {
        throw new PartialEntityDefinitionError("Expected to find @Partial on " + resultType.getCanonicalName());
    }//from   w  ww . j  ava 2  s  .co  m
    final Partial annotation = resultType.getAnnotation(Partial.class);
    final Statement statement = getStatement(annotation.targetEntity(), annotation.query(), null,
            StatementType.INSERT, StatementType.DELETE, StatementType.UPDATE);
    final PreparedStatement preparedStatement = openStatement(
            statement.prepare(openConnection(), mapCreator, sample));
    try {
        final int affectedRows = preparedStatement.executeUpdate();
        cleanUpStatement(preparedStatement);
        return affectedRows;
    } catch (SQLException e) {
        throw new UnsuccessfulOperationError("Failed to execute update", e);
    }
}

From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java

@Override
public <O> List<O> executeQuery(Class<O> resultType, Map<String, Object> values) {
    if (!resultType.isAnnotationPresent(Partial.class)) {
        throw new PartialEntityDefinitionError("Expected to find @Partial on " + resultType.getCanonicalName());
    }/*from   w w w  .j  a  v a  2 s . co m*/
    final Partial annotation = resultType.getAnnotation(Partial.class);
    final List<Map<String, Object>> maps = executeUntypedQuery(annotation.targetEntity(), annotation.query(),
            values);
    final ArrayList<O> result = new ArrayList<O>();
    for (Map<String, Object> map : maps) {
        final O partialEntity;
        try {
            partialEntity = beanInitializer.initialize(resultType, new Class[0]);
        } catch (BeanInstantiationException e) {
            throw new EntityInitializationError(resultType, e);
        }
        result.add(entityCreator.fromMap(partialEntity, getPartialEntityMetadata(resultType), map));
    }
    return result;
}

From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java

/**
 * @param className/*from w  ww  .  j a va 2s . co  m*/
 * @param tableList
 */
@SuppressWarnings("unchecked")
protected void processCascadeAddCascade(final String className, final List<Table> tableList) {
    //System.out.println(className);
    try {
        Class<?> classObj = Class.forName(packageName + "." + className);

        Table table = null;
        String tableName = null;

        if (classObj.isAnnotationPresent(javax.persistence.Table.class)) {
            Vector<TableIndex> indexes = new Vector<TableIndex>();

            javax.persistence.Table tableAnno = (javax.persistence.Table) classObj
                    .getAnnotation(javax.persistence.Table.class);
            tableName = tableAnno.name();

            org.hibernate.annotations.Table hiberTableAnno = (org.hibernate.annotations.Table) classObj
                    .getAnnotation(org.hibernate.annotations.Table.class);
            if (hiberTableAnno != null) {
                for (Index index : hiberTableAnno.indexes()) {
                    indexes.add(new TableIndex(index.name(), index.columnNames()));
                }
            }

            table = createTable(packageName + "." + className, tableName);
            table.setIndexes(indexes);
            tableList.add(table);
        }

        if (table != null) {

            for (Method method : classObj.getMethods()) {
                String methodName = method.getName();
                if (!methodName.startsWith("get")
                        || method.isAnnotationPresent(javax.persistence.Transient.class)) {
                    continue;
                }

                //String thisSideName = getFieldNameFromMethod(method);

                if (method.isAnnotationPresent(javax.persistence.ManyToOne.class)) {
                    if (!method.isAnnotationPresent(org.hibernate.annotations.Cascade.class)) {
                        System.out.println("Missing Cascade[" + method.getName() + "]");
                        missing++;
                        //addCascadeRule(classObj, method, "    @org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.LOCK })");
                    }

                } else if (method.isAnnotationPresent(javax.persistence.ManyToMany.class)) {
                    if (!method.isAnnotationPresent(org.hibernate.annotations.Cascade.class)) {
                        System.out.println("Missing Cascade[" + method.getName() + "]");
                        missing++;
                        //addCascadeRule(classObj, method, "    @org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.LOCK })");
                    }

                } else if (method.isAnnotationPresent(javax.persistence.OneToMany.class)) {
                    if (!method.isAnnotationPresent(org.hibernate.annotations.Cascade.class)) {
                        System.out.println("Missing Cascade[" + method.getName() + "]");
                        missing++;
                        addCascadeRule(classObj, method,
                                "    @org.hibernate.annotations.Cascade( { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })");

                    }

                } else if (method.isAnnotationPresent(javax.persistence.OneToOne.class)) {
                    if (!method.isAnnotationPresent(org.hibernate.annotations.Cascade.class)) {
                        //System.out.println("Missing Cascade["+method.getName()+"]");
                        missing++;
                    }

                }
            }

            // This updates each field as to whether it is an index
            table.updateIndexFields();
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DatamodelGenerator.class, ex);
        ex.printStackTrace();
    }
}

From source file:adalid.core.AbstractPersistentEntity.java

private void annotateDiscriminatorValue(Class<?> type) {
    /*/*from w w w. j ava 2  s.co m*/
     * DiscriminatorValue annotation cannot be "inherited"
     */
    _annotatedWithDiscriminatorValue = type.isAnnotationPresent(DiscriminatorValue.class);
    if (_annotatedWithDiscriminatorValue) {
        DiscriminatorValue annotation = type.getAnnotation(DiscriminatorValue.class);
        _discriminatorValue = StringUtils.trimToNull(annotation.value());
    }
}

From source file:adalid.core.AbstractPersistentEntity.java

private void annotateInheritanceMapping(Class<?> type) {
    /*//from  w  ww .j  av a 2  s  . co m
     * InheritanceMapping annotation cannot be "inherited"
     */
    _annotatedWithInheritanceMapping = type.isAnnotationPresent(InheritanceMapping.class);
    if (_annotatedWithInheritanceMapping) {
        InheritanceMapping annotation = type.getAnnotation(InheritanceMapping.class);
        _inheritanceMappingStrategy = annotation.strategy();
        //          _discriminatorFieldName = annotation.discriminator();
        //          if (StringUtils.isBlank(_discriminatorFieldName)) {
        //              _discriminatorFieldName = null;
        //              _discriminatorField = null;
        //          } else {
        //              _discriminatorField = getDiscriminatorField(_discriminatorFieldName, type);
        //          }
    }
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

@Override
public <E> TableMetadata<E> resolve(final Class<E> entityType) {
    log.info("Resolving metadata for " + entityType.getCanonicalName());
    final String tableName;
    final String schema;
    final Set<Set<String>> uniqueColumns = new HashSet<Set<String>>();
    final Set<String> keyColumns = new HashSet<String>();
    final Set<String> foreignKeys = new HashSet<String>();
    final HashSet<RelationMetadata<E, ?>> foreignReferences = new HashSet<RelationMetadata<E, ?>>();
    if (entityType.isAnnotationPresent(Table.class)) {
        final Table table = entityType.getAnnotation(Table.class);
        tableName = table.name().isEmpty() ? entityType.getSimpleName() : table.name();
        schema = table.schema();/* ww w.  j a  v  a 2s .  co m*/
        for (UniqueConstraint constraint : table.uniqueConstraints()) {
            final HashSet<String> columns = new HashSet<String>();
            uniqueColumns.add(columns);
            Collections.addAll(columns, constraint.columnNames());
        }
    } else {
        tableName = entityType.getSimpleName();
        schema = NO_SCHEMA;
    }
    final Set<StoredProcedureMetadata> storedProcedures = new HashSet<StoredProcedureMetadata>();
    if (entityType.isAnnotationPresent(StoredProcedure.class)) {
        storedProcedures.add(getStoredProcedureMetadata(entityType.getAnnotation(StoredProcedure.class)));
    } else if (entityType.isAnnotationPresent(StoredProcedures.class)) {
        final StoredProcedure[] procedures = entityType.getAnnotation(StoredProcedures.class).value();
        for (StoredProcedure procedure : procedures) {
            storedProcedures.add(getStoredProcedureMetadata(procedure));
        }
    }
    //noinspection unchecked
    if (!withMethods(entityType).keep(new GetterMethodFilter())
            .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new AnnotatedElementFilter(Transient.class)).isEmpty()) {
        throw new TransientColumnFoundError(entityType);
    }
    final Collection<SequenceMetadata> sequences = new HashSet<SequenceMetadata>();
    final HashSet<ConstraintMetadata> constraints = new HashSet<ConstraintMetadata>();
    final AtomicReference<ColumnMetadata> versionColumn = new AtomicReference<ColumnMetadata>();
    //noinspection unchecked
    final List<Method> getters = withMethods(entityType).keep(new GetterMethodFilter()).list();
    final List<Method> filteredGetters = new ArrayList<Method>();
    for (Method getter : getters) {
        final PropertyAccessorFilter filter = new PropertyAccessorFilter(
                ReflectionUtils.getPropertyName(getter.getName()));
        final Method method = with(filteredGetters).find(filter);
        if (method == null) {
            filteredGetters.add(getter);
        } else if (method.getDeclaringClass().equals(getter.getDeclaringClass())) {
            filteredGetters.remove(method);
            filteredGetters.add(pickGetter(method, getter));
        }
    }
    getters.clear();
    getters.addAll(filteredGetters);
    //noinspection unchecked
    final Collection<ColumnMetadata> tableColumns = with(getters)
            .drop(new AnnotatedElementFilter(Transient.class)).drop(new AnnotatedElementFilter(OneToMany.class))
            .drop(new AnnotatedElementFilter(ManyToMany.class)).drop(new Filter<Method>() {
                @Override
                public boolean accepts(Method item) {
                    return item.isAnnotationPresent(OneToOne.class)
                            && !item.isAnnotationPresent(JoinColumn.class);
                }
            }).drop(new PropertyAccessorFilter(CLASS_PROPERTY))
            .transform(new Transformer<Method, ColumnMetadata>() {
                @Override
                public ColumnMetadata map(Method method) {
                    final JoinColumn joinColumn = method.getAnnotation(JoinColumn.class);
                    Column column = method.getAnnotation(Column.class);
                    if (column == null && joinColumn == null) {
                        //let's assume it is a column anyway
                        column = new DefaultColumn();
                    }
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    if (column != null && joinColumn != null) {
                        throw new ColumnDefinitionError(
                                "Property " + propertyName + " is defined as both a column and a join column");
                    }
                    final Class<?> propertyType = method.getReturnType();
                    String name = column != null ? column.name() : joinColumn.name();
                    if (name.isEmpty()) {
                        name = propertyName;
                    }
                    final boolean nullable = column != null ? column.nullable() : joinColumn.nullable();
                    final int length = column != null ? column.length() : 0;
                    final int precision = column != null ? column.precision() : 0;
                    final int scale = column != null ? column.scale() : 0;
                    final ValueGenerationType generationType = determineValueGenerationType(method);
                    final String valueGenerator = determineValueGenerator(method);
                    final ColumnMetadata foreignColumn = joinColumn == null ? null
                            : determineForeignReference(method);
                    final int type = getColumnType(method, foreignColumn);
                    final Class<?> declaringClass = ReflectionUtils.getDeclaringClass(method);
                    if (method.isAnnotationPresent(BasicCollection.class)
                            && !(Collection.class.isAssignableFrom(method.getReturnType()))) {
                        throw new ColumnDefinitionError(
                                "Collection column must return a collection value: " + tableName + "." + name);
                    }
                    final ResolvedColumnMetadata columnMetadata = new ResolvedColumnMetadata(
                            new UnresolvedTableMetadata<E>(entityType), declaringClass, name, type,
                            propertyName, propertyType, nullable, length, precision, scale, generationType,
                            valueGenerator, foreignColumn, method.isAnnotationPresent(BasicCollection.class),
                            isComplex(method, foreignColumn));
                    if (foreignColumn != null) {
                        foreignKeys.add(name);
                    }
                    if (method.isAnnotationPresent(Id.class)) {
                        keyColumns.add(name);
                    }
                    if (method.isAnnotationPresent(SequenceGenerator.class)) {
                        final SequenceGenerator annotation = method.getAnnotation(SequenceGenerator.class);
                        sequences.add(new ImmutableSequenceMetadata(annotation.name(),
                                annotation.initialValue(), annotation.allocationSize()));
                    }
                    if (joinColumn != null) {
                        final RelationType relationType = getRelationType(method);
                        final CascadeMetadata cascadeMetadata = getCascadeMetadata(method);
                        final boolean isLazy = determineLaziness(method);
                        final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                                declaringClass, columnMetadata.getPropertyName(), true, null, null, null,
                                relationType, cascadeMetadata, isLazy, null);
                        reference.setForeignColumn(foreignColumn);
                        foreignReferences.add(reference);
                    }
                    if (method.isAnnotationPresent(Version.class)) {
                        if (versionColumn.get() != null) {
                            throw new MultipleVersionColumnsError(entityType);
                        }
                        if (column != null) {
                            if (columnMetadata.isNullable()) {
                                throw new VersionColumnDefinitionError("Version column cannot be nullable: "
                                        + entityType.getCanonicalName() + "." + columnMetadata.getName());
                            }
                            versionColumn.set(columnMetadata);
                        } else {
                            throw new VersionColumnDefinitionError(
                                    "Only local columns can be used for optimistic locking");
                        }
                    }
                    return columnMetadata;
                }
            }).list();
    //handling one-to-many relations
    //noinspection unchecked
    withMethods(entityType).keep(new GetterMethodFilter())
            .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new AnnotatedElementFilter(OneToMany.class)).each(new Processor<Method>() {
                @Override
                public void process(Method method) {
                    if (!Collection.class.isAssignableFrom(method.getReturnType())) {
                        throw new RelationDefinitionError(
                                "One to many relations must be collections. Error in " + method);
                    }
                    final OneToMany annotation = method.getAnnotation(OneToMany.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? ((Class) ((ParameterizedType) method.getGenericReturnType())
                                    .getActualTypeArguments()[0])
                            : annotation.targetEntity();
                    String foreignColumnName = annotation.mappedBy();
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    if (foreignColumnName.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> list = withMethods(foreignEntity)
                                .keep(new AnnotatedElementFilter(JoinColumn.class))
                                .keep(new AnnotatedElementFilter(ManyToOne.class))
                                .keep(new MethodReturnTypeFilter(entityType)).list();
                        if (list.isEmpty()) {
                            throw new RelationDefinitionError(
                                    "No ManyToOne relations for " + entityType.getCanonicalName()
                                            + " were found on " + foreignEntity.getCanonicalName());
                        }
                        if (list.size() > 1) {
                            throw new RelationDefinitionError("Ambiguous one to many relationship on "
                                    + entityType.getCanonicalName() + "." + propertyName);
                        }
                        final Method foreignMethod = list.get(0);
                        final Column column = foreignMethod.getAnnotation(Column.class);
                        final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class);
                        foreignColumnName = column == null ? joinColumn.name() : column.name();
                        if (foreignColumnName.isEmpty()) {
                            foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName());
                        }
                    }
                    final List<OrderMetadata> ordering = getOrdering(foreignEntity,
                            method.getAnnotation(OrderBy.class));
                    //noinspection unchecked
                    final UnresolvedColumnMetadata foreignColumn = new UnresolvedColumnMetadata(
                            foreignColumnName,
                            new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity));
                    final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null,
                            getRelationType(method), getCascadeMetadata(method), determineLaziness(method),
                            ordering);
                    reference.setForeignColumn(foreignColumn);
                    foreignReferences.add(reference);
                }
            });
    //Handling one-to-one relations where the entity is not the owner of the relationship
    //noinspection unchecked
    withMethods(entityType).keep(new GetterMethodFilter()).keep(new AnnotatedElementFilter(OneToOne.class))
            .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)).each(new Processor<Method>() {
                @Override
                public void process(Method method) {
                    final OneToOne annotation = method.getAnnotation(OneToOne.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? method.getReturnType()
                            : annotation.targetEntity();
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null,
                            getRelationType(method), getCascadeMetadata(method), determineLaziness(method),
                            null);
                    String foreignColumnName = annotation.mappedBy();
                    if (foreignColumnName.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter())
                                .keep(new MethodReturnTypeFilter(entityType))
                                .keep(new AnnotatedElementFilter(OneToOne.class))
                                .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)).list();
                        if (methods.isEmpty()) {
                            throw new EntityDefinitionError(
                                    "No OneToOne relations were found on " + foreignEntity.getCanonicalName()
                                            + " for " + entityType.getCanonicalName());
                        }
                        if (methods.size() > 1) {
                            throw new EntityDefinitionError("Ambiguous OneToOne relation on "
                                    + entityType.getCanonicalName() + "." + propertyName);
                        }
                        final Method foreignMethod = methods.get(0);
                        final Column column = foreignMethod.getAnnotation(Column.class);
                        final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class);
                        foreignColumnName = column == null ? joinColumn.name() : column.name();
                        if (foreignColumnName.isEmpty()) {
                            foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName());
                        }
                    }
                    //noinspection unchecked
                    reference.setForeignColumn(new UnresolvedColumnMetadata(foreignColumnName,
                            new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)));
                    foreignReferences.add(reference);
                }
            });
    final HashSet<NamedQueryMetadata> namedQueries = new HashSet<NamedQueryMetadata>();
    if (entityType.isAnnotationPresent(SequenceGenerator.class)) {
        final SequenceGenerator annotation = entityType.getAnnotation(SequenceGenerator.class);
        sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(),
                annotation.allocationSize()));
    }
    //finding orderings
    //noinspection unchecked
    final List<OrderMetadata> ordering = withMethods(entityType).keep(new AnnotatedElementFilter(Column.class))
            .keep(new AnnotatedElementFilter(Order.class)).sort(new Comparator<Method>() {
                @Override
                public int compare(Method firstMethod, Method secondMethod) {
                    final Order first = firstMethod.getAnnotation(Order.class);
                    final Order second = secondMethod.getAnnotation(Order.class);
                    return ((Integer) first.priority()).compareTo(second.priority());
                }
            }).transform(new Transformer<Method, OrderMetadata>() {
                @Override
                public OrderMetadata map(Method input) {
                    final Column column = input.getAnnotation(Column.class);
                    String columnName = column.name().isEmpty()
                            ? ReflectionUtils.getPropertyName(input.getName())
                            : column.name();
                    ColumnMetadata columnMetadata = with(tableColumns).find(new ColumnNameFilter(columnName));
                    if (columnMetadata == null) {
                        columnMetadata = with(tableColumns).find(new ColumnPropertyFilter(columnName));
                    }
                    if (columnMetadata == null) {
                        throw new NoSuchColumnError(entityType, columnName);
                    }
                    return new ImmutableOrderMetadata(columnMetadata, input.getAnnotation(Order.class).value());
                }
            }).list();
    final ResolvedTableMetadata<E> tableMetadata = new ResolvedTableMetadata<E>(entityType, schema, tableName,
            constraints, tableColumns, namedQueries, sequences, storedProcedures, foreignReferences,
            versionColumn.get(), ordering);
    if (!keyColumns.isEmpty()) {
        constraints.add(new PrimaryKeyConstraintMetadata(tableMetadata,
                with(keyColumns).transform(new Transformer<String, ColumnMetadata>() {
                    @Override
                    public ColumnMetadata map(String columnName) {
                        return getColumnMetadata(columnName, tableColumns, entityType);
                    }
                }).list()));
    }
    if (entityType.isAnnotationPresent(NamedNativeQueries.class)) {
        final NamedNativeQuery[] queries = entityType.getAnnotation(NamedNativeQueries.class).value();
        for (NamedNativeQuery query : queries) {
            namedQueries.add(new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata,
                    QueryType.NATIVE));
        }
    } else if (entityType.isAnnotationPresent(NamedNativeQuery.class)) {
        final NamedNativeQuery query = entityType.getAnnotation(NamedNativeQuery.class);
        namedQueries.add(
                new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE));
    }
    constraints
            .addAll(with(uniqueColumns).sort().transform(new Transformer<Set<String>, Set<ColumnMetadata>>() {
                @Override
                public Set<ColumnMetadata> map(Set<String> columns) {
                    return with(columns).transform(new Transformer<String, ColumnMetadata>() {
                        @Override
                        public ColumnMetadata map(String columnName) {
                            return getColumnMetadata(columnName, tableColumns, entityType);
                        }
                    }).set();
                }
            }).transform(new Transformer<Set<ColumnMetadata>, UniqueConstraintMetadata>() {
                @Override
                public UniqueConstraintMetadata map(Set<ColumnMetadata> columns) {
                    return new UniqueConstraintMetadata(tableMetadata, columns);
                }
            }).list());
    constraints.addAll(with(foreignKeys).sort().transform(new Transformer<String, ColumnMetadata>() {
        @Override
        public ColumnMetadata map(String columnName) {
            return getColumnMetadata(columnName, tableColumns, entityType);
        }
    }).transform(new Transformer<ColumnMetadata, ForeignKeyConstraintMetadata>() {
        @Override
        public ForeignKeyConstraintMetadata map(ColumnMetadata columnMetadata) {
            return new ForeignKeyConstraintMetadata(tableMetadata, columnMetadata);
        }
    }).list());
    //going after many-to-many relations
    //noinspection unchecked
    withMethods(entityType).drop(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new GetterMethodFilter()).forThose(new Filter<Method>() {
                @Override
                public boolean accepts(Method item) {
                    return item.isAnnotationPresent(ManyToMany.class);
                }
            }, new Processor<Method>() {
                @Override
                public void process(Method method) {
                    final ManyToMany annotation = method.getAnnotation(ManyToMany.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? ((Class) ((ParameterizedType) method.getGenericReturnType())
                                    .getActualTypeArguments()[0])
                            : annotation.targetEntity();
                    String foreignProperty = annotation.mappedBy();
                    if (foreignProperty.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter())
                                .keep(new AnnotatedElementFilter(ManyToMany.class)).list();
                        if (methods.isEmpty()) {
                            throw new EntityDefinitionError(
                                    "Failed to locate corresponding many-to-many relation on "
                                            + foreignEntity.getCanonicalName());
                        }
                        if (methods.size() == 1) {
                            throw new EntityDefinitionError("Ambiguous many-to-many relationship defined");
                        }
                        foreignProperty = ReflectionUtils.getPropertyName(methods.get(0).getName());
                    }
                    final List<OrderMetadata> ordering = getOrdering(foreignEntity,
                            method.getAnnotation(OrderBy.class));
                    //noinspection unchecked
                    foreignReferences.add(new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method),
                            ReflectionUtils.getPropertyName(method.getName()), false, tableMetadata, null,
                            new UnresolvedColumnMetadata(foreignProperty,
                                    new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)),
                            RelationType.MANY_TO_MANY, getCascadeMetadata(method), determineLaziness(method),
                            ordering));
                }
            });
    return tableMetadata;
}

From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java

private void bindObjectMapping(InternalObjectMapping objectMapping, String actualAccessor, String name,
        String annotationAccessor, Class<?> searchableClass) {
    if (!StringUtils.hasLength(annotationAccessor)) {
        objectMapping.setAccessor(actualAccessor);
    } else {// w w w  .  j  a v a2  s. com
        objectMapping.setAccessor(annotationAccessor);
    }
    objectMapping.setName(name);
    objectMapping.setPropertyName(name);
    // set the defined in alias for multiple ref aliases
    // note, with annotation, we might not have @Searchable defined on
    // the class, so we are using the FQN class name instead
    if (searchableClass.isAnnotationPresent(Searchable.class)) {
        Searchable searchable = searchableClass.getAnnotation(Searchable.class);
        objectMapping.setDefinedInAlias(getAliasFromSearchableClass(searchableClass, searchable));
    } else {
        objectMapping.setDefinedInAlias(ClassUtils.getShortName(searchableClass));
    }
}

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Inspects the entity resource and returns meta data about any addresssed/binary properties
 * @param api Api/*from  www  .j  ava2 s . c om*/
 * @param entityPath String
 */
public static void inspectAddressedProperties(Api api, Class<?> resource, final String entityPath,
        List<ResourceMetadata> metainfo) {
    final Map<String, List<ResourceOperation>> operationGroupedByProperty = new HashMap<String, List<ResourceOperation>>();

    MetaHelperAddressable helperForAddressProps = new MetaHelperAddressable(resource, entityPath,
            operationGroupedByProperty);

    findOperation(BinaryResourceAction.Read.class, HttpMethod.GET, helperForAddressProps);
    findOperation(BinaryResourceAction.Delete.class, HttpMethod.DELETE, helperForAddressProps);
    findOperation(BinaryResourceAction.Update.class, HttpMethod.PUT, helperForAddressProps);

    findOperation(BinaryResourceAction.ReadWithResponse.class, HttpMethod.GET, helperForAddressProps);
    findOperation(BinaryResourceAction.DeleteWithResponse.class, HttpMethod.DELETE, helperForAddressProps);
    findOperation(BinaryResourceAction.UpdateWithResponse.class, HttpMethod.PUT, helperForAddressProps);

    findOperation(RelationshipResourceBinaryAction.Read.class, HttpMethod.GET, helperForAddressProps);
    findOperation(RelationshipResourceBinaryAction.Delete.class, HttpMethod.DELETE, helperForAddressProps);
    findOperation(RelationshipResourceBinaryAction.Update.class, HttpMethod.PUT, helperForAddressProps);

    findOperation(RelationshipResourceBinaryAction.ReadWithResponse.class, HttpMethod.GET,
            helperForAddressProps);
    findOperation(RelationshipResourceBinaryAction.DeleteWithResponse.class, HttpMethod.DELETE,
            helperForAddressProps);
    findOperation(RelationshipResourceBinaryAction.UpdateWithResponse.class, HttpMethod.PUT,
            helperForAddressProps);

    boolean noAuth = resource.isAnnotationPresent(WebApiNoAuth.class);
    if (noAuth) {
        throw new IllegalArgumentException(
                "@WebApiNoAuth should not be on all (address properties) - only on individual methods: "
                        + entityPath);
    }

    Set<Class<? extends ResourceAction>> apiNoAuth = helperForAddressProps.apiNoAuth;

    if (resource.isAnnotationPresent(WebApiDeleted.class)) {
        metainfo.add(new ResourceMetadata(ResourceDictionary.propertyResourceKey(entityPath, "FIX_ME"),
                RESOURCE_TYPE.PROPERTY, null, inspectApi(resource), ALL_PROPERTY_RESOURCE_INTERFACES, apiNoAuth,
                null));
    } else {
        for (Entry<String, List<ResourceOperation>> groupedOps : operationGroupedByProperty.entrySet()) {
            metainfo.add(new ResourceMetadata(groupedOps.getKey(), RESOURCE_TYPE.PROPERTY,
                    groupedOps.getValue(), api, null, apiNoAuth, null));
        }
    }

}

From source file:org.apache.nifi.controller.StandardProcessorNode.java

public StandardProcessorNode(final Processor processor, final String uuid,
        final ValidationContextFactory validationContextFactory, final ProcessScheduler scheduler,
        final ControllerServiceProvider controllerServiceProvider, final String componentType,
        final String componentCanonicalClass, final NiFiProperties nifiProperties,
        final VariableRegistry variableRegistry, final ComponentLog logger) {

    super(processor, uuid, validationContextFactory, controllerServiceProvider, componentType,
            componentCanonicalClass, variableRegistry, logger);
    this.processor = processor;
    identifier = new AtomicReference<>(uuid);
    destinations = new HashMap<>();
    connections = new HashMap<>();
    incomingConnectionsRef = new AtomicReference<>(new ArrayList<>());
    lossTolerant = new AtomicBoolean(false);
    final Set<Relationship> emptySetOfRelationships = new HashSet<>();
    undefinedRelationshipsToTerminate = new AtomicReference<>(emptySetOfRelationships);
    comments = new AtomicReference<>("");
    schedulingPeriod = new AtomicReference<>("0 sec");
    schedulingNanos = new AtomicLong(MINIMUM_SCHEDULING_NANOS);
    yieldPeriod = new AtomicReference<>(DEFAULT_YIELD_PERIOD);
    yieldExpiration = new AtomicLong(0L);
    concurrentTaskCount = new AtomicInteger(1);
    position = new AtomicReference<>(new Position(0D, 0D));
    style = new AtomicReference<>(Collections.unmodifiableMap(new HashMap<String, String>()));
    this.processGroup = new AtomicReference<>();
    processScheduler = scheduler;//from ww  w . j  a va  2 s  .c o m
    penalizationPeriod = new AtomicReference<>(DEFAULT_PENALIZATION_PERIOD);
    this.nifiProperties = nifiProperties;

    final Class<?> procClass = processor.getClass();
    triggerWhenEmpty = procClass.isAnnotationPresent(TriggerWhenEmpty.class);
    sideEffectFree = procClass.isAnnotationPresent(SideEffectFree.class);
    batchSupported = procClass.isAnnotationPresent(SupportsBatching.class);
    triggeredSerially = procClass.isAnnotationPresent(TriggerSerially.class);
    triggerWhenAnyDestinationAvailable = procClass
            .isAnnotationPresent(TriggerWhenAnyDestinationAvailable.class);
    eventDrivenSupported = procClass.isAnnotationPresent(EventDriven.class) && !triggeredSerially
            && !triggerWhenEmpty;

    final boolean inputRequirementPresent = procClass.isAnnotationPresent(InputRequirement.class);
    if (inputRequirementPresent) {
        inputRequirement = procClass.getAnnotation(InputRequirement.class).value();
    } else {
        inputRequirement = Requirement.INPUT_ALLOWED;
    }

    schedulingStrategy = SchedulingStrategy.TIMER_DRIVEN;
    executionNode = ExecutionNode.ALL;
    try {
        if (procClass.isAnnotationPresent(DefaultSchedule.class)) {
            DefaultSchedule dsc = procClass.getAnnotation(DefaultSchedule.class);
            try {
                this.setSchedulingStrategy(dsc.strategy());
            } catch (Throwable ex) {
                LOG.error(String.format(
                        "Error while setting scheduling strategy from DefaultSchedule annotation: %s",
                        ex.getMessage()), ex);
            }
            try {
                this.setScheduldingPeriod(dsc.period());
            } catch (Throwable ex) {
                this.setSchedulingStrategy(SchedulingStrategy.TIMER_DRIVEN);
                LOG.error(String.format(
                        "Error while setting scheduling period from DefaultSchedule annotation: %s",
                        ex.getMessage()), ex);
            }
            if (!triggeredSerially) {
                try {
                    setMaxConcurrentTasks(dsc.concurrentTasks());
                } catch (Throwable ex) {
                    LOG.error(String.format(
                            "Error while setting max concurrent tasks from DefaultSchedule annotation: %s",
                            ex.getMessage()), ex);
                }
            }
        }
    } catch (Throwable ex) {
        LOG.error(String.format("Error while setting default schedule from DefaultSchedule annotation: %s",
                ex.getMessage()), ex);
    }
}