Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:de.codesourcery.springmass.springmass.SimulationParamsBuilder.java

private String extractParameterName(Method m) {
    Method methodWithLabel = null;
    if (isParameterGetter(m)) {
        // look for @Label on corresponding setter
        if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
            final int charsToRemove = m.getName().startsWith("get") ? 3 : 2;
            final String setterName = "set" + m.getName().substring(charsToRemove);
            try {
                methodWithLabel = m.getDeclaringClass().getMethod(setterName,
                        new Class<?>[] { m.getReturnType() });
            } catch (NoSuchMethodException | SecurityException e) {
                /* ok */ }
        }/* w  w w .j ava  2  s  . c  o m*/
    } else {
        methodWithLabel = m;
    }

    if (methodWithLabel != null) {
        final Label label = methodWithLabel.getAnnotation(Label.class);
        if (label != null && !StringUtils.isBlank(label.value())) {
            return label.value();
        }
    }

    String name;
    if (m.getName().startsWith("set") || m.getName().startsWith("get")) {
        name = m.getName().substring(3);
    } else if (m.getName().startsWith("is")) {
        name = m.getName().substring(2);
    } else {
        throw new IllegalArgumentException("Invalid method name: " + m);
    }
    name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
    final List<String> split = new ArrayList<>();
    final StringBuffer buffer = new StringBuffer();
    for (char s : name.toCharArray()) {
        if (Character.isUpperCase(s)) {
            if (buffer.length() > 1) {
                split.add(buffer.toString());
                buffer.setLength(0);
                buffer.append(Character.toLowerCase(s));
                continue;
            }
        }
        if (split.isEmpty()) {
            buffer.append(s);
        } else {
            buffer.append(Character.toLowerCase(s));
        }
    }
    if (buffer.length() > 0) {
        split.add(buffer.toString());
    }

    return StringUtils.join(split, " ");
}

From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException {
    if (log.isDebugEnabled())
        log.debug("getAttribute " + name);
    Method getter = (Method) _getter.get(name);
    if (getter == null)
        throw new AttributeNotFoundException(name);
    try {/*from  ww  w. ja  v  a 2 s.co  m*/
        Object o = _object;
        if (getter.getDeclaringClass().isInstance(this))
            o = this;
        return getter.invoke(o, (java.lang.Object[]) null);
    } catch (IllegalAccessException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new AttributeNotFoundException(e.toString());
    } catch (InvocationTargetException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new ReflectionException((Exception) e.getTargetException());
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

public Object invoke(String name, Object[] params, String[] signature)
        throws MBeanException, ReflectionException {
    if (log.isDebugEnabled())
        log.debug("invoke " + name);

    String methodKey = name + "(";
    if (signature != null)
        for (int i = 0; i < signature.length; i++)
            methodKey += (i > 0 ? "," : "") + signature[i];
    methodKey += ")";

    try {/*from   w ww  . ja  va 2 s .  c  o  m*/
        Method method = (Method) _method.get(methodKey);
        if (method == null)
            throw new NoSuchMethodException(methodKey);

        Object o = _object;
        if (method.getDeclaringClass().isInstance(this))
            o = this;
        return method.invoke(o, params);
    } catch (NoSuchMethodException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new ReflectionException(e);
    } catch (IllegalAccessException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new MBeanException(e);
    } catch (InvocationTargetException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new ReflectionException((Exception) e.getTargetException());
    }

}

From source file:org.aludratest.testcase.data.impl.xml.XmlBasedTestDataProvider.java

private InputStream tryFindXml(String uri, Method testMethod)
        throws IOException, AutomationException, URISyntaxException {
    if (uri.matches("[a-z]+://.*")) {
        URI realUri = new URI(uri);
        URL url = realUri.toURL();
        return url.openStream();
    }//from w  w w. ja  v  a  2s .c o  m

    // first search try: full path, as used for Excels
    StringBuilder sbPath = new StringBuilder();
    sbPath.append(aludraConfig.getXlsRootPath());

    if (sbPath.toString().endsWith(File.separator)) {
        sbPath.delete(sbPath.length() - 1, sbPath.length());
    }
    sbPath.append(File.separator);
    sbPath.append(testMethod.getDeclaringClass().getName().replace(".", File.separator));
    sbPath.append(File.separator);
    sbPath.append(uri);
    File f = new File(sbPath.toString());
    if (f.isFile()) {
        return new FileInputStream(f);
    }

    // second try: directly under root path
    sbPath = new StringBuilder();
    sbPath.append(aludraConfig.getXlsRootPath());

    if (sbPath.toString().endsWith(File.separator)) {
        sbPath.delete(sbPath.length() - 1, sbPath.length());
    }
    sbPath.append(File.separator);
    sbPath.append(uri);
    f = new File(sbPath.toString());
    if (f.isFile()) {
        return new FileInputStream(f);
    }

    throw new AutomationException("Could not find test data XML file " + uri);
}

From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

public void setAttribute(Attribute attr)
        throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    if (attr == null)
        return;/*from   w  ww  .j a v a  2 s . c om*/

    if (log.isDebugEnabled())
        log.debug("setAttribute " + attr.getName() + "=" + attr.getValue());
    Method setter = (Method) _setter.get(attr.getName());
    if (setter == null)
        throw new AttributeNotFoundException(attr.getName());
    try {
        Object o = _object;
        if (setter.getDeclaringClass().isInstance(this))
            o = this;
        setter.invoke(o, new Object[] { attr.getValue() });
    } catch (IllegalAccessException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new AttributeNotFoundException(e.toString());
    } catch (InvocationTargetException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new ReflectionException((Exception) e.getTargetException());
    }
}

From source file:com.developmentsprint.spring.breaker.annotations.AbstractFallbackCircuitBreakerAttributeSource.java

/**
 * Determine the circuit breaker attribute for this method invocation.
 * <p>//from  ww w. j  a  v a  2  s .  c  o m
 * Defaults to the class's circuit breaker attribute if no method attribute is found.
 * 
 * @param method
 *            the method for the current invocation (never {@code null})
 * @param targetClass
 *            the target class for this invocation (may be {@code null})
 * @return CircuitBreakerAttribute for this method, or {@code null} if the method is not wrapped in a circuit breaker
 */
public CircuitBreakerAttribute getCircuitBreakerAttribute(Method method, Class<?> targetClass) {
    // First, see if we have a cached value.
    Object cacheKey = getCacheKey(method, targetClass);
    Object cached = this.attributeCache.get(cacheKey);
    if (cached != null) {
        // Value will either be canonical value indicating there is no circuit breaker attribute,
        // or an actual circuit breaker attribute.
        if (cached == NULL_CIRCUIT_BREAKER_ATTRIBUTE) {
            return null;
        } else {
            return (CircuitBreakerAttribute) cached;
        }
    } else {
        // We need to work it out.
        CircuitBreakerAttribute cbAttribute = computeCircuitBreakerAttribute(method, targetClass);
        // Put it in the cache.
        if (cbAttribute == null) {
            this.attributeCache.put(cacheKey, NULL_CIRCUIT_BREAKER_ATTRIBUTE);
        } else {
            if (log.isDebugEnabled()) {
                Class<?> classToLog = (targetClass != null ? targetClass : method.getDeclaringClass());
                log.debug("Adding circuit breaker method '{}.{}' with attribute: {}",
                        classToLog.getSimpleName(), method.getName(), cbAttribute);
            }
            this.attributeCache.put(cacheKey, cbAttribute);
        }
        return cbAttribute;
    }
}

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 ww  . j a v  a2s .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:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

private void runInitMethod(Method method) {
    Class<?>[] parameters = method.getParameterTypes();
    Object[] args = new Object[parameters.length];

    for (int i = 0; i < parameters.length; i++) {
        Class<?> parameter = parameters[i];
        if (parameter == HeavySpleef.class) {
            args[i] = heavySpleef;/* w  w w  .  j a  v  a 2  s .  c om*/
        }
    }

    try {
        method.invoke(null, args);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new IllegalArgumentException("Could not invoke flag initialization method " + method.getName()
                + " of type " + method.getDeclaringClass().getCanonicalName() + ": ", e);
    }
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Parse callback methods into the given array, and return that array,
 * creating one if null. Each index into the array is a collection of
 * callback adapters for that numeric event type.
 *
 * @param sups whether to scan superclasses
 * @param listener whether this is a listener or not
 *//* w  w w  .  j av a2 s. com*/
public static Collection<LifecycleCallbacks>[] parseCallbackMethods(Class<?> cls,
        Collection<LifecycleCallbacks>[] callbacks, boolean sups, boolean listener, MetaDataRepository repos) {

    if (cls == null)
        throw new IllegalArgumentException("cls cannot be null");

    // first sort / filter based on inheritance
    Set<Method> methods = new TreeSet<Method>(MethodComparator.getInstance());

    int mods;
    Class<?> sup = cls;
    MethodKey key;
    Set<MethodKey> seen = new HashSet<MethodKey>();
    do {
        for (Method m : (Method[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(sup))) {
            mods = m.getModifiers();
            if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || Object.class.equals(m.getDeclaringClass()))
                continue;

            key = new MethodKey(m);
            if (!seen.contains(key)) {
                methods.add(m);
                seen.add(key);
            }
        }
        sup = sup.getSuperclass();
    } while (sups && !Object.class.equals(sup));

    OpenJPAConfiguration conf = repos.getConfiguration();
    for (Method m : methods) {
        for (Annotation anno : (Annotation[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredAnnotationsAction(m))) {
            MetaDataTag tag = _tags.get(anno.annotationType());
            if (tag == null)
                continue;
            int[] events = MetaDataParsers.getEventTypes(tag, conf);
            if (events == null)
                continue;

            if (callbacks == null)
                callbacks = (Collection<LifecycleCallbacks>[]) new Collection[LifecycleEvent.ALL_EVENTS.length];

            for (int i = 0; i < events.length; i++) {
                int e = events[i];
                if (callbacks[e] == null)
                    callbacks[e] = new ArrayList<LifecycleCallbacks>(3);
                MetaDataParsers.validateMethodsForSameCallback(cls, callbacks[e], m, tag, conf, repos.getLog());
                if (listener) {
                    callbacks[e].add(new BeanLifecycleCallbacks(cls, m, false));
                } else {
                    callbacks[e].add(new MethodLifecycleCallbacks(m, false));
                }
            }
        }
    }
    return callbacks;
}