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.sla.alerts.ServiceLevelAgreementActionUtil.java

public static ServiceLevelAgreementAction instantiate(Class<? extends ServiceLevelAgreementAction> clazz) {
    ServiceLevelAgreementAction action = null;
    try {//from   w  w  w.  j  ava  2s .c  om
        action = SpringApplicationContext.getBean(clazz);
    } catch (NoSuchBeanDefinitionException e) {
        //this is ok
    }

    //if not spring bound then construct the Responder
    if (action == null) {
        //construct and invoke
        try {
            action = ConstructorUtils.invokeConstructor(clazz, null);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException e) {
            //TODO LOG error
            e.printStackTrace();
        }
    }
    return action;
}

From source file:gobblin.hive.HiveSerDeManager.java

/**
 * Get an instance of {@link HiveSerDeManager}.
 *
 * @param type The {@link HiveSerDeManager} type. It should be either AVRO, or the name of a class that implements
 * {@link HiveSerDeManager}. The specified {@link HiveSerDeManager} type must have a constructor that takes a
 * {@link State} object.//from ww w  . j a v  a  2 s .  c  o  m
 * @param props A {@link State} object. To get a specific implementation of {@link HiveSerDeManager}, specify either
 * one of the values in {@link Implementation} (e.g., AVRO) or the name of a class that implements
 * {@link HiveSerDeManager} in property {@link #HIVE_ROW_FORMAT}. The {@link State} object is also used to
 * instantiate the {@link HiveSerDeManager}.
 */
public static HiveSerDeManager get(State props) {
    String type = props.getProp(HIVE_ROW_FORMAT, Implementation.AVRO.name());
    Optional<Implementation> implementation = Enums.getIfPresent(Implementation.class, type.toUpperCase());

    try {
        if (implementation.isPresent()) {
            return (HiveSerDeManager) ConstructorUtils
                    .invokeConstructor(Class.forName(implementation.get().toString()), props);
        }
        return (HiveSerDeManager) ConstructorUtils.invokeConstructor(Class.forName(type), props);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(
                "Unable to instantiate " + HiveSerDeManager.class.getSimpleName() + " with type " + type, e);
    }
}

From source file:gobblin.cluster.ScheduledJobConfigurationManager.java

public ScheduledJobConfigurationManager(EventBus eventBus, Config config) {
    super(eventBus, config);

    this.jobSpecs = Maps.newHashMap();
    this.refreshIntervalInSeconds = ConfigUtils.getLong(config,
            GobblinClusterConfigurationKeys.JOB_SPEC_REFRESH_INTERVAL, DEFAULT_JOB_SPEC_REFRESH_INTERVAL);

    this.fetchJobSpecExecutor = Executors.newSingleThreadScheduledExecutor(
            ExecutorsUtils.newThreadFactory(Optional.of(LOGGER), Optional.of("FetchJobSpecExecutor")));

    this.aliasResolver = new ClassAliasResolver<>(SpecExecutorInstanceConsumer.class);
    try {//from  w  ww.j  a va  2  s . c o m
        String specExecutorInstanceConsumerClassName = GobblinClusterConfigurationKeys.DEFAULT_SPEC_EXECUTOR_INSTANCE_CONSUMER_CLASS;
        if (config.hasPath(GobblinClusterConfigurationKeys.SPEC_EXECUTOR_INSTANCE_CONSUMER_CLASS_KEY)) {
            specExecutorInstanceConsumerClassName = config
                    .getString(GobblinClusterConfigurationKeys.SPEC_EXECUTOR_INSTANCE_CONSUMER_CLASS_KEY);
        }
        LOGGER.info("Using SpecExecutorInstanceConsumer ClassNameclass name/alias "
                + specExecutorInstanceConsumerClassName);
        this.specExecutorInstanceConsumer = (SpecExecutorInstanceConsumer) ConstructorUtils.invokeConstructor(
                Class.forName(this.aliasResolver.resolve(specExecutorInstanceConsumerClassName)), config);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:gobblin.data.management.policy.CombineSelectionPolicy.java

@SuppressWarnings("unchecked")
public CombineSelectionPolicy(Properties props) throws IOException {

    Preconditions.checkArgument(props.containsKey(VERSION_SELECTION_POLICIES_PREFIX),
            "Combine operation not specified.");

    ImmutableList.Builder<VersionSelectionPolicy<FileSystemDatasetVersion>> builder = ImmutableList.builder();

    for (String property : props.stringPropertyNames()) {
        if (property.startsWith(VERSION_SELECTION_POLICIES_PREFIX)) {

            try {
                builder.add((VersionSelectionPolicy<FileSystemDatasetVersion>) ConstructorUtils
                        .invokeConstructor(Class.forName(props.getProperty(property)), props));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                    | InstantiationException | ClassNotFoundException e) {
                throw new IllegalArgumentException(e);
            }/*from  w w  w .  jav a 2 s. co m*/
        }
    }

    this.selectionPolicies = builder.build();
    if (this.selectionPolicies.size() == 0) {
        throw new IOException(
                "No selection policies specified for " + CombineSelectionPolicy.class.getCanonicalName());
    }

    this.combineOperation = CombineOperation
            .valueOf(props.getProperty(VERSION_SELECTION_COMBINE_OPERATION).toUpperCase());

}

From source file:gobblin.source.extractor.filebased.FileBasedExtractor.java

@SuppressWarnings("unchecked")
public FileBasedExtractor(WorkUnitState workUnitState, FileBasedHelper fsHelper) {
    super(workUnitState);
    this.workUnitState = workUnitState;
    this.workUnit = workUnitState.getWorkunit();
    this.filesToPull = Lists
            .newArrayList(workUnitState.getPropAsList(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL, ""));
    this.statusCount = this.workUnit.getPropAsInt(ConfigurationKeys.FILEBASED_REPORT_STATUS_ON_COUNT,
            ConfigurationKeys.DEFAULT_FILEBASED_REPORT_STATUS_ON_COUNT);
    this.shouldSkipFirstRecord = this.workUnitState.getPropAsBoolean(ConfigurationKeys.SOURCE_SKIP_FIRST_RECORD,
            false);//from  w  ww. j  a va  2  s . c o m

    if (fsHelper instanceof SizeAwareFileBasedHelper) {
        this.fsHelper = (SizeAwareFileBasedHelper) fsHelper;
    } else {
        this.fsHelper = new SizeAwareFileBasedHelperDecorator(fsHelper);
    }

    try {
        this.fsHelper.connect();
    } catch (FileBasedHelperException e) {
        throw new RuntimeException(e);
    }

    if (workUnitState.contains(ConfigurationKeys.SOURCE_FILEBASED_OPTIONAL_DOWNLOADER_CLASS)) {
        try {
            this.fileDownloader = (FileDownloader<D>) ConstructorUtils.invokeConstructor(Class.forName(
                    workUnitState.getProp(ConfigurationKeys.SOURCE_FILEBASED_OPTIONAL_DOWNLOADER_CLASS)), this);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        this.fileDownloader = new SingleFileDownloader<>(this);
    }

    this.counters.initialize(getMetricContext(), CounterNames.class, this.getClass());
}

From source file:com.joyent.manta.serialization.EncryptedMultipartManagerSerializationTest.java

private EncryptedMultipartUpload<?> newUploadInstance(final Object... params) {
    try {/*from ww  w  .  j  ava2s  . c om*/
        return ConstructorUtils.invokeConstructor(EncryptedMultipartUpload.class, params);
    } catch (ReflectiveOperationException e) {
        throw new AssertionError(e);
    }
}

From source file:gobblin.runtime.api.TopologySpec.java

public SpecExecutorInstanceProducer getSpecExecutorInstanceProducer() {
    if (null == specExecutorInstanceProducer) {
        String specExecutorInstanceProducerClass = DEFAULT_SPEC_EXECUTOR_INSTANCE_PRODUCER;
        if (config.hasPath(SPEC_EXECUTOR_INSTANCE_PRODUCER_KEY)) {
            specExecutorInstanceProducerClass = config.getString(SPEC_EXECUTOR_INSTANCE_PRODUCER_KEY);
        }/* ww  w.j a v a  2 s  . co  m*/
        try {
            ClassAliasResolver<SpecExecutorInstanceProducer> _aliasResolver = new ClassAliasResolver<>(
                    SpecExecutorInstanceProducer.class);
            specExecutorInstanceProducer = (SpecExecutorInstanceProducer) ConstructorUtils.invokeConstructor(
                    Class.forName(_aliasResolver.resolve(specExecutorInstanceProducerClass)), config);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    return specExecutorInstanceProducer;
}

From source file:gobblin.service.modules.topology.ConfigBasedTopologySpecFactory.java

@Override
public Collection<TopologySpec> getTopologies() {

    if (!_config.hasPath(ServiceConfigKeys.TOPOLOGY_FACTORY_TOPOLOGY_NAMES_KEY)) {
        return Collections.EMPTY_LIST;
    }/*from  ww w .j  ava  2 s  .co  m*/
    Collection<TopologySpec> topologySpecs = Lists.newArrayList();
    Collection<String> topologyNames = SPLIT_BY_COMMA
            .splitToList(_config.getString(ServiceConfigKeys.TOPOLOGY_FACTORY_TOPOLOGY_NAMES_KEY));

    for (String topologyName : topologyNames) {
        Preconditions.checkArgument(_config.hasPath(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + topologyName),
                "Config does not contain Topology Factory descriptor for Topology" + topologyName);
        Config topologyConfig = _config.getConfig(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + topologyName);
        String description = ConfigUtils.getString(topologyConfig,
                ServiceConfigKeys.TOPOLOGYSPEC_DESCRIPTION_KEY, "NA");
        String version = ConfigUtils.getString(topologyConfig, ServiceConfigKeys.TOPOLOGYSPEC_VERSION_KEY,
                "-1");

        String specExecutorInstanceProducerClass = ServiceConfigKeys.DEFAULT_SPEC_EXECUTOR_INSTANCE_PRODUCER;
        if (topologyConfig.hasPath(ServiceConfigKeys.SPEC_EXECUTOR_INSTANCE_PRODUCER_KEY)) {
            specExecutorInstanceProducerClass = topologyConfig
                    .getString(ServiceConfigKeys.SPEC_EXECUTOR_INSTANCE_PRODUCER_KEY);
        }
        SpecExecutorInstanceProducer specExecutorInstanceProducer;
        try {
            _log.info(
                    "Using SpecExecutorInstanceProducer class name/alias " + specExecutorInstanceProducerClass);
            specExecutorInstanceProducer = (SpecExecutorInstanceProducer) ConstructorUtils.invokeConstructor(
                    Class.forName(_aliasResolver.resolve(specExecutorInstanceProducerClass)), topologyConfig);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        TopologySpec.Builder topologySpecBuilder = TopologySpec
                .builder(topologyConfig.getString(ServiceConfigKeys.TOPOLOGYSPEC_URI_KEY))
                .withConfig(topologyConfig).withDescription(description).withVersion(version)
                .withSpecExecutorInstanceProducer(specExecutorInstanceProducer);
        topologySpecs.add(topologySpecBuilder.build());
    }

    return topologySpecs;
}

From source file:gobblin.util.reflection.GobblinConstructorUtils.java

/**
 * Utility method to create an instance of <code>clsName</code> using the constructor matching the arguments, <code>args</code>
 *
 * @param superType of <code>clsName</code>. The new instance is cast to superType
 * @param clsName complete cannonical name of the class to be instantiated
 * @param args constructor args to be used
 *
 * @throws IllegalArgumentException if there was an issue creating the instance due to
 * {@link NoSuchMethodException}, {@link InvocationTargetException},{@link InstantiationException},
 *  {@link ClassNotFoundException}// w w w  .  jav a 2  s . com
 *
 * @return A new instance of <code>clsName</code>
 */
@SuppressWarnings("unchecked")
public static <T> T invokeConstructor(final Class<T> superType, final String clsName, Object... args) {

    try {
        return (T) ConstructorUtils.invokeConstructor(Class.forName(clsName), args);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:gobblin.data.management.retention.policy.CombineRetentionPolicy.java

@SuppressWarnings("unchecked")
public CombineRetentionPolicy(Properties props) throws IOException {

    Preconditions.checkArgument(props.containsKey(DELETE_SETS_COMBINE_OPERATION),
            "Combine operation not specified.");

    ImmutableList.Builder<RetentionPolicy<T>> builder = ImmutableList.builder();

    for (String property : props.stringPropertyNames()) {
        if (property.startsWith(RETENTION_POLICIES_PREFIX)) {

            try {
                builder.add((RetentionPolicy<T>) ConstructorUtils
                        .invokeConstructor(Class.forName(props.getProperty(property)), props));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                    | InstantiationException | ClassNotFoundException e) {
                throw new IllegalArgumentException(e);
            }//  ww  w.jav  a 2 s  .c  o m
        }
    }

    this.retentionPolicies = builder.build();
    if (this.retentionPolicies.size() == 0) {
        throw new IOException(
                "No retention policies specified for " + CombineRetentionPolicy.class.getCanonicalName());
    }

    this.combineOperation = DeletableCombineOperation
            .valueOf(props.getProperty(DELETE_SETS_COMBINE_OPERATION).toUpperCase());

}