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:com.thinkbiganalytics.metadata.modeshape.common.mixin.NodeEntityMixin.java

default <T> Set<T> getPropertyAsSet(String name, Class<T> objectType) {
    Object o = null;/*from  w  ww  .j a  va 2  s . c  om*/
    try {
        o = JcrPropertyUtil.getProperty(getNode(), name);
    } catch (UnknownPropertyException e) {

    }
    if (o != null) {
        if (o instanceof Collection) {
            //convert the objects to the correct type if needed
            if (JcrObject.class.isAssignableFrom(objectType)) {
                Set<T> objects = new HashSet<>();
                for (Object collectionObj : (Collection) o) {
                    T obj = null;
                    if (collectionObj instanceof Node) {

                        try {
                            obj = ConstructorUtils.invokeConstructor(objectType, (Node) collectionObj);
                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                                | InstantiationException e) {
                            obj = (T) collectionObj;
                        }

                    } else {
                        obj = (T) collectionObj;
                    }
                    objects.add(obj);
                }
                return objects;
            } else {
                return new HashSet<T>((Collection) o);
            }
        } else {
            Set<T> set = new HashSet<>();
            if (JcrObject.class.isAssignableFrom(objectType) && o instanceof Node) {
                T obj = null;
                try {
                    obj = ConstructorUtils.invokeConstructor(objectType, (Node) o);
                    set.add((T) obj);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                        | InstantiationException e) {

                }
                set.add(obj);
            } else {
                set.add((T) o);
            }
            return set;
        }
    }
    return new HashSet<T>();
}

From source file:gobblin.service.modules.orchestration.Orchestrator.java

public Orchestrator(Config config, Optional<TopologyCatalog> topologyCatalog, Optional<Logger> log,
        boolean instrumentationEnabled) {
    _log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    if (instrumentationEnabled) {
        this.metricContext = Instrumented.getMetricContext(ConfigUtils.configToState(config),
                IdentityFlowToJobSpecCompiler.class);
        this.flowOrchestrationSuccessFulMeter = Optional
                .of(this.metricContext.meter(ServiceMetricNames.FLOW_ORCHESTRATION_SUCCESSFUL_METER));
        this.flowOrchestrationFailedMeter = Optional
                .of(this.metricContext.meter(ServiceMetricNames.FLOW_ORCHESTRATION_FAILED_METER));
        this.flowOrchestrationTimer = Optional
                .<Timer>of(this.metricContext.timer(ServiceMetricNames.FLOW_ORCHESTRATION_TIMER));
    } else {//from  ww w  . ja v  a  2 s . c om
        this.metricContext = null;
        this.flowOrchestrationSuccessFulMeter = Optional.absent();
        this.flowOrchestrationFailedMeter = Optional.absent();
        this.flowOrchestrationTimer = Optional.absent();
    }

    this.aliasResolver = new ClassAliasResolver<>(SpecCompiler.class);
    this.topologyCatalog = topologyCatalog;
    try {
        String specCompilerClassName = ServiceConfigKeys.DEFAULT_GOBBLIN_SERVICE_FLOWCOMPILER_CLASS;
        if (config.hasPath(ServiceConfigKeys.GOBBLIN_SERVICE_FLOWCOMPILER_CLASS_KEY)) {
            specCompilerClassName = config.getString(ServiceConfigKeys.GOBBLIN_SERVICE_FLOWCOMPILER_CLASS_KEY);
        }
        _log.info("Using specCompiler class name/alias " + specCompilerClassName);

        this.specCompiler = (SpecCompiler) ConstructorUtils
                .invokeConstructor(Class.forName(this.aliasResolver.resolve(specCompilerClassName)), config);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.common.JcrObject.java

public <T> Set<T> getPropertyAsSet(String name, Class<T> objectType) {
    Object o = null;/*w  ww.j  ava  2 s .c  o m*/
    try {
        o = JcrPropertyUtil.getProperty(this.node, name);
    } catch (UnknownPropertyException | AccessControlException e) {

    }
    if (o != null) {
        if (o instanceof Collection) {
            //convert the objects to the correct type if needed
            if (JcrObject.class.isAssignableFrom(objectType)) {
                Set<T> objects = new HashSet<>();
                for (Object collectionObj : (Collection) o) {
                    T obj = null;
                    if (collectionObj instanceof Node) {

                        try {
                            obj = ConstructorUtils.invokeConstructor(objectType, (Node) collectionObj);
                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                                | InstantiationException e) {
                            obj = (T) collectionObj;
                        }

                    } else {
                        obj = (T) collectionObj;
                    }
                    objects.add(obj);
                }
                return objects;
            } else {
                return new HashSet<T>((Collection) o);
            }
        } else {
            Set<T> set = new HashSet<>();
            if (JcrObject.class.isAssignableFrom(objectType) && o instanceof Node) {
                T obj = null;
                try {
                    obj = ConstructorUtils.invokeConstructor(objectType, (Node) o);
                    set.add((T) obj);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                        | InstantiationException e) {

                }
                set.add(obj);
            } else {
                set.add((T) o);
            }
            return set;
        }
    } else {
        return new HashSet<T>();
    }
}

From source file:gobblin.source.extractor.extract.kafka.KafkaDeserializerExtractor.java

/**
 * Constructs a {@link KafkaSchemaRegistry} using the value of {@link #KAFKA_DESERIALIZER_TYPE}, if not set it
 * defaults to {@link SimpleKafkaSchemaRegistry}.
 *//*w w  w  .j a va  2  s  .c  o  m*/
private static KafkaSchemaRegistry<?, ?> getKafkaSchemaRegistry(Properties props)
        throws ReflectiveOperationException {

    Optional<Deserializers> deserializerType = Enums.getIfPresent(Deserializers.class,
            props.getProperty(KAFKA_DESERIALIZER_TYPE).toUpperCase());

    if (deserializerType.isPresent()) {
        return ConstructorUtils.invokeConstructor(deserializerType.get().getSchemaRegistryClass(), props);
    }
    if (props.containsKey(KafkaSchemaRegistry.KAFKA_SCHEMA_REGISTRY_CLASS)) {
        return KafkaSchemaRegistry.get(props);
    }
    return new SimpleKafkaSchemaRegistry(props);
}

From source file:me.j360.dubbo.modules.util.reflect.ReflectionUtil.java

/**
 * .//w  w w .ja  va  2  s.  c  o  m
 */
public static <T> T invokeConstructor(final Class<T> cls, Object... args) {
    try {
        return ConstructorUtils.invokeConstructor(cls, args);
    } catch (Exception e) {
        throw ExceptionUtil.uncheckedAndWrap(e);
    }
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustProperlySuspendWithSerialization() throws Exception {
    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(
            SERIALIZABLE_INVOKE_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(SERIALIZABLE_INVOKE_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, new StringBuilder());

        // Create and run original for a few cycles
        CoroutineRunner originalRunner = new CoroutineRunner(coroutine);

        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());

        // Serialize
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(originalRunner);
        oos.close();//from  ww w.  j a v a 2  s  .  c o m
        baos.close();
        byte[] serializedCoroutine = baos.toByteArray();

        // Deserialize
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedCoroutine);
        ObjectInputStream ois = new ObjectInputStream(bais) {

            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                try {
                    return super.resolveClass(desc);
                } catch (ClassNotFoundException cnfe) {
                    return classLoader.loadClass(desc.getName());
                }
            }

        };
        CoroutineRunner deserializedRunner = (CoroutineRunner) ois.readObject();

        // Continue running deserialized
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertFalse(deserializedRunner.execute()); // coroutine finished executing here
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());

        // Assert everything continued fine with deserialized version
        Object deserializedCoroutine = FieldUtils.readField(deserializedRunner, "coroutine", true);
        StringBuilder deserializedBuilder = (StringBuilder) FieldUtils.readField(deserializedCoroutine,
                "builder", true);

        Assert.assertEquals("started\n" + "0\n" + "1\n" + "2\n" + "3\n" + "4\n" + "5\n" + "6\n" + "7\n" + "8\n"
                + "9\n" + "started\n" + "0\n" + "1\n" + "2\n", deserializedBuilder.toString());
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.user.JcrUserGroup.java

private <C, J> Iterable<C> iterateReferances(String nodeType, Class<C> modelClass, Class<J> jcrClass) {
    return () -> {
        @SuppressWarnings("unchecked")
        Iterable<Property> propItr = () -> {
            try {
                return (Iterator<Property>) this.node.getWeakReferences();
            } catch (Exception e) {
                throw new MetadataRepositoryException(
                        "Failed to retrieve the users in the group node: " + this.node, e);
            }/*from w ww.ja  v  a 2 s  .  co m*/
        };

        return StreamSupport.stream(propItr.spliterator(), false).map(p -> JcrPropertyUtil.getParent(p))
                .filter(n -> JcrUtil.isNodeType(n, nodeType)).map(n -> {
                    try {
                        @SuppressWarnings("unchecked")
                        C entity = (C) ConstructorUtils.invokeConstructor(jcrClass, n);
                        return entity;
                    } catch (Exception e) {
                        throw new MetadataRepositoryException("Failed to retrieve create entity: " + jcrClass,
                                e);
                    }
                }).iterator();
    };
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.ProblemBuilder.java

/**
 * Returns a new instance of the problem used by this builder, or throws
 * an exception if no problem has been defined.  The code requesting the
 * problem instance is expected to close the problem when finished.
 * //w w w  .  ja  v  a 2  s.  co  m
 * @return a new instance of the problem used by this builder, or throws
 *         an exception if no problem has been defined
 * @throws IllegalArgumentException if no problem has been defined
 * @throws FrameworkException if an error occurred invoking the constructor
 *         caused by an {@link InstantiationException}, 
 *         {@link IllegalAccessException}, 
 *         {@link InvocationTargetException} or
 *         {@link NoSuchMethodException}.
 */
Problem getProblemInstance() {
    if ((problemName == null) && (problemClass == null)) {
        throw new IllegalArgumentException("no problem specified");
    }

    if (problemClass != null) {
        try {
            return (Problem) ConstructorUtils.invokeConstructor(problemClass, problemArguments);
        } catch (InstantiationException e) {
            throw new FrameworkException(e);
        } catch (IllegalAccessException e) {
            throw new FrameworkException(e);
        } catch (InvocationTargetException e) {
            throw new FrameworkException(e);
        } catch (NoSuchMethodException e) {
            throw new FrameworkException(e);
        }
    } else if (problemFactory == null) {
        return ProblemFactory.getInstance().getProblem(problemName);
    } else {
        return problemFactory.getProblem(problemName);
    }
}

From source file:gobblin.service.modules.core.GobblinServiceManager.java

public GobblinServiceManager(String serviceName, String serviceId, Config config,
        Optional<Path> serviceWorkDirOptional) throws Exception {

    // Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes
    Properties properties = ConfigUtils.configToProperties(config);
    if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) {
        properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300));
    }/*from   w  w  w.j  ava  2 s .co  m*/
    this.config = config;

    this.serviceId = serviceId;
    this.serviceLauncher = new ServiceBasedAppLauncher(properties, serviceName);

    this.fs = buildFileSystem(config);
    this.serviceWorkDir = serviceWorkDirOptional.isPresent() ? serviceWorkDirOptional.get()
            : getServiceWorkDirPath(this.fs, serviceName, serviceId);

    // Initialize TopologyCatalog
    this.isTopologyCatalogEnabled = ConfigUtils.getBoolean(config,
            ServiceConfigKeys.GOBBLIN_SERVICE_TOPOLOGY_CATALOG_ENABLED_KEY, true);
    if (isTopologyCatalogEnabled) {
        this.topologyCatalog = new TopologyCatalog(config, Optional.of(LOGGER));
        this.serviceLauncher.addService(topologyCatalog);
    }

    // Initialize FlowCatalog
    this.isFlowCatalogEnabled = ConfigUtils.getBoolean(config,
            ServiceConfigKeys.GOBBLIN_SERVICE_FLOW_CATALOG_ENABLED_KEY, true);
    if (isFlowCatalogEnabled) {
        this.flowCatalog = new FlowCatalog(config, Optional.of(LOGGER));
        this.serviceLauncher.addService(flowCatalog);
    }

    // Initialize Helix
    Optional<String> zkConnectionString = Optional
            .fromNullable(ConfigUtils.getString(config, ServiceConfigKeys.ZK_CONNECTION_STRING_KEY, null));
    if (zkConnectionString.isPresent()) {
        LOGGER.info("Using ZooKeeper connection string: " + zkConnectionString);
        // This will create and register a Helix controller in ZooKeeper
        this.helixManager = Optional.fromNullable(buildHelixManager(config, zkConnectionString.get()));
    } else {
        LOGGER.info("No ZooKeeper connection string. Running in single instance mode.");
        this.helixManager = Optional.absent();
    }

    // Initialize ServiceScheduler
    this.isSchedulerEnabled = ConfigUtils.getBoolean(config,
            ServiceConfigKeys.GOBBLIN_SERVICE_SCHEDULER_ENABLED_KEY, true);
    if (isSchedulerEnabled) {
        this.orchestrator = new Orchestrator(config, Optional.of(this.topologyCatalog), Optional.of(LOGGER));
        SchedulerService schedulerService = new SchedulerService(properties);
        this.scheduler = new GobblinServiceJobScheduler(config, this.helixManager,
                Optional.of(this.flowCatalog), Optional.of(this.topologyCatalog), this.orchestrator,
                schedulerService, Optional.of(LOGGER));
    }

    // Initialize RestLI
    this.isRestLIServerEnabled = ConfigUtils.getBoolean(config,
            ServiceConfigKeys.GOBBLIN_SERVICE_RESTLI_SERVER_ENABLED_KEY, true);
    if (isRestLIServerEnabled) {
        Injector injector = Guice.createInjector(new Module() {
            @Override
            public void configure(Binder binder) {
                binder.bind(FlowCatalog.class).annotatedWith(Names.named("flowCatalog"))
                        .toInstance(flowCatalog);
                binder.bindConstant().annotatedWith(Names.named("readyToUse")).to(Boolean.TRUE);
            }
        });
        this.restliServer = EmbeddedRestliServer.builder()
                .resources(Lists.<Class<? extends BaseResource>>newArrayList(FlowConfigsResource.class))
                .injector(injector).build();
        this.serviceLauncher.addService(restliServer);
    }

    // Register Scheduler to listen to changes in Flows
    if (isSchedulerEnabled) {
        this.flowCatalog.addListener(this.scheduler);
        this.topologyCatalog.addListener(this.orchestrator);
    }

    // Initialize TopologySpecFactory
    this.isTopologySpecFactoryEnabled = ConfigUtils.getBoolean(config,
            ServiceConfigKeys.GOBBLIN_SERVICE_TOPOLOGY_SPEC_FACTORY_ENABLED_KEY, true);
    if (this.isTopologySpecFactoryEnabled) {
        this.aliasResolver = new ClassAliasResolver<>(TopologySpecFactory.class);
        String topologySpecFactoryClass = ServiceConfigKeys.DEFAULT_TOPOLOGY_SPEC_FACTORY;
        if (config.hasPath(ServiceConfigKeys.TOPOLOGYSPEC_FACTORY_KEY)) {
            topologySpecFactoryClass = config.getString(ServiceConfigKeys.TOPOLOGYSPEC_FACTORY_KEY);
        }

        try {
            LOGGER.info("Using TopologySpecFactory class name/alias " + topologySpecFactoryClass);
            this.topologySpecFactory = (TopologySpecFactory) ConstructorUtils.invokeConstructor(
                    Class.forName(this.aliasResolver.resolve(topologySpecFactoryClass)), config);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustProperlySuspendWithUninitializedLocalVariables() throws Exception {
    StringBuilder builder = new StringBuilder();

    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(
            UNINITIALIZED_VARIABLE_INVOKE_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(UNINITIALIZED_VARIABLE_INVOKE_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, builder);

        CoroutineRunner runner = new CoroutineRunner(coroutine);

        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
    }//from  w  ww  .  ja  v  a  2 s. c  om
}