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

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

Introduction

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

Prototype

public static <T> T invokeConstructor(final Class<T> cls, Object... args) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException 

Source Link

Document

Returns a new instance of the specified class inferring the right constructor from the types of the arguments.

This locates and calls a constructor.

Usage

From source file:org.java0.factory.FactoryUtil.java

/**
 * Create an object of the given concrete type using the given constructor
 * arguments.//from   w  ww . j a  v  a 2s. co m
 * 
 * @param concreteType
 * @param constructorArgs
 * @return
 */
public static <T> T createNewObject(Class<T> concreteType, Object... constructorArgs) {
    T newObject = null;
    try {
        newObject = ConstructorUtils.invokeConstructor(concreteType, constructorArgs);
    } catch (NoSuchMethodException e) {
        Class<?>[] argTypes = null;
        argTypes = new Class[constructorArgs.length];
        for (int i = 0; i < constructorArgs.length; ++i) {
            argTypes[i] = constructorArgs[i].getClass();
        }
        StringBuffer message = new StringBuffer("Constructor not found: ");
        message.append(concreteType.getName());
        message.append("(");
        for (int i = 0; i < argTypes.length; ++i) {
            if (i > 0) {
                message.append(", ");
            }
            message.append(argTypes[i].getName());
        }
        message.append(")");

        throw logUtil.exception(new FactoryException(message.toString(), e));
    } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw logUtil.exception(new FactoryException("Received exception instantiating new object", e));
    }

    return newObject;
}

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

private static AttrMethod[] lookupAttrs(Class<? extends AbstractBeanEntityBuilder> type) {
    AttrMethod[] res = cache.get(type);//from www .ja v  a  2 s.c o m
    if (res != null) {
        return res;
    }

    DynamicClassLoader dlc = new DynamicClassLoader(type.getClassLoader());
    Map<TypedName<?>, Method> setters = new HashMap<>();
    Map<String, Method> clearers = new HashMap<>();
    for (Method m : type.getMethods()) {
        EntityAttributeSetter annot = m.getAnnotation(EntityAttributeSetter.class);
        if (annot != null) {
            Type[] params = m.getParameterTypes();
            if (params.length != 1) {
                throw new IllegalArgumentException(
                        "method " + m + " has " + params.length + " parameters, expected 1");
            }
            TypeToken atype = TypeToken.of(params[0]);
            TypedName<?> name = TypedName.create(annot.value(), atype);
            setters.put(name, m);
        }
        EntityAttributeClearer clearAnnot = m.getAnnotation(EntityAttributeClearer.class);
        if (clearAnnot != null) {
            clearers.put(clearAnnot.value(), m);
        }
    }

    AttrMethod[] ael = new AttrMethod[setters.size()];
    int attrIdx = 0;
    for (Map.Entry<TypedName<?>, Method> ce : setters.entrySet()) {
        TypedName<?> attr = ce.getKey();
        Method smethod = ce.getValue();
        Class smVtype = smethod.getParameterTypes()[0];
        Method cmethod = clearers.get(ce.getKey().getName());
        ClassNode cn = new ClassNode();
        cn.name = String.format("org/lenskit/generated/entities/AttrSet$$%s$$%s",
                type.getName().replace('.', '$'), ce.getValue().getName());
        cn.access = ACC_PUBLIC;
        cn.version = V1_8;
        Class<? extends AttrMethod> sc;
        if (attr.getRawType().equals(Long.class) && smVtype.equals(long.class)) {
            sc = LongAttrMethod.class;
        } else if (attr.getRawType().equals(Double.class) && smVtype.equals(double.class)) {
            sc = DoubleAttrMethod.class;
        } else {
            sc = AttrMethod.class;
        }
        cn.superName = getInternalName(sc);
        MethodNode ctor = generateBeanConstructor(sc);
        cn.methods.add(ctor);

        MethodNode setter = generateSetter(type, smethod);
        cn.methods.add(setter);
        if (attr.getRawType().equals(Long.class) && smVtype.equals(long.class)) {
            cn.methods.add(generateLongSetter(type, smethod));
        }
        if (attr.getRawType().equals(Double.class) && smVtype.equals(double.class)) {
            cn.methods.add(generateDoubleSetter(type, smethod));
        }

        MethodNode clearer = generateClearer(type, smethod, cmethod);
        cn.methods.add(clearer);

        Class<? extends AttrMethod> cls = dlc.defineClass(cn).asSubclass(AttrMethod.class);
        try {
            ael[attrIdx++] = ConstructorUtils.invokeConstructor(cls, attr);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
                | InvocationTargetException e) {
            throw new RuntimeException("cannot instantiate " + cls, e);
        }
    }

    cache.put(type, ael);
    return ael;
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyFactoryImpl.java

/**
 * {@inheritDoc}//from w w  w.  j a  v  a 2 s  .co  m
 */
@Override
public ServerConnector createConnector(final Server server, final String name, final int port, int securePort,
        final String host, final Boolean checkForwaredHeaders) {

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme(HttpScheme.HTTPS.asString());
    httpConfig.setSecurePort(securePort != 0 ? securePort : 8443);
    httpConfig.setOutputBufferSize(32768);
    if (checkForwaredHeaders) {
        httpConfig.addCustomizer(new ForwardedRequestCustomizer());
    }

    ConnectionFactory factory = null;

    if (alpnCLassesAvailable()) {
        log.info("HTTP/2 available, adding HTTP/2 to connector");
        // SPDY connector
        //         ServerConnector spdy;
        try {
            //            Class<?> loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnector");
            //            Constructor<?>[] constructors = loadClass.getConstructors();
            //
            //            for (Constructor<?> constructor : constructors) {
            //               Class<?>[] parameterTypes = constructor.getParameterTypes();
            //               if (parameterTypes.length == 1 && parameterTypes[0].equals(Server.class)) {
            //                  spdy = (ServerConnector) constructor.newInstance(server);
            //
            //                  spdy.setPort(port);
            //                  spdy.setName(name);
            //                  spdy.setHost(host);
            //                  spdy.setIdleTimeout(500000);
            //
            //                  return spdy;
            //               }
            //            }
            //
            Class<?> loadClass = bundle
                    .loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");
            factory = (ConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, httpConfig);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | NoSuchMethodException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        log.info("HTTP/2 not available, creating standard ServerConnector for Http");
        factory = new HttpConnectionFactory(httpConfig);
    }

    // HTTP connector
    ServerConnector http = new ServerConnector(server);
    http.addConnectionFactory(factory);
    http.setPort(port);
    http.setHost(host);
    http.setName(name);
    http.setIdleTimeout(30000);

    return http;
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyFactoryImpl.java

/**
 * {@inheritDoc}//from w  ww .j  a  v a  2 s  .  co  m
 */
@Override
public ServerConnector createSecureConnector(Server server, String name, int port, String sslKeystore,
        String sslKeystorePassword, String sslKeyPassword, String host, String sslKeystoreType,
        String sslKeyAlias, String trustStore, String trustStorePassword, String trustStoreType,
        boolean isClientAuthNeeded, boolean isClientAuthWanted, List<String> cipherSuitesIncluded,
        List<String> cipherSuitesExcluded, List<String> protocolsIncluded, List<String> protocolsExcluded,
        Boolean sslRenegotiationAllowed, String crlPath, Boolean enableCRLDP, Boolean validateCerts,
        Boolean validatePeerCerts, Boolean enableOCSP, String ocspResponderURL) {

    // SSL Context Factory for HTTPS and SPDY
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(sslKeystore);
    sslContextFactory.setKeyStorePassword(sslKeystorePassword);
    sslContextFactory.setKeyManagerPassword(sslKeyPassword);
    sslContextFactory.setNeedClientAuth(isClientAuthNeeded);
    sslContextFactory.setWantClientAuth(isClientAuthWanted);
    sslContextFactory.setEnableCRLDP(enableCRLDP);
    sslContextFactory.setValidateCerts(validateCerts);
    sslContextFactory.setValidatePeerCerts(validatePeerCerts);
    sslContextFactory.setEnableOCSP(enableOCSP);
    if ((null != crlPath) && (!"".equals(crlPath))) {
        sslContextFactory.setCrlPath(crlPath);
    }
    if ((null != ocspResponderURL) && (!"".equals(ocspResponderURL))) {
        sslContextFactory.setOcspResponderURL(ocspResponderURL);
    }
    if (sslKeystoreType != null) {
        sslContextFactory.setKeyStoreType(sslKeystoreType);
    }
    // Java key stores may contain more than one private key entry.
    // Specifying the alias tells jetty which one to use.
    if ((null != sslKeyAlias) && (!"".equals(sslKeyAlias))) {
        sslContextFactory.setCertAlias(sslKeyAlias);
    }

    // Quite often it is useful to use a certificate trust store other than the JVM default.
    if ((null != trustStore) && (!"".equals(trustStore))) {
        sslContextFactory.setTrustStorePath(trustStore);
    }
    if ((null != trustStorePassword) && (!"".equals(trustStorePassword))) {
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    if ((null != trustStoreType) && (!"".equals(trustStoreType))) {
        sslContextFactory.setTrustStoreType(trustStoreType);
    }

    // In light of well-known attacks against weak encryption algorithms such as RC4,
    // it is usefull to be able to include or exclude certain ciphersuites.
    // Due to the overwhelming number of cipher suites using regex to specify inclusions
    // and exclusions greatly simplifies configuration.
    final String[] cipherSuites;
    try {
        SSLContext context = SSLContext.getDefault();
        SSLSocketFactory sf = context.getSocketFactory();
        cipherSuites = sf.getSupportedCipherSuites();
    } catch (NoSuchAlgorithmException e) {

        throw new RuntimeException("Failed to get supported cipher suites.", e);
    }

    if (cipherSuitesIncluded != null && !cipherSuitesIncluded.isEmpty()) {
        final List<String> cipherSuitesToInclude = new ArrayList<>();
        for (final String cipherSuite : cipherSuites) {
            for (final String includeRegex : cipherSuitesIncluded) {
                if (cipherSuite.matches(includeRegex)) {
                    cipherSuitesToInclude.add(cipherSuite);
                }
            }
        }
        sslContextFactory.setIncludeCipherSuites(
                cipherSuitesToInclude.toArray(new String[cipherSuitesToInclude.size()]));
    }

    if (cipherSuitesExcluded != null && !cipherSuitesExcluded.isEmpty()) {
        final List<String> cipherSuitesToExclude = new ArrayList<>();
        for (final String cipherSuite : cipherSuites) {
            for (final String excludeRegex : cipherSuitesExcluded) {
                if (cipherSuite.matches(excludeRegex)) {
                    cipherSuitesToExclude.add(cipherSuite);
                }
            }
        }
        sslContextFactory.setExcludeCipherSuites(
                cipherSuitesToExclude.toArray(new String[cipherSuitesToExclude.size()]));
    }

    // In light of attacks against SSL 3.0 as "POODLE" it is useful to include or exclude
    // SSL/TLS protocols as needed.
    if ((null != protocolsIncluded) && (!protocolsIncluded.isEmpty())) {
        sslContextFactory.setIncludeProtocols(protocolsIncluded.toArray(new String[protocolsIncluded.size()]));
    }
    if ((null != protocolsExcluded) && (!protocolsExcluded.isEmpty())) {
        sslContextFactory.setExcludeProtocols(protocolsExcluded.toArray(new String[protocolsExcluded.size()]));
    }
    if (sslRenegotiationAllowed != null) {
        sslContextFactory.setRenegotiationAllowed(sslRenegotiationAllowed);
    }

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme(HttpScheme.HTTPS.asString());
    httpConfig.setSecurePort(port);
    httpConfig.setOutputBufferSize(32768);

    // HTTPS Configuration
    HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    List<AbstractConnectionFactory> connectionFactories = new ArrayList<>();

    HttpConnectionFactory httpConFactory = new HttpConnectionFactory(httpsConfig);

    SslConnectionFactory sslFactory = null;
    AbstractConnectionFactory http2Factory = null;

    NegotiatingServerConnectionFactory alpnFactory = null;

    if (alpnCLassesAvailable()) {
        log.info("HTTP/2 available, creating HttpSpdyServerConnector for Https");
        // SPDY connector
        try {
            Class<?> comparatorClass = bundle.loadClass("org.eclipse.jetty.http2.HTTP2Cipher");

            Comparator<String> cipherComparator = (Comparator<String>) FieldUtils
                    .readDeclaredStaticField(comparatorClass, "COMPARATOR");
            sslContextFactory.setCipherComparator(cipherComparator);

            sslFactory = new SslConnectionFactory(sslContextFactory, "h2");
            connectionFactories.add(sslFactory);

            //org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory
            Class<?> loadClass = bundle
                    .loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");
            //            
            //            //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
            //            alpnFactory = (NegotiatingServerConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, (Object) new String[] {"ssl", "http/2", "http/1.1"});
            //            alpnFactory.setDefaultProtocol("http/1.1");
            //            connectionFactories.add(alpnFactory);

            //HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
            //            loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory");
            //            loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");

            http2Factory = (AbstractConnectionFactory) ConstructorUtils.invokeConstructor(loadClass,
                    httpsConfig);
            connectionFactories.add(http2Factory);

        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException
                | IllegalArgumentException | IllegalAccessException | InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        log.info("SPDY not available, creating standard ServerConnector for Https");
        sslFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
    }

    //      HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
    //      
    //      ServerConnector https = new ServerConnector(server); 

    // HTTPS connector
    ServerConnector https = new ServerConnector(server, sslFactory, httpConFactory);
    for (AbstractConnectionFactory factory : connectionFactories) {
        https.addConnectionFactory(factory);
    }

    https.setPort(port);
    https.setName(name);
    https.setHost(host);
    https.setIdleTimeout(500000);

    /*
             
    SslContextFactory sslContextFactory = new SslContextFactory();
    HttpConfiguration httpConfig = new HttpConfiguration();
            
    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "alpn");
    ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
    alpn.setDefaultProtocol("http/1.1");
    HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
    HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);
            
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, new ConnectionFactory[]{ssl, alpn, spdy, http});
             
     */

    return https;

}

From source file:org.panthercode.arctic.core.reflect.ClassBuilder.java

/**
 * Create a new instance of the given class with stored  arguments.
 *
 * @return Returns a new instance.//from   w  w  w  .  j a va2s  .  c  om
 * @throws NoSuchMethodException     Is thrown if no matching constructor exists to the given argument signature.
 * @throws IllegalAccessException    Is thrown if invocation is not permitted by security. For example the constructor
 *                                   you would like to call has not modification <tt>public</tt>.
 * @throws InstantiationException    Is thrown if an error occurs on instantiation.
 * @throws InvocationTargetException Is thrown if an error occurs on invocation.
 */
public T build() throws NoSuchMethodException, IllegalAccessException, InstantiationException,
        InvocationTargetException {
    return ConstructorUtils.invokeConstructor(clazz, this.arguments);
}

From source file:org.spongepowered.common.mixin.core.world.MixinWorld.java

@Override
public Optional<Entity> createEntity(EntityType type, Vector3d position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");

    Entity entity = null;//from w w  w.ja v a2 s .co m

    Class<? extends Entity> entityClass = type.getEntityClass();
    double x = position.getX();
    double y = position.getY();
    double z = position.getZ();

    if (entityClass.isAssignableFrom(EntityPlayerMP.class)
            || entityClass.isAssignableFrom(EntityDragonPart.class)) {
        // Unable to construct these
        return Optional.empty();
    }

    net.minecraft.world.World world = (net.minecraft.world.World) (Object) this;

    // Not all entities have a single World parameter as their constructor
    if (entityClass.isAssignableFrom(EntityLightningBolt.class)) {
        entity = (Entity) new EntityLightningBolt(world, x, y, z);
    } else if (entityClass.isAssignableFrom(EntityEnderPearl.class)) {
        EntityArmorStand tempEntity = new EntityArmorStand(world, x, y, z);
        tempEntity.posY -= tempEntity.getEyeHeight();
        entity = (Entity) new EntityEnderPearl(world, tempEntity);
        ((EnderPearl) entity).setShooter(ProjectileSource.UNKNOWN);
    }

    // Some entities need to have non-null fields (and the easiest way to
    // set them is to use the more specialised constructor).
    if (entityClass.isAssignableFrom(EntityFallingBlock.class)) {
        entity = (Entity) new EntityFallingBlock(world, x, y, z, Blocks.sand.getDefaultState());
    } else if (entityClass.isAssignableFrom(EntityItem.class)) {
        entity = (Entity) new EntityItem(world, x, y, z, new ItemStack(Blocks.stone));
    }

    if (entity == null) {
        try {
            entity = ConstructorUtils.invokeConstructor(entityClass, this);
            ((net.minecraft.entity.Entity) entity).setPosition(x, y, z);
        } catch (Exception e) {
            SpongeImpl.getLogger().error(ExceptionUtils.getStackTrace(e));
        }
    }

    // TODO - replace this with an actual check
    /*
    if (entity instanceof EntityHanging) {
    if (((EntityHanging) entity).facingDirection == null) {
        // TODO Some sort of detection of a valid direction?
        // i.e scan immediate blocks for something to attach onto.
        ((EntityHanging) entity).facingDirection = EnumFacing.NORTH;
    }
    if (!((EntityHanging) entity).onValidSurface()) {
        return Optional.empty();
    }
    }*/

    // Last chance to fix null fields
    if (entity instanceof EntityPotion) {
        // make sure EntityPotion.potionDamage is not null
        ((EntityPotion) entity).getPotionDamage();
    } else if (entity instanceof EntityPainting) {
        // This is default when art is null when reading from NBT, could
        // choose a random art instead?
        ((EntityPainting) entity).art = EnumArt.KEBAB;
    }

    return Optional.ofNullable(entity);
}

From source file:org.spongepowered.mod.mixin.core.world.MixinWorld.java

@Override
public Optional<Entity> createEntity(EntityType type, Vector3d position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");

    Entity entity = null;/*from w  w  w .  j a  v  a2  s .c om*/

    try {
        entity = ConstructorUtils.invokeConstructor(type.getEntityClass(), this);
        entity.setLocation(entity.getLocation().setPosition(position));
    } catch (Exception e) {
        SpongeMod.instance.getLogger().error(ExceptionUtils.getStackTrace(e));
    }
    return Optional.fromNullable(entity);
}

From source file:org.spongepowered.mod.mixin.core.world.MixinWorld.java

@Override
public Optional<Entity> createEntity(EntityType type, Vector3i position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");
    Entity entity = null;// ww  w  .  j  av  a2 s. c  o m

    try {
        entity = ConstructorUtils.invokeConstructor(type.getEntityClass(), this);
        entity.setLocation(entity.getLocation().setPosition(position.toDouble()));
    } catch (Exception e) {
        SpongeMod.instance.getLogger().error(ExceptionUtils.getStackTrace(e));
    }
    return Optional.fromNullable(entity);
}

From source file:org.spongepowered.mod.mixin.world.MixinWorld.java

@Override
public Optional<Entity> createEntity(EntityType type, Vector3d position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");

    Entity entity = null;//from w w  w . j a  va  2s  .c  o  m

    try {
        entity = ConstructorUtils.invokeConstructor(type.getEntityClass(), this);
        entity.setLocation(entity.getLocation().setPosition(position));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Optional.fromNullable(entity);
}

From source file:org.spongepowered.mod.mixin.world.MixinWorld.java

@Override
public Optional<Entity> createEntity(EntityType type, Vector3i position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");
    Entity entity = null;/*  w w w.j  av  a2 s.  com*/

    try {
        entity = ConstructorUtils.invokeConstructor(type.getEntityClass(), this);
        entity.setLocation(entity.getLocation().setPosition(position.toDouble()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Optional.fromNullable(entity);
}