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

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

Introduction

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

Prototype

public static Object invokeConstructor(Class cls, Object[] args) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException 

Source Link

Document

Returns new instance of klazz created using the actual arguments args.

Usage

From source file:com.cloudera.impala.authorization.AuthorizationChecker.java

private static ResourceAuthorizationProvider createProvider(AuthorizationConfig config,
        AuthorizationPolicy policy) {//from   w ww . j  ava2 s .co m
    try {
        // Try to create an instance of the specified policy provider class.
        // Re-throw any exceptions that are encountered.
        return (ResourceAuthorizationProvider) ConstructorUtils.invokeConstructor(
                Class.forName(config.getPolicyProviderClassName()),
                new Object[] { config.getPolicyFile(), config.getServerName() });
    } catch (Exception e) {
        // Re-throw as unchecked exception.
        throw new IllegalStateException("Error creating ResourceAuthorizationProvider: " + e.getMessage(), e);
    }
}

From source file:com.tobedevoured.modelcitizen.template.JavaBeanTemplate.java

@SuppressWarnings("unchecked")
public <T> T construct(Class<T> modelClass) throws BlueprintTemplateException {
    try {//from  w ww. j  a  v a  2s .  c  o  m
        return (T) ConstructorUtils.invokeConstructor(modelClass, null);
    } catch (NoSuchMethodException e) {
        throw new BlueprintTemplateException(e);
    } catch (IllegalAccessException e) {
        throw new BlueprintTemplateException(e);
    } catch (InvocationTargetException e) {
        throw new BlueprintTemplateException(e);
    } catch (InstantiationException e) {
        throw new BlueprintTemplateException(e);
    }
}

From source file:com.yahoo.flowetl.core.util.KlassUtils.java

/**
 * Gets the instance of a class by calling the constructor with the given
 * object arguments.//from  w w w  . j  a  v a 2s  .c  o  m
 * 
 * @param <T>
 *            the generic type to construct
 * @param klass
 *            the class to attempt to construct
 * 
 * @param constructorArgs
 *            the constructor args to provide to that class
 * 
 * @return an instance of that object
 * 
 * @throws ConstructException
 *             a exception if that class can not be constructed
 */
@SuppressWarnings("unchecked")
public static <T> T getInstanceOf(Class<T> klass, Object[] constructorArgs) {
    try {
        return (T) ConstructorUtils.invokeConstructor(klass, constructorArgs);
    } catch (Exception e) {
        throw new RuntimeException("Unable to construct class " + klass, e);
    }
}

From source file:com.jroossien.boxx.nms.NMS.java

public <T> Object loadFromNMS(Class<T> dep, Object... objects) {
    if (!dep.isAnnotationPresent(NMSDependant.class))
        return null;
    NMSDependant nmsDependant = dep.getAnnotation(NMSDependant.class);
    Class<?> impl = null;//w w w. jav  a 2  s.  c  o  m
    try {
        impl = Class.forName(nmsDependant.implementationPath() + "." + dep.getSimpleName() + "_" + version);
        return ConstructorUtils.invokeConstructor(impl, objects);
    } catch (ClassNotFoundException e) {
        Boxx.get().error("The current version is not supported: " + version + ".\n" + e.getMessage());
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
            | InvocationTargetException e) {
        e.printStackTrace();
    }
    return impl;
}

From source file:net.audumla.scheduler.camel.SchedulerComponent.java

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {
    // Get couple of scheduler settings
    Integer startDelayedSeconds = getAndRemoveParameter(parameters, "startDelayedSeconds", Integer.class);
    if (startDelayedSeconds != null) {
        if (getStartDelayedSeconds() != 0 && !(getStartDelayedSeconds() == startDelayedSeconds)) {
            logger.warn(/*  ww  w .j  av  a 2 s  .  c o  m*/
                    "A Quartz job is already configured with a different 'startDelayedSeconds' configuration! "
                            + "All Quartz jobs must share the same 'startDelayedSeconds' configuration! Cannot apply the 'startDelayedSeconds' configuration!");
        } else {
            setStartDelayedSeconds(startDelayedSeconds);
        }
    }

    Boolean autoStartScheduler = getAndRemoveParameter(parameters, "autoStartScheduler", Boolean.class);
    if (autoStartScheduler != null) {
        setAutoStartScheduler(autoStartScheduler);
    }

    Boolean prefixJobNameWithEndpointId = getAndRemoveParameter(parameters, "prefixJobNameWithEndpointId",
            Boolean.class);
    if (prefixJobNameWithEndpointId != null) {
        this.prefixJobNameWithEndpointId = prefixJobNameWithEndpointId;
    }

    DefaultSchedulerEndpoint result = null;
    // Create quartz endpoint
    for (Class<? extends DefaultSchedulerEndpoint> clazz : registeredSchedulers.keySet()) {
        Map<String, String> params = registeredSchedulers.get(clazz);
        Set<String> subset = new TreeSet<String>(parameters.keySet());
        // see if any of the parameters match with a scheduler.
        subset.retainAll(params.keySet());
        if (subset.size() > 0) {
            boolean found = true;
            for (String key : subset) {
                String value = params.get(key);
                if (value != null) {
                    Pattern pattern = Pattern.compile(value);
                    if (!pattern.matcher(parameters.get(key).toString()).find()) {
                        found = false;
                        break;
                    }
                }

            }
            if (found) {
                try {
                    result = (DefaultSchedulerEndpoint) ConstructorUtils.invokeConstructor(clazz,
                            new Object[] { uri, this });
                } catch (Exception ex) {
                    logger.error("Failed to create Scheduler - {}", uri, ex);
                    return null;
                }
            }
        }
    }
    if (result == null) {
        result = new SimpleScheduleEndpoint(uri, this);
    }
    // Extract [trigger].XXX and job.XXX properties to be set on endpoint below
    Map<String, Object> triggerParameters = IntrospectionSupport.extractProperties(parameters,
            result.getParameterPrefix() + ".");
    Map<String, Object> jobParameters = IntrospectionSupport.extractProperties(parameters, "job.");

    TriggerKey triggerKey = createTriggerKey(uri, remaining, result);
    result.setTriggerKey(triggerKey);
    result.setTriggerParameters(triggerParameters);
    result.setJobParameters(jobParameters);
    return result;
}

From source file:net.audumla.climate.bom.BOMClimateObserverCatalogue.java

protected static ClimateObserver getClimateObserverById(Class<?> clazz, ClimateDataSource source)
        throws Exception {
    ClimateDataSource name = ClimateDataSourceFactory.getInstance().newInstance();
    name.setId(source.getId() + ":" + clazz.getName());
    ClimateObserver station = ClimateObserverCatalogue.getInstance().getRegisteredClimateObserver(name);
    if (station == null) {
        // delegated to allow ClimateObservers to not be compiled into factory
        BOMClimateDataSource bomSource = ClimateDataSourceFactory.decorateInstance(source,
                BOMClimateDataSource.class);
        loadBOMStationInfo(bomSource);// w ww. j  a  va2  s.c om
        station = (ClimateObserver) ConstructorUtils.invokeConstructor(clazz, bomSource);
        ClimateObserverCatalogue.getInstance().registerClimateObserver(name, station);
    }
    return station;
}

From source file:com.tobedevoured.modelcitizen.ModelFactory.java

/**
 * Register {@link Blueprint} from instance.
 *
 * @param blueprint {@link Blueprint}/*from w  w  w.java2  s. c  o m*/
 * @throws RegisterBlueprintException
 */
public void registerBlueprint(Object blueprint) throws RegisterBlueprintException {

    Blueprint blueprintAnnotation = blueprint.getClass().getAnnotation(Blueprint.class);
    if (blueprintAnnotation == null) {
        throw new RegisterBlueprintException("Blueprint class not annotated by @Blueprint: " + blueprint);
    }
    Class target = blueprintAnnotation.value();

    List<ModelField> modelFields = new ArrayList<ModelField>();

    logger.debug("Registering {} blueprint for {}", blueprint.getClass(), target);

    Constructable newInstance = null;

    List<Callback> afterCreateCallbacks = new ArrayList<Callback>();

    // Get all fields for the blueprint target class
    Collection<Field> fields = getAllFields(blueprint.getClass()).values();
    for (Field field : fields) {

        field.setAccessible(true);

        // Register ConstructorCallback field
        if (field.getType().equals(ConstructorCallback.class)
                || field.getType().equals(com.tobedevoured.modelcitizen.callback.ConstructorCallback.class)) {
            Object fieldVal = null;
            try {
                fieldVal = field.get(blueprint);
            } catch (IllegalArgumentException e) {
                throw new RegisterBlueprintException(e);
            } catch (IllegalAccessException e) {
                throw new RegisterBlueprintException(e);
            }

            if (fieldVal instanceof Constructable) {
                logger.debug("Registering ConstructorCallback for {}", blueprint.getClass());
                newInstance = (Constructable) fieldVal;
            } else {
                throw new RegisterBlueprintException("Blueprint " + blueprint.getClass().getSimpleName()
                        + " Field class for " + field.getName() + " is invalid ConstructorCallback");
            }

            // ConstructorCallback is only used to create new instance.
            continue;
        }

        // Register AfterCreateCallback field
        if (field.getType().equals(AfterCreateCallback.class)) {

            Object fieldVal = null;
            try {
                fieldVal = field.get(blueprint);
            } catch (IllegalArgumentException e) {
                throw new RegisterBlueprintException(e);
            } catch (IllegalAccessException e) {
                throw new RegisterBlueprintException(e);
            }

            if (fieldVal instanceof AfterCreateCallback) {
                logger.debug("Registering AfterCreateCallback for {}", blueprint.getClass());
                afterCreateCallbacks.add((AfterCreateCallback) fieldVal);
            } else {
                throw new RegisterBlueprintException("Blueprint " + blueprint.getClass().getSimpleName()
                        + " Field class for " + field.getName() + " is invalid AfterCreateCallback");
            }

            // AfterCreateCallback is only used in callbacks
            continue;
        }

        // Process @Default
        Default defaultAnnotation = field.getAnnotation(Default.class);
        if (defaultAnnotation != null) {

            DefaultField defaultField = new DefaultField();
            defaultField.setName(field.getName());
            defaultField.setForce(defaultAnnotation.force());

            try {
                defaultField.setValue(field.get(blueprint));
            } catch (IllegalArgumentException e) {
                throw new RegisterBlueprintException(e);
            } catch (IllegalAccessException e) {
                throw new RegisterBlueprintException(e);
            }

            defaultField.setTarget(field.getType());
            defaultField.setFieldClass(field.getType());
            modelFields.add(defaultField);

            logger.trace("  Setting default for {} to {} and forced {}",
                    new Object[] { defaultField.getName(), defaultField.getValue(), defaultField.isForce() });

        }

        // Process @Mapped
        Mapped mapped = field.getAnnotation(Mapped.class);
        if (mapped != null) {
            MappedField mappedField = new MappedField();
            mappedField.setName(field.getName());

            if (field.getAnnotation(Nullable.class) != null) {
                mappedField.setNullable(true);
            }

            // If @Mapped(target) not set, use Field's class
            if (NotSet.class.equals(mapped.target())) {
                mappedField.setTarget(field.getType());

                // Use @Mapped(target) for MappedField#target
            } else {
                mappedField.setTarget(mapped.target());
            }

            mappedField.setFieldClass(field.getType());
            modelFields.add(mappedField);

            logger.trace("  Setting mapped for {} to {}", mappedField.getName(), mappedField.getTarget());
        }

        // Process @MappedList
        MappedList mappedCollection = field.getAnnotation(MappedList.class);
        if (mappedCollection != null) {
            MappedListField listField = new MappedListField();
            listField.setName(field.getName());
            listField.setFieldClass(field.getType());
            listField.setSize(mappedCollection.size());
            listField.setIgnoreEmpty(mappedCollection.ignoreEmpty());
            listField.setForce(mappedCollection.force());

            // If @MappedList(target) not set, use Field's class
            if (NotSet.class.equals(mappedCollection.target())) {
                listField.setTarget(field.getType());

                // Use @MappedList(target) for MappedListField#target
            } else {
                listField.setTarget(mappedCollection.target());
            }

            // If @MappedList(targetList) not set, use ArrayList
            if (NotSet.class.equals(mappedCollection.targetList())) {
                listField.setTargetList(ArrayList.class);
            } else {

                // Ensure that the targetList implements List
                boolean implementsList = false;
                for (Class interf : mappedCollection.targetList().getInterfaces()) {
                    if (List.class.equals(interf)) {
                        implementsList = true;
                        break;
                    }
                }

                if (!implementsList) {
                    throw new RegisterBlueprintException(
                            "@MappedList targetList must implement List for field " + field.getName());
                }

                listField.setTargetList(mappedCollection.targetList());
            }

            modelFields.add(listField);

            logger.trace("  Setting mapped list for {} to {} as <{}> and forced {}",
                    new Object[] { listField.getName(), listField.getFieldClass(), listField.getTarget(),
                            listField.isForce() });

        }

        // Process @MappedSet
        MappedSet mappedSet = field.getAnnotation(MappedSet.class);
        if (mappedSet != null) {
            MappedSetField setField = new MappedSetField();
            setField.setName(field.getName());
            setField.setFieldClass(field.getType());
            setField.setSize(mappedSet.size());
            setField.setIgnoreEmpty(mappedSet.ignoreEmpty());
            setField.setForce(mappedSet.force());

            // XXX: @MappedSet( target ) is required
            // If @MappedSet(target) not set
            if (NotSet.class.equals(mappedSet.target())) {

                // XXX: incorrect, should use generic defined by Set, luckily annotation forces target to be set
                setField.setTarget(field.getType());

                // Use @MappedSet(target) for MappedSet#target
            } else {
                setField.setTarget(mappedSet.target());
            }

            // If @MappedSet(targetSet) not set, use HashSet
            if (NotSet.class.equals(mappedSet.targetSet())) {
                setField.setTargetSet(HashSet.class);
            } else {

                // Ensure that the targetSet implements Set
                boolean implementsSet = false;
                for (Class interf : mappedSet.targetSet().getInterfaces()) {
                    if (Set.class.equals(interf)) {
                        implementsSet = true;
                        break;
                    }
                }

                if (!implementsSet) {
                    throw new RegisterBlueprintException(
                            "@MappedSet targetSet must implement Set for field " + field.getName());
                }

                setField.setTargetSet(mappedSet.targetSet());
            }

            modelFields.add(setField);

            logger.trace("  Setting mapped set for {} to {} as <{}> and is forced {}", new Object[] {
                    setField.getName(), setField.getFieldClass(), setField.getTarget(), setField.isForce() });

        }
    }

    blueprints.add(blueprint);

    Class templateClass = blueprintAnnotation.template();
    BlueprintTemplate template = null;
    try {
        template = (BlueprintTemplate) ConstructorUtils.invokeConstructor(templateClass, null);
    } catch (NoSuchMethodException e) {
        throw new RegisterBlueprintException(e);
    } catch (IllegalAccessException e) {
        throw new RegisterBlueprintException(e);
    } catch (InvocationTargetException e) {
        throw new RegisterBlueprintException(e);
    } catch (InstantiationException e) {
        throw new RegisterBlueprintException(e);
    }

    // Create Erector for this Blueprint
    Erector erector = new Erector();
    erector.setTemplate(template);
    erector.setBlueprint(blueprint);
    erector.setModelFields(modelFields);
    erector.setTarget(target);
    erector.setNewInstance(newInstance);
    erector.setCallbacks("afterCreate", afterCreateCallbacks);

    erectors.put(target, erector);
}

From source file:org.apache.hadoop.hbase.replication.ReplicationFactory.java

public static ReplicationQueues getReplicationQueues(ReplicationQueuesArguments args) throws Exception {
    Class<?> classToBuild = args.getConf().getClass(
            "hbase.region.replica." + "replication.replicationQueues.class", defaultReplicationQueueClass);
    return (ReplicationQueues) ConstructorUtils.invokeConstructor(classToBuild, args);
}

From source file:org.apache.hadoop.hbase.replication.ReplicationFactory.java

public static ReplicationQueuesClient getReplicationQueuesClient(ReplicationQueuesClientArguments args)
        throws Exception {
    Class<?> classToBuild = args.getConf().getClass(
            "hbase.region.replica." + "replication.replicationQueuesClient.class",
            ReplicationQueuesClientZKImpl.class);
    return (ReplicationQueuesClient) ConstructorUtils.invokeConstructor(classToBuild, args);
}

From source file:org.apache.impala.authorization.AuthorizationChecker.java

private static ResourceAuthorizationProvider createProvider(AuthorizationConfig config,
        AuthorizationPolicy policy) {/*from   w  w  w  .  j  av  a2 s .c  om*/
    try {
        ProviderBackend providerBe;
        // Create the appropriate backend provider.
        if (config.isFileBasedPolicy()) {
            providerBe = new SimpleFileProviderBackend(config.getSentryConfig().getConfig(),
                    config.getPolicyFile());
        } else {
            // Note: The second parameter to the ProviderBackend is a "resourceFile" path
            // which is not used by Impala. We cannot pass 'null' so instead pass an empty
            // string.
            providerBe = new SimpleCacheProviderBackend(config.getSentryConfig().getConfig(), "");
            Preconditions.checkNotNull(policy);
            ProviderBackendContext context = new ProviderBackendContext();
            context.setBindingHandle(policy);
            providerBe.initialize(context);
        }

        SimpleDBPolicyEngine engine = new SimpleDBPolicyEngine(config.getServerName(), providerBe);

        // Try to create an instance of the specified policy provider class.
        // Re-throw any exceptions that are encountered.
        String policyFile = config.getPolicyFile() == null ? "" : config.getPolicyFile();
        return (ResourceAuthorizationProvider) ConstructorUtils.invokeConstructor(
                Class.forName(config.getPolicyProviderClassName()), new Object[] { policyFile, engine });
    } catch (Exception e) {
        // Re-throw as unchecked exception.
        throw new IllegalStateException("Error creating ResourceAuthorizationProvider: ", e);
    }
}