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, Class<?>[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
        InstantiationException 

Source Link

Document

Returns a new instance of the specified class choosing the right constructor from the list of parameter types.

This locates and calls a constructor.

Usage

From source file:gobblin.data.management.copy.replication.ReplicationDataValidPathPicker.java

@SuppressWarnings("unchecked")
public static Collection<Path> getValidPaths(HadoopFsEndPoint hadoopFsEndPoint) throws IOException {
    Config selectionConfig = hadoopFsEndPoint.getSelectionConfig();

    FileSystemDataset tmpDataset = new HadoopFsEndPointDataset(hadoopFsEndPoint);
    FileSystem theFs = FileSystem.get(hadoopFsEndPoint.getFsURI(), new Configuration());

    /**//from   ww w .j  av  a 2 s  . c o m
     * Use {@link FileSystemDatasetVersion} as
     * {@link DateTimeDatasetVersionFinder} / {@link GlobModTimeDatasetVersionFinder} use {@link TimestampedDatasetVersion}
     * {@link SingleVersionFinder} uses {@link FileStatusDatasetVersion}
     */
    VersionFinder<FileSystemDatasetVersion> finder;
    try {
        finder = (VersionFinder<FileSystemDatasetVersion>) ConstructorUtils.invokeConstructor(
                Class.forName(selectionConfig.getString(FINDER_CLASS)), theFs, selectionConfig);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    }

    List<FileSystemDatasetVersion> versions = Ordering.natural().reverse()
            .sortedCopy(finder.findDatasetVersions(tmpDataset));

    VersionSelectionPolicy<FileSystemDatasetVersion> selector;
    try {
        selector = (VersionSelectionPolicy<FileSystemDatasetVersion>) ConstructorUtils
                .invokeConstructor(Class.forName(selectionConfig.getString(POLICY_CLASS)), selectionConfig);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    }

    Collection<FileSystemDatasetVersion> versionsSelected = selector.listSelectedVersions(versions);

    List<Path> result = new ArrayList<Path>();
    for (FileSystemDatasetVersion t : versionsSelected) {
        // get the first element out
        result.add(t.getPaths().iterator().next());
    }
    return result;
}

From source file:com.uber.hoodie.utilities.UtilHelpers.java

public static HoodieRecordPayload createPayload(String payloadClass, GenericRecord record,
        Comparable orderingVal) throws IOException {
    try {/*from w  w w .j a va 2 s.  c  om*/
        return (HoodieRecordPayload) ConstructorUtils.invokeConstructor(Class.forName(payloadClass),
                (Object) record, (Object) orderingVal);
    } catch (Throwable e) {
        throw new IOException("Could not create payload for class: " + payloadClass, e);
    }
}

From source file:com.uber.hoodie.DataSourceUtils.java

/**
 * Create a payload class via reflection, passing in an ordering/precombine value.
 *//*w  w w.j  a v  a2 s.  co  m*/
public static HoodieRecordPayload createPayload(String payloadClass, GenericRecord record,
        Comparable orderingVal) throws IOException {
    try {
        return (HoodieRecordPayload) ConstructorUtils.invokeConstructor(Class.forName(payloadClass),
                (Object) record, (Object) orderingVal);
    } catch (Throwable e) {
        throw new IOException("Could not create payload for class: " + payloadClass, e);
    }
}

From source file:gobblin.audit.values.sink.DefaultAuditSinkFactory.java

/**
 * Create a new {@link AuditSink} using the alias or cannonical classname specified at {@value #AUDIT_SINK_CLASS_NAME_KEY} in the <code>config</code>
 * The {@link AuditSink} class MUST have an accessible constructor <code>abc(Config config, TableMetadata tableMetadata)</code>
 * <br>//from ww w . j  ava 2s.  c  o  m
 * If {@value #AUDIT_SINK_CLASS_NAME_KEY} is not set in <code>config</code>, a default {@link #DEFAULT_AUDIT_SINK_CLASS} is used
 *
 * @param config job configs
 * @param auditRuntimeMetadata runtime table metadata
 *
 * @return a new instance of {@link AuditSink}
 */
public AuditSink create(Config config, ValueAuditRuntimeMetadata auditRuntimeMetadata) {

    String sinkClassName = DEFAULT_AUDIT_SINK_CLASS;
    if (config.hasPath(AUDIT_SINK_CLASS_NAME_KEY)) {
        sinkClassName = config.getString(AUDIT_SINK_CLASS_NAME_KEY);
    }
    log.info("Using audit sink class name/alias " + sinkClassName);

    try {
        return (AuditSink) ConstructorUtils.invokeConstructor(
                Class.forName(this.aliasResolver.resolve(sinkClassName)), config, auditRuntimeMetadata);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:hoot.services.models.osm.ElementFactory.java

/**
 * Creates an element/* ww  w  . j  a  v  a2 s  .  c  o  m*/
 *
 * @param elementType the type of element to create
 * @param conn JDBC Connection
 * @return an element
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
public Element create(final long mapId, final ElementType elementType, Connection conn)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException {
    Long oMapId = new Long(mapId);
    return (Element) ConstructorUtils.invokeConstructor(
            Class.forName(ClassUtils.getPackageName(ElementFactory.class) + "." + elementType.toString()),
            new Object[] { oMapId, conn }, new Class<?>[] { Long.class, Connection.class });
}

From source file:gobblin.audit.values.policy.column.DefaultColumnProjectionPolicyFactory.java

/**
 * Create a new {@link ColumnProjectionPolicy} using the alias or cannonical classname specified at {@value #COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY} in the <code>config</code>
 * The {@link ColumnProjectionPolicy} class MUST have an accessible constructor <code>abc(Config config, TableMetadata tableMetadata)</code>
 * <b>Note : Must have the key {@value #COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY} set in <code>config</code> to create the {@link ColumnProjectionPolicy}</b>
 *
 * @param config job configs, Must have the key {@value #COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY} set to create the {@link ColumnProjectionPolicy}
 * @param tableMetadata runtime table metadata
 *
 * @return a new instance of {@link ColumnProjectionPolicy}
 *///from w  w  w .  j  a va 2s  .  c  o  m
public ColumnProjectionPolicy create(Config config, ValueAuditRuntimeMetadata.TableMetadata tableMetadata) {

    Preconditions.checkArgument(config.hasPath(COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY));

    log.info("Using column projection class name/alias "
            + config.getString(COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY));

    try {
        return (ColumnProjectionPolicy) ConstructorUtils.invokeConstructor(
                Class.forName(
                        this.aliasResolver.resolve(config.getString(COLUMN_PROJECTION_POLICY_CLASS_NAME_KEY))),
                config, tableMetadata);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thinkbiganalytics.metadata.core.dataset.InMemoryDatasourceProvider.java

@Override
public <D extends Datasource> D ensureDatasource(String name, String descr, Class<D> type) {
    synchronized (this.datasets) {
        try {//from   w  w  w  . j ava 2s . co  m
            D ds = null;
            BaseDatasource existing = getExistingDataset(name);

            if (existing == null) {
                ds = (D) ConstructorUtils.invokeConstructor(type, name, descr);
                this.datasets.put(ds.getId(), ds);
            } else if (type.isInstance(ds)) {
                ds = (D) existing;
            } else {
                throw new MetadataException("A datasource already exists of type: " + ds.getClass()
                        + " but expected one of type: " + type);
            }

            return ds;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException e) {
            throw new MetadataException("Failed to create a datasource to type: " + type, e);
        }
    }
}

From source file:gobblin.data.management.retention.profile.MultiDatasetFinder.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public MultiDatasetFinder(FileSystem fs, Properties jobProps) {
    this.jobProps = jobProps;
    try {/*from w w  w  .  j a v a  2s. c o m*/
        this.datasetFinders = Lists.newArrayList();

        if (jobProps.containsKey(datasetFinderClassKey())) {
            try {
                log.info(String.format("Instantiating datasetfinder %s ",
                        jobProps.getProperty(datasetFinderClassKey())));
                this.datasetFinders.add((DatasetsFinder) ConstructorUtils.invokeConstructor(
                        Class.forName(jobProps.getProperty(datasetFinderClassKey())), fs, jobProps));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                    | InstantiationException | ClassNotFoundException e) {
                log.error(String.format("Retention ignored could not instantiate datasetfinder %s.",
                        jobProps.getProperty(datasetFinderClassKey())), e);
                Throwables.propagate(e);
            }
        } else if (jobProps.containsKey(datasetFinderImportedByKey())) {

            log.info("Instatiating dataset finders using tag "
                    + jobProps.getProperty(datasetFinderImportedByKey()));

            ConfigClient client = ConfigClientCache.getClient(VersionStabilityPolicy.STRONG_LOCAL_STABILITY);
            Collection<URI> importedBys = Lists.newArrayList();

            for (String tag : TAGS_SPLITTER.split(jobProps.getProperty(datasetFinderImportedByKey()))) {
                log.info("Looking for datasets that import tag " + tag);
                importedBys.addAll(client.getImportedBy(new URI(tag), false));
            }

            for (URI importedBy : importedBys) {
                Config datasetClassConfig = client.getConfig(importedBy);

                try {
                    this.datasetFinders.add((DatasetsFinder) GobblinConstructorUtils.invokeFirstConstructor(
                            Class.forName(datasetClassConfig.getString(datasetFinderClassKey())),
                            ImmutableList.of(fs, jobProps, datasetClassConfig),
                            ImmutableList.of(fs, jobProps)));
                    log.info(String.format("Instantiated datasetfinder %s for %s.",
                            datasetClassConfig.getString(datasetFinderClassKey()), importedBy));
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException | NoSuchMethodException | SecurityException
                        | ClassNotFoundException e) {
                    log.error(String.format("Retention ignored for %s. Could not instantiate datasetfinder %s.",
                            importedBy, datasetClassConfig.getString(datasetFinderClassKey())), e);
                    Throwables.propagate(e);
                }
            }
        } else {
            log.warn(String.format(
                    "NO DATASET_FINDERS FOUND. Either specify dataset finder class at %s or specify the imported tags at %s",
                    datasetFinderClassKey(), datasetFinderImportedByKey()));
        }

    } catch (IllegalArgumentException | VersionDoesNotExistException | ConfigStoreFactoryDoesNotExistsException
            | ConfigStoreCreationException | URISyntaxException e) {
        Throwables.propagate(e);
    }
}

From source file:hoot.services.models.osm.ElementFactory.java

/**
 * Creates an element from a new element record
 *
 * @param elementType the type of element to create
 * @param record record to associate with the element
 * @param conn JDBC Connection/*  ww w  .  j  a  v a  2  s.  co  m*/
 * @return an element
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws NoSuchMethodException
 */
public Element create(final ElementType elementType, final Object record, Connection conn, final long mapId)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException,
        ClassNotFoundException, Exception {
    Object oRec = record;
    Object oElem = oRec;
    if (oRec instanceof Tuple) {
        // This was forced since we are using reflection which need to be refactored to something more solid.

        Tuple tRec = (Tuple) oRec;
        Object[] tRecs = tRec.toArray();
        if (tRecs.length > 0) {
            // assume first record is good.
            oElem = tRecs[0];
        } else {
            throw new Exception(
                    "Bad Record type. Tuple is empty. Please make sure the first object is tuple is DTO that supports setVersion.");
        }
    }
    Long oMapId = new Long(mapId);
    String className = ClassUtils.getPackageName(ElementFactory.class) + "." + elementType.toString();
    return (Element) ConstructorUtils.invokeConstructor(
            Class.forName(ClassUtils.getPackageName(ElementFactory.class) + "." + elementType.toString()),
            new Object[] { oMapId, conn, oElem },
            new Class<?>[] { Long.class, Connection.class, oElem.getClass() });
}

From source file:gobblin.runtime.spec_catalog.FlowCatalog.java

public FlowCatalog(Config config, Optional<Logger> log, Optional<MetricContext> parentMetricContext,
        boolean instrumentationEnabled) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    this.listeners = new SpecCatalogListenersList(log);
    if (instrumentationEnabled) {
        MetricContext realParentCtx = parentMetricContext
                .or(Instrumented.getMetricContext(new gobblin.configuration.State(), getClass()));
        this.metricContext = realParentCtx.childBuilder(FlowCatalog.class.getSimpleName()).build();
        this.metrics = new StandardMetrics(this);
    } else {//from   w  ww  . j  a  v a  2s.  co m
        this.metricContext = null;
        this.metrics = null;
    }

    this.aliasResolver = new ClassAliasResolver<>(SpecStore.class);
    try {
        Config newConfig = config;
        if (config.hasPath(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY)) {
            newConfig = config.withValue(ConfigurationKeys.SPECSTORE_FS_DIR_KEY,
                    config.getValue(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY));
        }
        String specStoreClassName = DEFAULT_FLOWSPEC_STORE_CLASS;
        if (config.hasPath(ConfigurationKeys.FLOWSPEC_STORE_CLASS_KEY)) {
            specStoreClassName = config.getString(ConfigurationKeys.FLOWSPEC_STORE_CLASS_KEY);
        }
        this.log.info("Using audit sink class name/alias " + specStoreClassName);
        this.specStore = (SpecStore) ConstructorUtils.invokeConstructor(
                Class.forName(this.aliasResolver.resolve(specStoreClassName)), newConfig, this);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}