List of usage examples for java.lang.reflect Constructor newInstance
@CallerSensitive @ForceInline public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java
static void registerDriver(String driverClassName) { if (isDriverExisted(driverClassName)) return;/*from w ww . j a v a2 s. c o m*/ Class<?> tibcoDriver = null; Constructor<?> tdConstructor = null; Driver driver = null; if (driverClassName != null) { try { tibcoDriver = Class.forName(driverClassName); tdConstructor = tibcoDriver.getDeclaredConstructor(); driver = (Driver) tdConstructor.newInstance((Object[]) null); DriverManager.registerDriver(driver); } catch (Exception ex) { } if (tibcoDriver == null) printLog("Couldn't Class.forName for " + driverClassName); else if (tdConstructor == null) printLog("Couldn't get constructor for " + driverClassName); else if (driver == null) printLog("Couldn't instantiate " + driverClassName); } }
From source file:org.uimafit.spring.SpringContextResourceManager.java
/** * Instantiate a non-visible class./*from w ww . ja v a 2 s. c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException { Constructor constr = null; try { Class<?> cl = Class.forName(aClassName); List<Class> types = new ArrayList<Class>(); List<Object> values = new ArrayList<Object>(); for (int i = 0; i < aArgs.length; i += 2) { types.add((Class) aArgs[i]); values.add(aArgs[i + 1]); } constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()])); constr.setAccessible(true); return (T) constr.newInstance(values.toArray(new Object[values.size()])); } catch (Exception e) { throw new ResourceInitializationException(e); } finally { if (constr != null) { constr.setAccessible(false); } } }
From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java
/** * Copy source bean properties of type bean to target bean as detached beans * //from ww w .j a v a2 s.c o m * @param sourceBean * Source Bean * @param targetBean * Target Bean * @param childrenBeanConverters * List of converters needed to convert source bean children of * type bean to target bean children of type bean * @param sourceFields * Fields of source Bean * @throws Exception */ private static void convertBeanFields(AbstractBean sourceBean, AbstractBean targetBean, IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception { // Arrays to hold bean field names, source types and target types String[] beanFieldNames = new String[0]; Type[] sourceFieldTypes = new Type[0]; Type[] targetFieldTypes = new Type[0]; // For each source field... for (Field field : sourceFields) { // If source field is a bean... if (AbstractBean.class.isAssignableFrom(field.getType())) { // Fill Arrays with name, source field type and target type beanFieldNames = (String[]) ArrayUtils.add(beanFieldNames, field.getName()); sourceFieldTypes = (Type[]) ArrayUtils.add(sourceFieldTypes, field.getType()); targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes, targetBean.getClass().getDeclaredField(field.getName()).getType()); } } // For each field with bean type... for (int i = 0; i < beanFieldNames.length; i++) { String beanFieldName = beanFieldNames[i]; Type sourceFieldType = sourceFieldTypes[i]; Type targetFieldType = targetFieldTypes[i]; // Select the proper converter... IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldType, targetFieldType); // Get the target bean constructor @SuppressWarnings("unchecked") Constructor<AbstractBean> constructor = ((Class<AbstractBean>) targetFieldType) .getConstructor(new Class[] {}); // Create target child bean AbstractBean targetChildBean = constructor.newInstance(new Object[] {}); // Detach target child bean with source child bean and converter ((Detachable) targetChildBean).detach( (AbstractBean) getGetterMethod(beanFieldName, sourceBean).invoke(sourceBean), converter); // Set the detached target bean getSetterMethod(beanFieldName, targetFieldType, targetBean).invoke(targetBean, targetChildBean); } }
From source file:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils.java
/** * Returns a DataGetter using information in the * displayModel for the individual with the URI given by dataGetterURI * to configure it. /* w ww . j a v a2 s . c o m*/ * * May return null. * This should not throw an exception if the URI exists and has a type * that does not implement the DataGetter interface. */ public static DataGetter dataGetterForURI(VitroRequest vreq, Model displayModel, String dataGetterURI) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, SecurityException { //get java class for dataGetterURI String dgClassName = getJClassForDataGetterURI(displayModel, dataGetterURI); //figure out if it implements interface DataGetter Class<?> clz = Class.forName(dgClassName); if (!DataGetter.class.isAssignableFrom(clz)) { log.debug("Class doesn't implement DataGetter: '" + dgClassName + "'"); return null; } // we want a constructor that will work for one of these argument lists (in this order) Object[][] argLists = new Object[][] { { vreq, displayModel, dataGetterURI }, { displayModel, dataGetterURI }, { vreq }, {} }; // look through the available constructors for the best fit for (Object[] argList : argLists) { for (Constructor<?> ct : clz.getConstructors()) { if (isConstructorSuitableForArguments(ct, argList)) { log.debug("Using this constructor: " + ct); return (DataGetter) ct.newInstance(argList); } } } log.debug("Didn't find a suitable constructor for '" + dgClassName + "'"); return null; }
From source file:com.rockagen.commons.util.ClassUtil.java
/** * Create new instance of specified class and type * /*w w w.j a va2 s . com*/ * @param clazz class * @param accessible accessible * @param parameterTypes parameter types * @param paramValue param value * @param <T> t * @return instance */ public static <T> T getInstance(Class<T> clazz, boolean accessible, Class<?>[] parameterTypes, Object[] paramValue) { if (clazz == null) return null; T t = null; try { if (parameterTypes != null && paramValue != null) { Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes); Object[] obj = new Object[parameterTypes.length]; System.arraycopy(paramValue, 0, obj, 0, parameterTypes.length); constructor.setAccessible(accessible); t = constructor.newInstance(obj); } } catch (SecurityException e) { log.error("{}", e.getMessage(), e); } catch (NoSuchMethodException e) { log.error("{}", e.getMessage(), e); } catch (IllegalArgumentException e) { log.error("{}", e.getMessage(), e); } catch (InstantiationException e) { log.error("{}", e.getMessage(), e); } catch (IllegalAccessException e) { log.error("{}", e.getMessage(), e); } catch (InvocationTargetException e) { log.error("{}", e.getMessage(), e); } return t; }
From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java
public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) { final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig(); final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false); if (solrServerNode != null) { try {//from w w w. ja v a2 s.co m final Node classNode = solrServerNode.getAttributes().getNamedItem("class"); String className; if (classNode != null) { className = classNode.getTextContent(); } else { className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer"; } @SuppressWarnings("unchecked") final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className); final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false); SolrServer solrServer; if (StringUtils.isNotBlank(arg)) { final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class); solrServer = constructor.newInstance(arg); } else { solrServer = clazz.newInstance(); } final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username", false); final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password", false); if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && solrServer instanceof SolrLibHttpSolrServer) { final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer; final URL u = new URL(arg); final AuthScope authScope = new AuthScope(u.getHost(), u.getPort()); final Credentials credentials = new UsernamePasswordCredentials(username, password); solrLibHttpSolrServer.setCredentials(authScope, credentials); solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor()); } final NodeList childNodes = solrServerNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final String name = node.getNodeName(); if (!"arg".equals(name) && !"credentials".equals(name)) { final String value = node.getTextContent(); final Node typeNode = node.getAttributes().getNamedItem("type"); final Method method = clazz.getMethod( "set" + name.substring(0, 1).toUpperCase() + name.substring(1), getMethodArgClass(typeNode)); method.invoke(solrServer, getMethodArgValue(typeNode, value)); } } } if (solrServer instanceof SolrLibHttpSolrServer) { ((SolrLibHttpSolrServer) solrServer).init(); } suggestUpdateConfig.setSolrServer(solrServer); } catch (final Exception e) { throw new FessSuggestException("Failed to load SolrServer.", e); } } final String labelFields = config.getVal("updateHandler/suggest/labelFields", false); if (StringUtils.isNotBlank(labelFields)) { suggestUpdateConfig.setLabelFields(labelFields.trim().split(",")); } final String roleFields = config.getVal("updateHandler/suggest/roleFields", false); if (StringUtils.isNotBlank(roleFields)) { suggestUpdateConfig.setRoleFields(roleFields.trim().split(",")); } final String expiresField = config.getVal("updateHandler/suggest/expiresField", false); if (StringUtils.isNotBlank(expiresField)) { suggestUpdateConfig.setExpiresField(expiresField); } final String segmentField = config.getVal("updateHandler/suggest/segmentField", false); if (StringUtils.isNotBlank(segmentField)) { suggestUpdateConfig.setSegmentField(segmentField); } final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false); if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) { suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval)); } //set suggestFieldInfo final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true); for (int i = 0; i < nodeList.getLength(); i++) { try { final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig(); final Node fieldInfoNode = nodeList.item(i); final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes(); final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName"); final String fieldName = fieldNameNode.getNodeValue(); if (StringUtils.isBlank(fieldName)) { continue; } fieldConfig.setTargetFields(fieldName.trim().split(",")); if (logger.isInfoEnabled()) { for (final String s : fieldConfig.getTargetFields()) { logger.info("fieldName : " + s); } } final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes(); for (int j = 0; j < fieldInfoChilds.getLength(); j++) { final Node fieldInfoChildNode = fieldInfoChilds.item(j); final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName(); if ("tokenizerFactory".equals(fieldInfoChildNodeName)) { //field tokenier settings final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig(); final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes(); final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class"); final String tokenizerClassName = tokenizerClassNameNode.getNodeValue(); tokenizerConfig.setClassName(tokenizerClassName); if (logger.isInfoEnabled()) { logger.info("tokenizerFactory : " + tokenizerClassName); } final Map<String, String> args = new HashMap<String, String>(); for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) { final Node attribute = tokenizerFactoryAttributes.item(k); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { args.put(key, value); } } if (!args.containsKey(USER_DICT_PATH)) { final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, ""); if (StringUtils.isNotBlank(userDictPath)) { args.put(USER_DICT_PATH, userDictPath); } final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING, ""); if (StringUtils.isNotBlank(userDictEncoding)) { args.put(USER_DICT_ENCODING, userDictEncoding); } } tokenizerConfig.setArgs(args); fieldConfig.setTokenizerConfig(tokenizerConfig); } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) { //field reading converter settings final NodeList converterNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < converterNodeList.getLength(); k++) { final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig(); final Node converterNode = converterNodeList.item(k); if (!"converter".equals(converterNode.getNodeName())) { continue; } final NamedNodeMap converterAttributes = converterNode.getAttributes(); final Node classNameNode = converterAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); converterConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("converter : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < converterAttributes.getLength(); l++) { final Node attribute = converterAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } converterConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("converter properties = " + properties); } fieldConfig.addConverterConfig(converterConfig); } } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) { //field normalizer settings final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < normalizerNodeList.getLength(); k++) { final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig(); final Node normalizerNode = normalizerNodeList.item(k); if (!"normalizer".equals(normalizerNode.getNodeName())) { continue; } final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes(); final Node classNameNode = normalizerAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); normalizerConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("normalizer : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < normalizerAttributes.getLength(); l++) { final Node attribute = normalizerAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } normalizerConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("normalize properties = " + properties); } fieldConfig.addNormalizerConfig(normalizerConfig); } } } suggestUpdateConfig.addFieldConfig(fieldConfig); } catch (final Exception e) { throw new FessSuggestException("Failed to load Suggest Field Info.", e); } } return suggestUpdateConfig; }
From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtil.java
/** * Returns new instance of a class.//from ww w .j a va 2 s . c om * @param constructor * to invoke * @param parameters * to pass to constructor * @param <T> * type of constructor * @return new instance of class or {@link IllegalStateException} if any exception occurs * @see Constructor#newInstance(Object...) */ public static <T> T invokeConstructor(Constructor<T> constructor, Object... parameters) { try { return constructor.newInstance(parameters); } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) { throw new IllegalStateException(ex); } }
From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests * @param context to use for caching SSL sessions (may be null for no caching) * @return AndroidHttpClient for you to use for all your requests. *///from w w w .j a v a2 s . c om public static AndroidHttpClient newInstance(String userAgent, Context context) { HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, false); Object sessionCache = null; // Use a session cache for SSL sockets -- Froyo only if (null != context && null != sSslSessionCacheClass) { Constructor<?> ct; try { ct = sSslSessionCacheClass.getConstructor(Context.class); sessionCache = ct.newInstance(context); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SocketFactory sslCertificateSocketFactory = null; if (null != sessionCache) { Method getHttpSocketFactoryMethod; try { getHttpSocketFactoryMethod = SSLCertificateSocketFactory.class .getDeclaredMethod("getHttpSocketFactory", Integer.TYPE, sSslSessionCacheClass); sslCertificateSocketFactory = (SocketFactory) getHttpSocketFactoryMethod.invoke(null, SOCKET_OPERATION_TIMEOUT, sessionCache); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null == sslCertificateSocketFactory) { sslCertificateSocketFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme("https", sslCertificateSocketFactory, 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); }
From source file:de.kp.ames.web.function.domain.JsonBusinessProvider.java
/** * @param jaxrHandle// w ww.j a va 2 s . c om * @param objectName * @return */ private static IJsonRegistryObject createJsonObjectForName(JaxrHandle jaxrHandle, String objectName) throws Exception { String MODUL_PACKAGE = "de.kp.ames.web.function.domain.model"; Class<?> clazz = Class.forName(MODUL_PACKAGE + "." + objectName); Constructor<?> constructor = clazz.getConstructor(JaxrHandle.class); Object instance = constructor.newInstance(jaxrHandle); return (IJsonRegistryObject) instance; }
From source file:net.authorize.api.controller.test.ApiCoreTestBase.java
@SuppressWarnings("unchecked") private static <Q extends ANetApiRequest, S extends ANetApiResponse, T extends ApiOperationBase<Q, S>> S executeTestRequest( boolean successExpected, Q request, Class<T> controllerClass, Environment execEnvironment) { LogHelper.debug(logger, "Created %s Request: '%s'", request.getClass(), request); S response = null;//w w w . j a va 2s . c om T controller = null; errorResponse = null; try { Class<?>[] parameterTypes = new Class<?>[] { request.getClass() }; Constructor<T> constructor = controllerClass.getConstructor(parameterTypes); Object controllerObject = constructor.newInstance(request); controller = (T) controllerObject; ANetApiResponse baseResponse = controller.executeWithApiResponse(execEnvironment); LogHelper.info(logger, "%s ResultCode: %s", controllerClass, controller.getResultCode()); LogHelper.info(logger, "%s Results: %s", controllerClass, controller.getResults()); response = (S) baseResponse; } catch (Exception e) { LogHelper.error(logger, "Exception : '%s' during %s", e.getMessage(), controllerClass); } if (successExpected) { processFailureResult(true, controller, response); validateSuccess(controller, response); } else { validateFailure(controller, response); } if (null == response && null != controller && null != controller.getErrorResponse()) { errorResponse = controller.getErrorResponse(); } return response; }