Example usage for org.apache.commons.lang3.reflect ConstructorUtils getAccessibleConstructor

List of usage examples for org.apache.commons.lang3.reflect ConstructorUtils getAccessibleConstructor

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect ConstructorUtils getAccessibleConstructor.

Prototype

public static <T> Constructor<T> getAccessibleConstructor(final Class<T> cls,
        final Class<?>... parameterTypes) 

Source Link

Document

Finds a constructor given a class and signature, checking accessibility.

This finds the constructor and ensures that it is accessible.

Usage

From source file:com.avego.oauth.migration.OauthMigrationDaoFactory.java

/**
 * This creates an instance of a token dao
 * @param params The dao params//from   w  ww. j  a v a2  s.  c om
 * @return The token dao instance
 * @throws DaoCreationException If it failed to instantiate the dao
 */
public static OauthMigrationDao newInstance(Map<String, Object> params) throws DaoCreationException {

    OauthMigrationDao dao = null;
    String className = System.getProperty(MIGRATION_DAO_PROPERTY, DEFAULT_MIGRATION_DAO);
    if (params != null && params.containsKey(MIGRATION_DAO_PROPERTY)) {
        String paramClassName = (String) params.get(MIGRATION_DAO_PROPERTY);
        if (paramClassName != null && paramClassName.length() > 0) {
            className = paramClassName;
        }
    }
    Constructor<OauthMigrationDao> constructor = null;
    try {
        @SuppressWarnings("unchecked")
        Class<OauthMigrationDao> clazz = (Class<OauthMigrationDao>) Class.forName(className);

        // look for a constructor that takes the jdbc template
        constructor = ConstructorUtils.getAccessibleConstructor(clazz, Map.class);
        if (constructor == null) {
            // use default no arg constructor
            constructor = ConstructorUtils.getAccessibleConstructor(clazz);
            if (constructor != null) {
                dao = constructor.newInstance();
            }
        } else {
            dao = constructor.newInstance(params);
        }
    } catch (Exception ex) {
        throw new DaoCreationException(
                "Failed to create the dao with the class: " + className + ", msg; " + ex.getMessage(), ex);
    }
    if (constructor == null) {
        throw new DaoCreationException("The class: " + className
                + " Did not have a no args constructor nor a constructor taking a Map<String, Object>");
    }
    return dao;
}

From source file:fr.mycellar.test.matchers.PropertiesMatcher.java

protected final <G> void addNullableProperty(String property, G value,
        Class<? extends PropertiesMatcher<G>> matcherClass) {
    if (value != null) {
        try {//w  ww .j a va2  s  .  c om
            addProperty(property, ConstructorUtils.getAccessibleConstructor(matcherClass, value.getClass())
                    .newInstance(value));
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    } else {
        addProperty(property, is(nullValue()));
    }
}

From source file:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates the oauth access tokens
 * @throws IOException If an IO error occurs such as when serializing/deserializing data
 * @throws ClassNotFoundException If a class not found when serializing/deserializing data
 * @throws InvocationTargetException If an invocation target exception occurs when using reflection to convert to the new objects
 * @throws IllegalAccessException If an IllegalAccessException exception occurs when using reflection to convert to the new objects
 * @throws NoSuchMethodException If a NoSuchMethodException exception occurs when using reflection to convert to the new objects
 * @throws InstantiationException/*from   w  w  w .j a va  2 s.c o m*/
 * @throws IllegalArgumentException
 */
@SuppressWarnings("unchecked")
protected void migrateAccessTokens() throws IOException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, IllegalArgumentException, InstantiationException {

    int numTokens = this.dao.countUnmigratedAccessTokens();
    int pageSize = PAGE_SIZE;

    int numMigrated = 0;
    System.out.println("Starting Migrating " + numTokens + " access token(s) ...");

    while (numTokens > 0) {

        List<OauthAccessTokenRecord> accessTokens = this.dao.getUnmigratedOauthAccessTokenRecords(pageSize);

        for (OauthAccessTokenRecord tokenRecord : accessTokens) {

            String oldTokenId = tokenRecord.getTokenId();
            System.out.println("Migrating token with id: " + oldTokenId + "...");

            String newTokenId = this.dao.generateNewTokenKey(tokenRecord.getTokenId());
            String newRefreshToken = this.dao.generateNewTokenKey(tokenRecord.getRefreshToken());

            if (this.removeRefreshTokens) {
                newRefreshToken = null;
            }

            System.out.println("New token id: " + newTokenId);
            System.out.println("New refresh token id: " + newRefreshToken);

            // deserialize the token, note this is backward compatible
            OAuth2AccessToken accessToken = null;
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(tokenRecord.getToken()));
            try {
                Object obj = ois.readObject();
                accessToken = (OAuth2AccessToken) obj;
            } finally {
                ois.close();
            }

            // replace the token value in the access token..
            if (this.serializeNewTokenValues) {

                Constructor<OAuth2AccessToken> constructor = null;

                // see if it has a set value method
                Method setValueMethod = MethodUtils.getAccessibleMethod(accessToken.getClass(), "setValue",
                        String.class);
                if (setValueMethod != null) {
                    Object res = setValueMethod.invoke(accessToken, newTokenId);
                    if (res != null && res instanceof OAuth2AccessToken) {
                        accessToken = (OAuth2AccessToken) res;
                    }
                } else {

                    // look for constructors that we can use
                    constructor = (Constructor<OAuth2AccessToken>) ConstructorUtils
                            .getAccessibleConstructor(accessToken.getClass(), String.class);
                    if (constructor != null) {

                        OAuth2AccessToken newAccessToken = constructor.newInstance(newTokenId);

                        // we also need to invoke setters for other fields
                        MethodUtils.invokeMethod(newAccessToken, "setAdditionalInformation",
                                accessToken.getAdditionalInformation());
                        MethodUtils.invokeMethod(newAccessToken, "setExpiration", accessToken.getExpiration());
                        MethodUtils.invokeMethod(newAccessToken, "setScope", accessToken.getScope());
                        MethodUtils.invokeMethod(newAccessToken, "setTokenType", accessToken.getTokenType());

                        accessToken = newAccessToken;

                    } else {
                        throw new IllegalStateException("The access token with the class: "
                                + accessToken.getClass().getName()
                                + " did not have a set value method nor a constructor taking a string which we need to update its token value");
                    }

                }

                // we also need to overwrite the refresh token
                String newRefreshTokenValue = this.dao
                        .generateNewTokenKey(accessToken.getRefreshToken().getValue());
                OAuth2RefreshToken refreshToken = replaceOAuth2RefreshTokenValue(accessToken.getRefreshToken(),
                        newRefreshTokenValue);
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", refreshToken);
            }

            if (this.removeRefreshTokens) {
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", new Object[] { null },
                        new Class<?>[] { OAuth2RefreshToken.class });
            }

            byte[] tokenData = SerializationUtils.serialize((Serializable) accessToken);

            // deserialise the authenticated, this is NOT backward compatible so we have to read using a diff class loader
            OAuth2Authentication auth = deserializeOAuth2Authentication(tokenRecord.getAuthentication());
            byte[] authData = SerializationUtils.serialize(auth);

            // this does the actual migration of the token
            this.dao.updateOauthAccessToken(oldTokenId, newTokenId, newRefreshToken, tokenData, authData);

            System.out.println("Migrated token with id: " + oldTokenId);
            numMigrated++;
            System.out.println("");
        }
        numTokens = this.dao.countUnmigratedAccessTokens();
    }

    System.out.println("Finished Migrating " + numMigrated + " access token(s).");

}

From source file:org.gerzog.spock.injectmock.internal.accessors.ConstructorAccessor.java

@Override
public boolean exists(final Class<?> clazz, final String name, final Class<?>... types) {
    return ConstructorUtils.getAccessibleConstructor(clazz, types) != null;
}

From source file:org.lenskit.data.entities.Entities.java

/**
 * Project an entity to a target view type.
 * @param e The entity to project.//from w w w .ja  v  a  2  s  .com
 * @param viewClass The view type.
 * @param <E> The view type.
 * @return The projected entity.
 */
public static <E extends Entity> E project(@Nonnull Entity e, @Nonnull Class<E> viewClass) {
    if (viewClass.isInstance(e)) {
        return viewClass.cast(e);
    } else {
        Optional<Constructor<? extends EntityBuilder>> ctor = BUILDER_CTOR_CACHE.get(viewClass);
        if (ctor == null) {
            BuiltBy bb = viewClass.getAnnotation(BuiltBy.class);
            if (bb != null) {
                Class<? extends EntityBuilder> ebClass = bb.value();
                Constructor<? extends EntityBuilder> found = ConstructorUtils.getAccessibleConstructor(ebClass,
                        EntityType.class);
                ctor = Optional.<Constructor<? extends EntityBuilder>>fromNullable(found);
            } else {
                ctor = Optional.absent();
            }
            BUILDER_CTOR_CACHE.put(viewClass, ctor);
        }

        if (ctor.isPresent()) {
            EntityBuilder builder = null;
            try {
                builder = ctor.get().newInstance(e.getType());
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
                throw new RuntimeException("cannot invoke " + ctor.get(), ex);
            }
            for (Attribute<?> attr : e.getAttributes()) {
                builder.setAttribute(attr);
            }
            return viewClass.cast(builder.build());
        } else {
            throw new IllegalArgumentException(
                    "entity type " + e.getClass() + " cannot be projected to " + viewClass);
        }
    }
}