Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

In this page you can find the example usage for java.lang Class newInstance.

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

From source file:com.linkedin.databus.bootstrap.utils.BootstrapSeederMain.java

public static void init(String[] args) throws Exception {
    parseArgs(args);//  w w w .ja v a2s. c om

    // Load the source configuration JSON file
    //File sourcesJson = new File("integration-test/config/sources-member2.json");
    File sourcesJson = new File(_sSourcesConfigFile);

    ObjectMapper mapper = new ObjectMapper();
    PhysicalSourceConfig physicalSourceConfig = mapper.readValue(sourcesJson, PhysicalSourceConfig.class);
    physicalSourceConfig.checkForNulls();

    Config config = new Config();

    ConfigLoader<StaticConfig> configLoader = new ConfigLoader<StaticConfig>("databus.seed.", config);
    _sStaticConfig = configLoader.loadConfig(_sBootstrapConfigProps);

    // Make sure the URI from the configuration file identifies an Oracle JDBC source.
    String uri = physicalSourceConfig.getUri();
    if (!uri.startsWith("jdbc:oracle")) {
        throw new InvalidConfigException("Invalid source URI (" + physicalSourceConfig.getUri()
                + "). Only jdbc:oracle: URIs are supported.");
    }

    String sourceTypeStr = physicalSourceConfig.getReplBitSetter().getSourceType();
    if (SourceType.TOKEN.toString().equalsIgnoreCase(sourceTypeStr))
        throw new InvalidConfigException(
                "Token Source-type for Replication bit setter config cannot be set for trigger-based Databus relay !!");

    // Create the OracleDataSource used to get DB connection(s)
    try {
        Class oracleDataSourceClass = OracleJarUtils.loadClass("oracle.jdbc.pool.OracleDataSource");
        Object ods = oracleDataSourceClass.newInstance();
        Method setURLMethod = oracleDataSourceClass.getMethod("setURL", String.class);
        setURLMethod.invoke(ods, uri);
        _sDataStore = (DataSource) ods;
    } catch (Exception e) {
        String errMsg = "Error creating a data source object ";
        LOG.error(errMsg, e);
        throw e;
    }

    //TODO: Need a better way than relaying on RelayFactory for generating MonitoredSourceInfo
    OracleEventProducerFactory factory = new BootstrapSeederOracleEventProducerFactory(
            _sStaticConfig.getController().getPKeyNameMap());

    // Parse each one of the logical sources
    _sources = new ArrayList<OracleTriggerMonitoredSourceInfo>();
    FileSystemSchemaRegistryService schemaRegistryService = FileSystemSchemaRegistryService
            .build(_sStaticConfig.getSchemaRegistry().getFileSystem());

    Set<String> seenUris = new HashSet<String>();
    for (LogicalSourceConfig sourceConfig : physicalSourceConfig.getSources()) {
        String srcUri = sourceConfig.getUri();
        if (seenUris.contains(srcUri)) {
            String msg = "Uri (" + srcUri
                    + ") is used for more than one sources. Currently Bootstrap Seeder cannot support seeding sources with the same URI together. Please have them run seperately !!";
            LOG.fatal(msg);
            throw new InvalidConfigException(msg);
        }
        seenUris.add(srcUri);
        OracleTriggerMonitoredSourceInfo source = factory.buildOracleMonitoredSourceInfo(sourceConfig.build(),
                physicalSourceConfig.build(), schemaRegistryService);
        _sources.add(source);
    }
    _sSeeder = new BootstrapDBSeeder(_sStaticConfig.getBootstrap(), _sources);

    _sBootstrapBuffer = new BootstrapEventBuffer(_sStaticConfig.getController().getCommitInterval() * 2);

    _sWriterThread = new BootstrapSeederWriterThread(_sBootstrapBuffer, _sSeeder);

    _sReader = new BootstrapSrcDBEventReader(_sDataStore, _sBootstrapBuffer, _sStaticConfig.getController(),
            _sources, _sSeeder.getLastRows(), _sSeeder.getLastKeys(), 0);
}

From source file:com.digitalpebble.storm.crawler.util.MetadataTransfer.java

public static MetadataTransfer getInstance(Map<String, Object> conf) {
    String className = ConfUtils.getString(conf, metadataTransferClassParamName);

    MetadataTransfer transferInstance;//from  w  w  w. j  a  va  2s .  co  m

    // no custom class specified
    if (StringUtils.isBlank(className)) {
        transferInstance = new MetadataTransfer();
    }

    else {
        try {
            Class<?> transferClass = Class.forName(className);
            boolean interfaceOK = MetadataTransfer.class.isAssignableFrom(transferClass);
            if (!interfaceOK) {
                throw new RuntimeException("Class " + className + " must extend MetadataTransfer");
            }
            transferInstance = (MetadataTransfer) transferClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Can't instanciate " + className);
        }
    }

    // should not be null
    if (transferInstance != null)
        transferInstance.configure(conf);

    return transferInstance;
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * @see Inicializacao/*  w ww .ja  v  a  2  s .c o  m*/
 */
private static void executarInicializacao()
        throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {

    String nome = getPropriedade("IpeRoxo.Inicializacao");
    if (nome == null || nome.isEmpty())
        return;

    log.info(getMensagem(null, "Log.Executando.Inicializacao"));

    Class<?> classe = Class.forName(nome);

    try {

        ((Inicializacao) classe.newInstance()).inicializar();

    } catch (InstantiationException e) {
        throw e;
    } catch (IllegalAccessException e) {
        throw e;
    } catch (Exception e) {
        if (Boolean.parseBoolean(getPropriedade("IpeRoxo.Inicializacao.Essencial"))) {
            throw e instanceof IOException ? (IOException) e : new IOException(e);
        } else {
            log.error(e.getMessage(), e);
        }
    }

}

From source file:com.redhat.rhtracking.persistance.services.Queries.java

public static <T extends Catalog, K extends Serializable> void initCatalog(List<String> catalogue,
        CrudRepository<T, K> repository, Class<T> type) {
    logger.info("Starting " + type.getSimpleName() + " catalog");
    Iterable<T> typeItr = repository.findAll();
    for (T t : typeItr) {
        if (catalogue.contains(t.toString())) {
            catalogue.remove(t.toString());
        }/* ww  w . j av  a  2s . c o  m*/
    }
    if (!catalogue.isEmpty()) {
        try {
            for (String s : catalogue) {
                T missing = type.newInstance();
                missing.setType(s);
                repository.save(missing);
            }
        } catch (IllegalAccessException | InstantiationException ex) {
            logger.error(ex);
        }
    }
}

From source file:grails.plugin.searchable.internal.lucene.LuceneUtils.java

/**
 * Returns an array of {@link Term}s by parsing the given query string. Since Lucene's query parser is used,
 * special query characters and words (OR / AND) are not included in the returned terms
 *
 * @param defaultField The default term field, cannot be null
 * @param queryString the query string to parse, cannot be null
 * @param analyzerClass the Class of Analyzer, may be null in which case Lucene's StandardAnalyzer is used
 * @return the Term array (field + term pairs)
 * @throws org.apache.lucene.queryParser.ParseException if the the query has invalid syntax
 *//*from   w w w . j a  v  a  2 s.com*/
public static Term[] realTermsForQueryString(String defaultField, String queryString, Class analyzerClass)
        throws ParseException {
    if (analyzerClass == null) {
        return realTermsForQueryString(defaultField, queryString, (Analyzer) null);
    }
    try {
        return realTermsForQueryString(defaultField, queryString, (Analyzer) analyzerClass.newInstance());
    } catch (Exception ex) {
        // Convert to unchecked
        LOG.error("Failed to create instance of Analyzer class [" + analyzerClass + "]: " + ex, ex);
        throw new IllegalStateException(
                "Failed to create instance of Analyzer class [" + analyzerClass + "]: " + ex);
    }
}

From source file:com.krm.dbaudit.common.utils.Collections3.java

/** 
 *  Map  JavaBean /* w  w  w .j a  v a 2s .com*/
 * @param type ? 
 * @param map ? map 
 * @return ? JavaBean  
 * @throws IntrospectionException ? 
 * @throws IllegalAccessException  JavaBean  
 * @throws InstantiationException  JavaBean  
 * @throws InvocationTargetException  setter  
 */
public static Object convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException,
        InstantiationException, InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(type); // ?   
    Object obj = type.newInstance(); //  JavaBean    

    //  JavaBean    
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor descriptor = propertyDescriptors[i];
        String propertyName = descriptor.getName();

        if (map.containsKey(propertyName)) {
            // ??? try ???   
            Object value = map.get(propertyName);
            if (propertyName.equals("id") || propertyName.equals("parentId")) {
                value = Long.valueOf(value.toString());
            }
            if (value instanceof Number) {
                value = Long.valueOf(value.toString());
            } else if (value instanceof Date) {
                value = (Date) value;
            }
            Object[] args = new Object[1];
            args[0] = value;
            descriptor.getWriteMethod().invoke(obj, args);
        }
    }
    return obj;
}

From source file:com.us.reflect.ClassFinder.java

/**
 *  before//from  ww w. ja  v a2  s.  co  m
 * @param invocation
 */
public static void beforeAction(ActionInvocation invc, String actionPath) throws Exception {
    ActionInvocation invocation = (ActionInvocation) invc;
    final ActionProxy proxy = invocation.getProxy();
    Class<?> classFromPath = findClass(actionPath);// ?Class
    Class<?> targetClass = classFromPath == null ? proxy.getAction().getClass() : classFromPath;
    String methodName = findMethodName(actionPath);// ??? checkExist(sessionKey)
    String[] paramers = findParameters(actionPath);
    Class<?>[] paramersType = findParameterTypes(targetClass, paramers);
    Method method = targetClass.getDeclaredMethod(methodName, paramersType);
    Object runner = targetClass.newInstance();
    Field[] allFiled = targetClass.getDeclaredFields();
    for (Field field : allFiled) {
        String beanName = field.getName();
        Object bean = DaoHelper.getBeanById(beanName);
        if (bean != null) {
            BeanUtils.setProperty(runner, beanName, bean);
        }
    }
    method.invoke(runner, getRuntimeArgs(invocation, paramers));
}

From source file:com.sematext.hbase.hut.UpdatesProcessingMrJob.java

@SuppressWarnings({ "unchecked", "unused" })
private static <T> T createInstance(String className, Class<T> clazz) {
    try {/*from   ww  w .j  a va2  s. co  m*/
        Class c = Class.forName(className);
        return (T) c.newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException("Could not create class instance.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Could not create class instance.", e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Could not create class instance.", e);
    }
}

From source file:management.limbr.test.util.PojoTester.java

@SuppressWarnings("unchecked")
private static <T> T createRichObject(Class<T> type) {
    try {/*www . j a  v a  2s .  c  o  m*/
        if (type.equals(Set.class)) {
            return (T) new HashSet<>();
        } else if (type.equals(List.class)) {
            return (T) new ArrayList<>();
        } else if (type.isEnum()) {
            T[] values = type.getEnumConstants();
            return values[random.nextInt(values.length)];
        } else {
            return type.newInstance();
        }
    } catch (IllegalAccessException | InstantiationException ex) {
        throw new IllegalStateException("Couldn't construct object of type " + type.getName() + ".", ex);
    }
}

From source file:com.xidu.framework.common.util.Utils.java

public static List<?> convertDtoListToDomainList(List<?> origDtoList, Class<?> domainClass) {
    if (null == origDtoList) {
        return null;
    }//w ww .j  a  v  a2s .co m
    List<Object> convertedList = new ArrayList<Object>();
    for (Object orig : origDtoList) {
        Object dest;
        try {
            dest = domainClass.newInstance();
            ConvertUtils.register(new DateConverter(null), Date.class);
            BeanUtils.copyProperties(dest, orig);
            convertedList.add(dest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return convertedList;
}