Example usage for java.lang.reflect Method isAnnotationPresent

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.lhings.java.LhingsDevice.java

/**
 * This method detects the actions, events and status components of the
 * device using reflection, builds the descriptor of the device and stores
 * it in the field jsonDescriptor.//  w w  w .j  a v  a2 s .c o  m
 *
 * @throws InitializationException
 */
private void autoconfigure() throws InitializationException {
    Class<?> deviceClass = this.getClass();
    Map<String, Object> deviceDescriptor = new HashMap<String, Object>();
    // List<com.lhings.java.model.Action> actionList = new
    // ArrayList<com.lhings.java.model.Action>();
    List<com.lhings.java.model.Event> eventList = new ArrayList<com.lhings.java.model.Event>();
    // inspect class to identify descriptor fields and status components
    deviceDescriptor.put("actionList", actionDefinitions.values());
    deviceDescriptor.put("stateVariableList", statusDefinitions.values());
    deviceDescriptor.put("eventList", eventList);

    DeviceInfo info = deviceClass.getAnnotation(DeviceInfo.class);
    if (info != null) {
        deviceDescriptor.put("modelName", info.modelName());
        deviceDescriptor.put("manufacturer", info.manufacturer());
        deviceDescriptor.put("deviceType", info.deviceType());
        deviceDescriptor.put("serialNumber", info.serialNumber());
    } else {
        deviceDescriptor.put("modelName", "");
        deviceDescriptor.put("manufacturer", "");
        deviceDescriptor.put("deviceType", DEFAULT_DEVICE_TYPE);
        deviceDescriptor.put("serialNumber", "");
    }

    Field[] fields = deviceClass.getDeclaredFields();

    for (Field field : fields) {
        // discover status components and add them to descriptor
        if (field.isAnnotationPresent(StatusComponent.class)) {
            StatusComponent statusComp = field.getAnnotation(StatusComponent.class);
            String statusComponentName = statusComp.name();
            String statusComponentType;
            try {
                statusComponentType = tellLhingsType(field.getType().getName());
            } catch (InitializationException ex) {
                // rethrow with appropriate message
                throw new InitializationException("Initialization failed for device with uuid " + uuid
                        + ". Type " + field.getType().getName() + " is not allowed for field " + field.getName()
                        + ". Methods annotated with @StatusComponent can only have parameters of the following types: int, float, double, boolean, String and java.util.Date.");
            }

            // if no name was provided for field, it defaults to the
            // name used to declare it in source code
            boolean validStatusComponentName = statusComponentName.matches("^[a-zA-Z0-9_]*$");
            if (!validStatusComponentName) {
                log.warn("\"" + statusComponentName
                        + "\" is not a valid name for a status component. Only alphanumeric and underscore characters are allowed. Taking field name \""
                        + field.getName() + "\" as status component name.");
            }
            if (statusComponentName.isEmpty() || !validStatusComponentName) {
                statusComponentName = field.getName();
            }
            statusDefinitions.put(statusComponentName,
                    new com.lhings.java.model.StatusComponent(statusComponentName, statusComponentType));
            statusFields.put(statusComponentName, field);
        }

        // discover events and add them to descriptor
        if (field.isAnnotationPresent(Event.class)) {
            Event event = field.getAnnotation(Event.class);
            String eventName = event.name();
            boolean validEventComponentName = eventName.matches("^[a-zA-Z0-9_]*$");
            if (!validEventComponentName) {
                log.warn("\"" + eventName
                        + "\" is not a valid name for an event. Only alphanumeric and underscore characters are allowed. Taking field name \""
                        + field.getName() + "\" as event name.");
            }
            if (eventName.isEmpty() || !validEventComponentName) // default event name is the name of the field
            {
                eventName = field.getName();
            }

            com.lhings.java.model.Event eventToAdd = new com.lhings.java.model.Event(eventName);

            String[] componentNames = event.component_names();
            String[] componentTypes = event.component_types();
            if (componentNames.length != componentTypes.length) {
                log.warn("Payload component list for event \"" + eventName
                        + "\" is not valid: wrong number of component types provided.");
            } else {
                for (int j = 0; j < componentNames.length; j++) {
                    eventToAdd.getComponents().add(new Argument(componentNames[j], componentTypes[j]));
                }
            }

            eventList.add(eventToAdd);
            eventDefinitions.add(eventName);
        }

    }
    // inspect class methods to identify possible actions
    Method[] methods = deviceClass.getMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(Action.class)) {
            com.lhings.java.model.Action modelAction = autoconfigureAction(method);
            String actionName = method.getAnnotation(Action.class).name();
            boolean validNameProvided = actionName.matches("^[a-zA-Z0-9_]*$");
            if (!validNameProvided) {
                log.warn("\"" + actionName
                        + "\" is not a valid name for an action. Only alphanumeric and underscore characters are allowed. Taking method name \""
                        + method.getName() + "\" as action name.");
            }
            if (actionName.isEmpty() || !validNameProvided) {
                actionName = method.getName();
            }

            actionDefinitions.put(actionName, modelAction);
        }
    }

    jsonDescriptor = new JSONObject(deviceDescriptor).toString();
}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

private String getDeleteCommand(String tableName, String schema, HashMap<Method, String> fieldMapping,
        HashMap<Integer, Method> indexMapping) {
    String command = "delete from " + ((schema == null) ? "" : (schema + ".")) + tableName;
    String fields = "";
    int paramIndex = 1;
    String pkField = null;/*from w  w w  . ja  v a  2s. c o m*/

    Method pkFieldMethod = null;
    for (Method dbFieldMethod : fieldMapping.keySet()) {
        if (dbFieldMethod.isAnnotationPresent(Id.class)) {
            pkFieldMethod = dbFieldMethod;
            pkField = (String) fieldMapping.get(pkFieldMethod);
        }
    }
    indexMapping.put(paramIndex, pkFieldMethod);
    command += " where " + pkField + " = ?";
    return command;
}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

private String getUpdateCommand(String tableName, String schema, HashMap<Method, String> fieldMapping,
        HashMap<Integer, Method> indexMapping) {
    String command = "update " + ((schema == null) ? "" : (schema + ".")) + tableName + " set ";
    String fields = "";
    int paramIndex = 1;
    String pkField = null;/*from ww w . j  a v  a2 s . c o  m*/

    Method pkFieldMethod = null;
    for (Method dbFieldMethod : fieldMapping.keySet()) {
        if (dbFieldMethod.isAnnotationPresent(Id.class)) {
            pkFieldMethod = dbFieldMethod;
            pkField = (String) fieldMapping.get(pkFieldMethod);
        } else {
            String field = (String) fieldMapping.get(dbFieldMethod);
            fields += field + "=?,";
            indexMapping.put(paramIndex, dbFieldMethod);
            paramIndex++;
        }
    }
    indexMapping.put(paramIndex, pkFieldMethod);
    fields = fields.substring(0, fields.length() - 1);
    command += fields + " where " + pkField + " = ?";
    return command;
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private void invokePostConstruct(Object object) throws InvocationTargetException, IllegalAccessException {
    Class<?> clazz = object.getClass();
    List<Method> postConstructMethods = new ArrayList<Method>();
    while (clazz != null) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                addMethodIfNotOverriden(postConstructMethods, method);
            }/*from  ww  w. j a va2s. co m*/
        }
        clazz = clazz.getSuperclass();
    }
    Collections.reverse(postConstructMethods);
    for (Method method : postConstructMethods) {
        boolean accessible = method.isAccessible();
        try {
            if (!accessible) {
                method.setAccessible(true);
            }
            method.invoke(object);
        } finally {
            if (!accessible) {
                method.setAccessible(false);
            }
        }
    }
}

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();/*from w  w w  .ja v a2 s.c  om*/
        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:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public String getDbName(Boolean isCamelCase, String attributeName, Method method) {
    if (method != null && method.isAnnotationPresent(Column.class)) {
        Column c = method.getAnnotation(Column.class);
        return c.name();
    } else {//  w ww .  ja  va 2  s  .c o  m
        String fieldName = "";
        if (isCamelCase) {
            fieldName = attributeName;
        } else {
            fieldName = getDbName(attributeName);
        }
        return fieldName;
    }
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public String getIdFieldName(HashMap<Method, String> fieldMap) {
    for (Method method : fieldMap.keySet()) {
        if (method.isAnnotationPresent(Id.class)) {
            return fieldMap.get(method);
        }//from  w  w w .  j  a v a 2  s.co m
    }
    return null;
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public String getIdFieldName(Class clazz) {
    Boolean useCamelCase = this.useCamelCase(clazz);
    HashMap<Method, String> fieldMap = this.getFieldMapping(clazz, GET, useCamelCase, Boolean.TRUE);
    for (Method method : fieldMap.keySet()) {
        if (method.isAnnotationPresent(Id.class)) {
            return getDbName(useCamelCase, method.getName().substring(3), method);
        }//from   w ww  . j a  va  2s . c  o m
    }
    return null;
}

From source file:org.protorabbit.json.DefaultSerializer.java

protected boolean skipSerialization(Method m) {
    boolean skipIt = !(Modifier.isPublic(m.getModifiers()) && !"getHibernateLazyInitializer".equals(m.getName())
            && !"getClass".equals(m.getName()) && !"getParent".equals(m.getName())
            && !"getSystemClassLoader".equals(m.getName()) && !"getMethods".equals(m.getName())
            && !"getDeclaredClasses".equals(m.getName()) && !"getConstructors".equals(m.getName())
            && !"getDeclaringClass".equals(m.getName()) && !"getEnclosingClass".equals(m.getName())
            && !"getClassLoader".equals(m.getName())
            && (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.getName().length() > 2
            && m.getParameterTypes().length == 0);
    if (!skipIt && m.isAnnotationPresent(Serialize.class)) {
        Serialize s = m.getAnnotation(Serialize.class);

        if ("skip".equals(s.value())) {
            skipIt = true;//  w  ww .  j  a  va  2  s . co  m
        }
    }
    return skipIt;
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of available SENSE service API resource URLs.
 *
 * Operation: GET /api/sense/v1/*from ww w  .  jav  a2  s  .  co m*/
 *
 * @return A RESTful response.
 * @throws java.net.MalformedURLException
 */
@ApiOperation(value = "Get a list of supported SENSE resources.", notes = "Returns a list of available SENSE resource URL.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_MSG, response = Resource.class),
        @ApiResponse(code = HttpConstants.UNAUTHORIZED_CODE, message = HttpConstants.UNAUTHORIZED_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class), })
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getResources() throws MalformedURLException {
    try {
        // We need the request URL to build fully qualified resource URLs.
        final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

        log.info("[SenseRmController] GET operation = {}", location);

        // We will populate some HTTP response headers.
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Location", location.toASCIIString());

        List<Resource> resources = new ArrayList<>();
        Method[] methods = SenseRmController.class.getMethods();
        for (Method m : methods) {
            if (m.isAnnotationPresent(ResourceAnnotation.class)) {
                ResourceAnnotation ra = m.getAnnotation(ResourceAnnotation.class);
                RequestMapping rm = m.getAnnotation(RequestMapping.class);
                if (ra == null || rm == null) {
                    continue;
                }
                Resource resource = new Resource();
                resource.setId(ra.name());
                resource.setVersion(ra.version());
                UriComponentsBuilder path = utilities.getPath(location.toASCIIString());
                path.path(rm.value()[0]);
                resource.setHref(path.build().toUriString());
                resources.add(resource);
            }
        }

        return new ResponseEntity<>(resources, headers, HttpStatus.OK);
    } catch (SecurityException | MalformedURLException ex) {
        log.error("[SenseRmController] Exception caught", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}