org.apache.commons.lang3.reflect.ConstructorUtils Java Examples

The following examples show how to use org.apache.commons.lang3.reflect.ConstructorUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UIComponentRegistry.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a given class.
 *
 * @param currentClass
 *            Class to instantiate.
 * @param args
 *            Arguments for the class constructor.
 * @return New instance, what else?
 */
private static <T> T instantiate(Class<? extends T> currentClass, Object... args) {
    T instance = null;

    Log.debug("Args: " + Arrays.toString(args));
    Class<? extends Object>[] classes = new Class<?>[args.length];
    try {
        for (int i = 0; i < args.length; i++) {
            classes[i] = args[i].getClass();
        }
        final Constructor<? extends T> ctor = ConstructorUtils.getMatchingAccessibleConstructor(currentClass, classes);
        instance = ctor.newInstance(args);
    } catch (final Exception e) {
        // not pretty but we're catching several exceptions we can do little
        // about
        Log.error("Error calling constructor for " + currentClass.getName() + " with arguments " + classes, e);
    }
    return instance;
}
 
Example #2
Source File: ThreadPoolFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param size     Maximum pool size
 * @param priority Thread priority
 * @param handler  Uncaught thread exception handler
 */
protected ThreadPool create(final String prefix, final Integer size, final ThreadPool.Priority priority, final Thread.UncaughtExceptionHandler handler) {
    try {
        final Constructor<ThreadPool> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            prefix.getClass(), size.getClass(), priority.getClass(), handler.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", handler.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(prefix, size, priority, handler);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example #3
Source File: LoginCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public LoginCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledLoginCallback();
    }
}
 
Example #4
Source File: UserDateFormatterFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public AbstractUserDateFormatter create(final String timezone) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, timezone.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", timezone.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(timezone);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example #5
Source File: AlertCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public AlertCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledAlertCallback();
    }
}
 
Example #6
Source File: HostKeyCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public HostKeyCallback create(final Controller c, final Protocol protocol) {
    if(Scheme.sftp.equals(protocol.getScheme())) {
        try {
            if(null == constructor) {
                constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, c.getClass());
            }
            if(null == constructor) {
                log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
                // Call default constructor for disabled implementations
                return clazz.newInstance();
            }
            return constructor.newInstance(c);
        }
        catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
            log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
            return new DisabledHostKeyCallback();
        }
    }
    return new DisabledHostKeyCallback();
}
 
Example #7
Source File: VaultFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
private Vault create(final Path directory, final String masterkey, final byte[] pepper) {
    try {
        final Constructor<Vault> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            directory.getClass(), masterkey.getClass(), pepper.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", directory.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(directory, masterkey, pepper);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return Vault.DISABLED;
    }
}
 
Example #8
Source File: CertificateTrustCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public CertificateTrustCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateTrustCallback();
    }
}
 
Example #9
Source File: PasswordCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public PasswordCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledPasswordCallback();
    }
}
 
Example #10
Source File: CertificateIdentityCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public CertificateIdentityCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateIdentityCallback();
    }
}
 
Example #11
Source File: GameServiceImpl.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
private List<Class> allGames() {
    List<Class> result = new LinkedList<>(
            findInPackage(gamePackage));

    result.sort(Comparator.comparing(Class::getName));

    result.remove(NullGameType.class);
    result.remove(AbstractGameType.class);

    remove(result,
            it -> ConstructorUtils.getMatchingAccessibleConstructor(it) == null);

    if (pluginsEnable) {
        loadFromPlugins(result);
    }

    if (excludeGames != null) {
        remove(result, it -> Stream.of(excludeGames)
                .anyMatch(name -> it.getPackage().toString().contains(name)));
    }

    return result;
}
 
Example #12
Source File: ReflectionCompactorListenerFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<CompactorListener> createCompactorListener(Properties properties)
    throws CompactorListenerCreationException {
  State state = new State(properties);

  if (Strings.isNullOrEmpty(state.getProp(COMPACTOR_LISTENERS))) {
    return Optional.absent();
  }

  List<CompactorListener> listeners = new ArrayList<>();
  for (String listenerClassName : state.getPropAsList(COMPACTOR_LISTENERS)) {
    try {
      listeners.add((CompactorListener) ConstructorUtils
          .invokeConstructor(Class.forName(listenerClassName), properties));
    } catch (ReflectiveOperationException e) {
      throw new CompactorListenerCreationException(String
          .format("Unable to create CompactorListeners from key \"%s\" with value \"%s\"", COMPACTOR_LISTENERS,
              properties.getProperty(COMPACTOR_LISTENERS)), e);
    }
  }
  return Optional.<CompactorListener>of(new SerialCompactorListener(listeners));
}
 
Example #13
Source File: GobblinConstructorUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new
 * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the
 * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first
 * constructor whose signature matches the argument types will be invoked.
 *
 * @param cls the class to be instantiated
 * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor.
 * @return
 *
 * @throws NoSuchMethodException if no constructor matched was found
 */
@SafeVarargs
public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs)
    throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  for (List<Object> args : constructorArgs) {

    Class<?>[] parameterTypes = new Class[args.size()];
    for (int i = 0; i < args.size(); i++) {
      parameterTypes[i] = args.get(i).getClass();
    }

    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) {
      return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()]));
    }
  }
  throw new NoSuchMethodException("No accessible constructor found");
}
 
Example #14
Source File: AbstractObjectToStringConverter.java    From yarg with Apache License 2.0 6 votes vote down vote up
protected Object convertFromStringUnresolved(Class<?> parameterClass, String paramValueStr) {
    try {
        Constructor constructor = ConstructorUtils.getAccessibleConstructor(parameterClass, String.class);
        if (constructor != null) {
            return constructor.newInstance(paramValueStr);
        } else {
            Method valueOf = MethodUtils.getAccessibleMethod(parameterClass, "valueOf", String.class);
            if (valueOf != null) {
                return valueOf.invoke(null, paramValueStr);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new ReportingException(
                String.format("Could not instantiate object with class [%s] from [%s] string.",
                        parameterClass.getCanonicalName(),
                        paramValueStr));
    }
    return paramValueStr;
}
 
Example #15
Source File: ScheduledJobConfigurationManager.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
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<>(SpecConsumer.class);
  try {
    String specConsumerClassName = GobblinClusterConfigurationKeys.DEFAULT_SPEC_CONSUMER_CLASS;
    if (config.hasPath(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY)) {
      specConsumerClassName = config.getString(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY);
    }
    LOGGER.info("Using SpecConsumer ClassNameclass name/alias " + specConsumerClassName);
    this._specConsumer = (SpecConsumer) ConstructorUtils
        .invokeConstructor(Class.forName(this.aliasResolver.resolve(specConsumerClassName)), config);
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
      | ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
Example #16
Source File: LegacyJobLockFactoryManager.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of {@link JobLock}.
 *
 * @param properties the properties used to determine which instance of {@link JobLock} to create and the
 *                   relevant settings
 * @param jobLockEventListener the {@link JobLock} event listener
 * @return an instance of {@link JobLock}
 * @throws JobLockException throw when the {@link JobLock} fails to initialize
 */
public static JobLock getJobLock(Properties properties, JobLockEventListener jobLockEventListener)
        throws JobLockException {
  Preconditions.checkNotNull(properties);
  Preconditions.checkNotNull(jobLockEventListener);
  JobLock jobLock;
  if (properties.containsKey(ConfigurationKeys.JOB_LOCK_TYPE)) {
    try {
      Class<?> jobLockClass = Class.forName(
          properties.getProperty(ConfigurationKeys.JOB_LOCK_TYPE, FileBasedJobLock.class.getName()));
      jobLock = (JobLock) ConstructorUtils.invokeConstructor(jobLockClass, properties);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
        NoSuchMethodException | InvocationTargetException e) {
      throw new JobLockException(e);
    }
  } else {
    jobLock = new FileBasedJobLock(properties);
  }
  if (jobLock instanceof ListenableJobLock) {
    ((ListenableJobLock)jobLock).setEventListener(jobLockEventListener);
  }
  return jobLock;
}
 
Example #17
Source File: TopologySpec.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * @return A {@link SpecExecutor}'s instance defined by <Technology, Location, Communication Mechanism>
 */
public synchronized SpecExecutor getSpecExecutor() {
  if (null == specExecutorInstance) {
    String specExecutorClass = DEFAULT_SPEC_EXECUTOR_INSTANCE;
    if (config.hasPath(SPEC_EXECUTOR_INSTANCE_KEY)) {
      specExecutorClass = config.getString(SPEC_EXECUTOR_INSTANCE_KEY);
    }
    try {
      ClassAliasResolver<SpecExecutor> _aliasResolver =
          new ClassAliasResolver<>(SpecExecutor.class);
      specExecutorInstance = (SpecExecutor) ConstructorUtils
          .invokeConstructor(Class.forName(_aliasResolver
              .resolve(specExecutorClass)), config);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
        | ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  return specExecutorInstance;
}
 
Example #18
Source File: HiveSerDeManager.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get an instance of {@link HiveSerDeManager}.
 *
 * @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 ORC) 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);
  }
}
 
Example #19
Source File: KafkaSchemaRegistryFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static KafkaSchemaRegistry getSchemaRegistry(Properties props) {
  Preconditions.checkArgument(props.containsKey(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS),
      "Missing required property " + KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS);

  boolean tryCache = Boolean.parseBoolean(props.getProperty(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CACHE,
      DEFAULT_TRY_CACHING));

  Class<?> clazz;
  try {
    clazz =
        (Class<?>) Class.forName(props.getProperty(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS));
    KafkaSchemaRegistry schemaRegistry = (KafkaSchemaRegistry) ConstructorUtils.invokeConstructor(clazz, props);
    if (tryCache && !schemaRegistry.hasInternalCache())
    {
      schemaRegistry = new CachingKafkaSchemaRegistry(schemaRegistry);
    }
    return schemaRegistry;
  } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
      | InstantiationException e) {
    log.error("Failed to instantiate " + KafkaSchemaRegistry.class, e);
    throw Throwables.propagate(e);
  }
}
 
Example #20
Source File: PusherFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public SharedResourceFactoryResponse<Pusher<T>> createResource(SharedResourcesBroker<S> broker,
    ScopedConfigView<S, StringNameSharedResourceKey> config)
    throws NotConfiguredException {
  Config pusherConfig = config.getConfig().withFallback(FALLBACK);
  String pusherClass = pusherConfig.getString(PUSHER_CLASS);

  Pusher<T> pusher;
  try {
    pusher = (Pusher) ConstructorUtils.invokeConstructor(Class.forName(pusherClass), pusherConfig);
  } catch (ReflectiveOperationException e) {
    log.warn("Unable to construct a pusher with class {}. LoggingPusher will be used", pusherClass, e);
    pusher = new LoggingPusher<>();
  }
  return new ResourceInstance<>(pusher);
}
 
Example #21
Source File: GobblinConstructorUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a
 * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will
 * invoke the first constructor found.
 *
 * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with
 * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and
 * finally <init>().
 *
 * @param cls the class to instantiate.
 * @param args the arguments to use for instantiation.
 * @throws ReflectiveOperationException
 */
public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException {

  Class<?>[] parameterTypes = new Class[args.length];
  for (int i = 0; i < args.length; i++) {
    parameterTypes[i] = args[i].getClass();
  }

  for (int i = args.length; i >= 0; i--) {
    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, Arrays.copyOfRange(parameterTypes, 0, i)) != null) {
      log.debug(
          String.format("Found accessible constructor for class %s with parameter types %s.", cls,
              Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i))));
      return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i));
    }
  }
  throw new NoSuchMethodException(String.format("No accessible constructor for class %s with parameters a subset of %s.",
      cls, Arrays.toString(parameterTypes)));
}
 
Example #22
Source File: DefaultAuditSinkFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * 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>
 * 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);
  }
}
 
Example #23
Source File: ReflectionUtil.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * 调用构造函数.
 */
public static <T> T invokeConstructor(final Class<T> cls, Object... args) {
	try {
		return ConstructorUtils.invokeConstructor(cls, args);
	} catch (Exception e) {
		throw ExceptionUtil.unwrapAndUnchecked(e);
	}
}
 
Example #24
Source File: KafkaDeserializerExtractor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link KafkaSchemaRegistry} using the value of {@link #KAFKA_DESERIALIZER_TYPE}, if not set it
 * defaults to {@link SimpleKafkaSchemaRegistry}.
 */
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);
}
 
Example #25
Source File: HiveRegistrationPolicyBase.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link HiveRegistrationPolicy} from a {@link State} object.
 *
 * @param props A {@link State} object that contains property, {@link #HIVE_REGISTRATION_POLICY},
 * which is the class name of the desired policy. This policy class must have a constructor that
 * takes a {@link State} object.
 */
public static HiveRegistrationPolicy getPolicy(State props) {
  Preconditions.checkArgument(props.contains(ConfigurationKeys.HIVE_REGISTRATION_POLICY));

  String policyType = props.getProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY);
  try {
    return (HiveRegistrationPolicy) ConstructorUtils.invokeConstructor(Class.forName(policyType), props);
  } catch (ReflectiveOperationException e) {
    throw new RuntimeException(
        "Unable to instantiate " + HiveRegistrationPolicy.class.getSimpleName() + " with type " + policyType, e);
  }
}
 
Example #26
Source File: HiveRegister.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Get an instance of {@link HiveRegister}.
 *
 * @param hiveRegisterType The name of a class that implements {@link HiveRegister}.
 * @param props A {@link State} object used to instantiate the {@link HiveRegister} object.
 */
public static HiveRegister get(String hiveRegisterType, State props, Optional<String> metastoreURI) {
  try {
    return (HiveRegister) ConstructorUtils.invokeConstructor(Class.forName(hiveRegisterType), props, metastoreURI);
  } catch (ReflectiveOperationException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #27
Source File: HiveRegister.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
protected HiveRegistrationUnitComparator<?> getPartitionComparator(HivePartition existingPartition,
    HivePartition newPartition) {
  try {
    Class<?> clazz =
        Class.forName(this.props.getProp(HIVE_PARTITION_COMPARATOR_TYPE, DEFAULT_HIVE_PARTITION_COMPARATOR_TYPE));
    return (HiveRegistrationUnitComparator<?>) ConstructorUtils
        .invokeConstructor(clazz, existingPartition, newPartition);
  } catch (ReflectiveOperationException e) {
    log.error("Unable to instantiate Hive partition comparator", e);
    throw Throwables.propagate(e);
  }
}
 
Example #28
Source File: SimpleKafkaSpecProducer.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private AsyncDataWriter<byte[]> getKafkaProducer() {
  if (null == _kafkaProducer) {
    try {
      Class<?> kafkaProducerClass = (Class<?>) Class.forName(_kafkaProducerClassName);
      _kafkaProducer = (AsyncDataWriter<byte[]>) ConstructorUtils.invokeConstructor(kafkaProducerClass,
          ConfigUtils.configToProperties(_config));
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
      log.error("Failed to instantiate Kafka consumer from class " + _kafkaProducerClassName, e);
      throw new RuntimeException("Failed to instantiate Kafka consumer", e);
    }
  }
  return _kafkaProducer;
}
 
Example #29
Source File: CombineRetentionPolicy.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@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);
      }
    }
  }

  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());

}
 
Example #30
Source File: HiveUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * @return an instance of the {@link InputFormat} in this {@link StorageDescriptor}.
 */
public static InputFormat<?, ?> getInputFormat(StorageDescriptor sd) throws IOException {
  try {
    InputFormat<?, ?> inputFormat =
        ConstructorUtils.invokeConstructor((Class<? extends InputFormat>) Class.forName(sd.getInputFormat()));
    if (inputFormat instanceof JobConfigurable) {
      ((JobConfigurable) inputFormat).configure(new JobConf(getHadoopConfiguration()));
    }
    return inputFormat;
  } catch (ReflectiveOperationException re) {
    throw new IOException("Failed to instantiate input format.", re);
  }
}