List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.streamsets.datacollector.stagelibrary.ClassLoaderStageLibraryTask.java
@VisibleForTesting void loadStages() { if (LOG.isDebugEnabled()) { for (ClassLoader cl : stageClassLoaders) { LOG.debug("About to load stages from library '{}'", StageLibraryUtils.getLibraryName(cl)); }/*from w w w . j a v a 2 s .c o m*/ } try { RuntimeEL.loadRuntimeConfiguration(runtimeInfo); } catch (IOException e) { throw new RuntimeException(Utils.format("Could not load runtime configuration, '{}'", e.toString()), e); } try { int libs = 0; int stages = 0; long start = System.currentTimeMillis(); LocaleInContext.set(Locale.getDefault()); for (ClassLoader cl : stageClassLoaders) { libs++; StageLibraryDefinition libDef = StageLibraryDefinitionExtractor.get().extract(cl); LOG.debug("Loading stages from library '{}'", libDef.getName()); try { Enumeration<URL> resources = cl.getResources(STAGES_DEFINITION_RESOURCE); while (resources.hasMoreElements()) { Map<String, String> stagesInLibrary = new HashMap<>(); URL url = resources.nextElement(); try (InputStream is = url.openStream()) { List<String> stageList = json.readValue(is, List.class); stageList = removeIgnoreStagesFromList(libDef, stageList); for (String className : stageList) { stages++; Class<? extends Stage> klass = (Class<? extends Stage>) cl.loadClass(className); StageDefinition stage = StageDefinitionExtractor.get().extract(libDef, klass, Utils.formatL("Library='{}'", libDef.getName())); String key = createKey(libDef.getName(), stage.getName()); LOG.debug("Loaded stage '{}' (library:name)", key); if (stagesInLibrary.containsKey(key)) { throw new IllegalStateException(Utils.format( "Library '{}' contains more than one definition for stage '{}', class '{}' and class '{}'", libDef.getName(), key, stagesInLibrary.get(key), stage.getStageClass())); } stagesInLibrary.put(key, stage.getClassName()); this.stageList.add(stage); stageMap.put(key, stage); computeDependsOnChain(stage); } } } } catch (IOException | ClassNotFoundException ex) { throw new RuntimeException( Utils.format("Could not load stages definition from '{}', {}", cl, ex.toString()), ex); } } LOG.debug("Loaded '{}' libraries with a total of '{}' stages in '{}ms'", libs, stages, System.currentTimeMillis() - start); } finally { LocaleInContext.set(null); } }
From source file:catalina.startup.BootstrapService.java
/** * Load the Catalina Service./*from w ww . j ava 2 s . c om*/ */ public void init(DaemonContext context) throws Exception { String arguments[] = null; /* Read the arguments from the Daemon context */ if (context != null) { arguments = context.getArguments(); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { if (arguments[i].equals("-debug")) { debug = 1; } } } } log("Create Catalina server"); // Set Catalina path setCatalinaHome(); setCatalinaBase(); // Construct the class loaders we will need ClassLoader commonLoader = null; ClassLoader catalinaLoader = null; ClassLoader sharedLoader = null; try { File unpacked[] = new File[1]; File packed[] = new File[1]; File packed2[] = new File[2]; ClassLoaderFactory.setDebug(debug); unpacked[0] = new File(getCatalinaHome(), "common" + File.separator + "classes"); packed2[0] = new File(getCatalinaHome(), "common" + File.separator + "endorsed"); packed2[1] = new File(getCatalinaHome(), "common" + File.separator + "lib"); commonLoader = ClassLoaderFactory.createClassLoader(unpacked, packed2, null); unpacked[0] = new File(getCatalinaHome(), "server" + File.separator + "classes"); packed[0] = new File(getCatalinaHome(), "server" + File.separator + "lib"); catalinaLoader = ClassLoaderFactory.createClassLoader(unpacked, packed, commonLoader); System.err.println("Created catalinaLoader in: " + getCatalinaHome() + File.separator + "server" + File.separator + "lib"); unpacked[0] = new File(getCatalinaBase(), "shared" + File.separator + "classes"); packed[0] = new File(getCatalinaBase(), "shared" + File.separator + "lib"); sharedLoader = ClassLoaderFactory.createClassLoader(unpacked, packed, commonLoader); } catch (Throwable t) { log("Class loader creation threw exception", t); } Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); // Load our startup class and call its process() method if (debug >= 1) log("Loading startup class"); Class startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.CatalinaService"); Object startupInstance = startupClass.newInstance(); // Set the shared extensions class loader if (debug >= 1) log("Setting startup class properties"); String methodName = "setParentClassLoader"; Class paramTypes[] = new Class[1]; paramTypes[0] = Class.forName("java.lang.ClassLoader"); Object paramValues[] = new Object[1]; paramValues[0] = sharedLoader; Method method = startupInstance.getClass().getMethod(methodName, paramTypes); method.invoke(startupInstance, paramValues); catalinaService = startupInstance; // Call the load() method methodName = "load"; Object param[]; if (arguments == null || arguments.length == 0) { paramTypes = null; param = null; } else { paramTypes[0] = arguments.getClass(); param = new Object[1]; param[0] = arguments; } method = catalinaService.getClass().getMethod(methodName, paramTypes); if (debug >= 1) log("Calling startup class " + method); method.invoke(catalinaService, param); }
From source file:net.jawr.web.bundle.processor.BundleProcessor.java
/** * Returns the list of servlet definition, which must be initialize * //from ww w. j a va 2s . c o m * @param webXmlDoc * the web.xml document * @param servletContext * the servlet context * @param servletsToInitialize * the list of servlet to initialize * @param webAppClassLoader * the web application class loader * @return the list of servlet definition, which must be initialize * @throws ClassNotFoundException * if a class is not found */ protected List<ServletDefinition> getWebXmlServletDefinitions(Document webXmlDoc, ServletContext servletContext, List<String> servletsToInitialize, ClassLoader webAppClassLoader) throws ClassNotFoundException { // Parse the servlet configuration NodeList servletNodes = webXmlDoc.getElementsByTagName(SERVLET_TAG_NAME); List<ServletDefinition> servletDefinitions = new ArrayList<ServletDefinition>(); for (int i = 0; i < servletNodes.getLength(); i++) { String servletName = null; Class<?> servletClass = null; MockServletConfig config = new MockServletConfig(servletContext); int order = i; Node servletNode = servletNodes.item(i); Map<String, Object> initParameters = new HashMap<String, Object>(); NodeList childNodes = servletNode.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node servletChildNode = childNodes.item(j); if (servletChildNode.getNodeName().equals(SERVLET_NAME_TAG_NAME)) { servletName = getTextValue(servletChildNode); config.setServletName(servletName); } else if (servletChildNode.getNodeName().equals(SERVLET_CLASS_TAG_NAME)) { String servletClassName = getTextValue(servletChildNode); servletClass = webAppClassLoader.loadClass(servletClassName); } else if (servletChildNode.getNodeName().equals(INIT_PARAM_TAG_NAME)) { initializeInitParams(servletChildNode, initParameters); } else if (servletChildNode.getNodeName().equals(LOAD_ON_STARTUP_TAG_NAME)) { order = Integer.parseInt(getTextValue(servletChildNode)); } } // Initialize the servlet config with the init parameters config.setInitParameters(initParameters); // If the servlet name is part of the list of servlet to initialized // Set the flag accordingly if (servletsToInitialize.contains(servletName) || JawrServlet.class.isAssignableFrom(servletClass)) { ServletDefinition servletDef = new ServletDefinition(servletClass, config, order); servletDefinitions.add(servletDef); } // Handle Spring MVC servlet definition if (servletContext.getInitParameter(CONFIG_LOCATION_PARAM) == null && servletClass.getName().equals("org.springframework.web.servlet.DispatcherServlet")) { ((MockServletContext) servletContext).putInitParameter(CONFIG_LOCATION_PARAM, "/WEB-INF/" + servletName + "-servlet.xml"); } } return servletDefinitions; }
From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java
/** Loads strategy class and creates instance by calling constructor. @param strategyText contains full class name followed by parameter list for constructor. Constructor parameters may be int, double, boolean, String. Constructor parameters are parsed by splitting on commas and trimming whitespace. <pre>// w w w. j a v a 2 s . co m mypkg.MyStrategy(12, -345.67, true, false, Alpha Strategy) </pre> **/ protected TradingStrategy loadStrategy(String strategyText) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, ExceptionInInitializerError, InstantiationException, InvocationTargetException { Pattern strategyPattern = // matches full.class.Name(args...) Pattern.compile("^([A-Za-z](?:[A-Za-z0-9_.]*))\\s*[(](.*)[)]$"); Matcher matcher = strategyPattern.matcher(strategyText); if (!matcher.matches()) throw new IllegalArgumentException( "Bad Strategy: " + strategyText + "\n" + "Expected: full.class.name(-123.45, 67, true, false)"); final String strategyClassName = matcher.group(1).trim(); String parameters[] = matcher.group(2).split(","); // clean parameters for (int i = 0; i < parameters.length; i++) parameters[i] = parameters[i].trim(); if (parameters.length == 1 && parameters[0].length() == 0) parameters = new String[] {}; // 0 parameters // build classpath String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); ArrayList<URL> classPathURLs = new ArrayList<URL>(); for (int i = 0; i < classPath.length; i++) { String path = classPath[i]; if (".".equals(path)) path = System.getProperty("user.dir"); path = path.replace(File.separatorChar, '/'); if (!path.endsWith("/") && !path.endsWith(".jar")) path += "/"; try { classPathURLs.add(new File(path).toURL()); } catch (MalformedURLException e) { // bad directory in class path, skip } } final String strategyPackagePrefix = strategyClassName.substring(0, Math.max(0, strategyClassName.lastIndexOf('.') + 1)); ClassLoader loader = new URLClassLoader(classPathURLs.toArray(new URL[] {}), this.getClass().getClassLoader()) { /** Don't search parent for classes with strategyPackagePrefix. Exception: interface TradingStrategy **/ protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) return loadedClass; if (!className.startsWith(strategyPackagePrefix) || className.equals(TradingStrategy.class.getName())) { loadedClass = this.getParent().loadClass(className); if (loadedClass != null) return loadedClass; } loadedClass = findClass(className); if (loadedClass != null) { if (resolve) resolveClass(loadedClass); return loadedClass; } else throw new ClassNotFoundException(className); } }; // load class. Throws ClassNotFoundException if not found. Class<?> strategyClass = loader.loadClass(strategyClassName); // Make sure it is a TradingStrategy. if (!TradingStrategy.class.isAssignableFrom(strategyClass)) throw new ClassCastException(strategyClass.getName() + " does not implement TradingStrategy"); // Find constructor compatible with parameters Constructor[] constructors = strategyClass.getConstructors(); findConstructor: for (Constructor constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length != parameters.length) continue; Object[] values = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { if (boolean.class.equals(parameterTypes[i])) { String parameter = parameters[i].toLowerCase(); if ("false".equals(parameter)) values[i] = Boolean.FALSE; else if ("true".equals(parameter)) values[i] = Boolean.TRUE; else continue findConstructor; } else if (int.class.equals(parameterTypes[i])) { try { values[i] = new Integer(parameters[i]); } catch (NumberFormatException e) { continue findConstructor; } } else if (double.class.equals(parameterTypes[i])) { try { values[i] = new Double(parameters[i]); } catch (NumberFormatException e) { continue findConstructor; } } else if (String.class.equals(parameterTypes[i])) { values[i] = parameters[i]; } else continue findConstructor; // unsupported parameter type, skip } // all values matched types, so create instance return (TradingStrategy) constructor.newInstance(values); } throw new NoSuchMethodException(strategyText); }
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Loads the integration test classes from the class path and publishes them * to the OSGi registry./*from w w w .j a v a 2s . c o m*/ * * @param path * the bundle path to load classes from * @param bundle * the bundle */ private List<IntegrationTest> loadIntegrationTestClasses(String path, Bundle bundle) { List<IntegrationTest> tests = new ArrayList<IntegrationTest>(); // Load the classes in question ClassLoader loader = Thread.currentThread().getContextClassLoader(); Enumeration<?> entries = bundle.findEntries("/", "*.class", true); if (entries == null) { return tests; } // Look at the classes and instantiate those that implement the integration // test interface. while (entries.hasMoreElements()) { URL url = (URL) entries.nextElement(); Class<?> c = null; String className = url.getPath(); try { className = className.substring(1, className.indexOf(".class")); className = className.replace('/', '.'); c = loader.loadClass(className); boolean implementsInterface = Arrays.asList(c.getInterfaces()).contains(IntegrationTest.class); boolean extendsBaseClass = false; if (c.getSuperclass() != null) { extendsBaseClass = IntegrationTestBase.class.getName().equals(c.getSuperclass().getName()); } if (!implementsInterface && !extendsBaseClass) continue; IntegrationTest test = (IntegrationTest) c.newInstance(); test.setSite(this); tests.add(test); } catch (ClassNotFoundException e) { throw new IllegalStateException("Implementation " + className + " for integration test of class '" + identifier + "' not found", e); } catch (NoClassDefFoundError e) { // We are trying to load each and every class here, so we may as well // see classes that are not meant to be loaded logger.debug("The related class " + e.getMessage() + " for potential test case implementation " + className + " could not be found"); } catch (InstantiationException e) { throw new IllegalStateException("Error instantiating impelementation " + className + " for integration test '" + identifier + "'", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Access violation instantiating implementation " + className + " for integration test '" + identifier + "'", e); } catch (Throwable t) { throw new IllegalStateException( "Error loading implementation " + className + " for integration test '" + identifier + "'", t); } } return tests; }
From source file:it.cnr.icar.eric.client.ui.thin.RegistryObjectCollectionBean.java
private void invokeMethodOnRegistryObject(String methodPrefix) throws NoSuchMethodException, Exception { RegistryObject drilldownRO = currentRegistryObject.getRegistryObject(); Object currentRO = null;//from w w w . j a va 2 s .co m if (currentComposedRegistryObject.getNonRegistryObject() == null) { currentRO = currentComposedRegistryObject.getRegistryObject(); } else { currentRO = currentComposedRegistryObject.getNonRegistryObject(); } String objectType = currentRO.getClass().getName(); Class<? extends RegistryObject> clazz = drilldownRO.getClass(); Method m = null; String methodName = methodPrefix + objectType.substring(objectType.lastIndexOf(".") + 1); Class<?> argsClass[] = new Class[1]; String argClassName = currentRO.getClass().getName(); if (argClassName.endsWith("Impl")) { ClassLoader loader = drilldownRO.getClass().getClassLoader(); int classNamelastIndex = argClassName.lastIndexOf(".") + 1; argClassName = argClassName.substring(classNamelastIndex); argClassName = argClassName.substring(0, argClassName.length() - 4); argsClass[0] = loader.loadClass("javax.xml.registry.infomodel." + argClassName); methodName = methodPrefix + argClassName; if ((currentRegistryObject.getObjectType().equalsIgnoreCase("ClassificationScheme") || currentRegistryObject.getObjectType().equalsIgnoreCase("ClassificationNode")) && methodName.equalsIgnoreCase("addConcept")) { methodName = "addChildConcept"; } if ((currentRegistryObject.getObjectType().equalsIgnoreCase("ClassificationScheme") || currentRegistryObject.getObjectType().equalsIgnoreCase("ClassificationNode")) && methodName.equalsIgnoreCase("removeConcept")) { methodName = "removeChildConcept"; } if (currentRegistryObject.getObjectType().equalsIgnoreCase("Organization") && methodName.equalsIgnoreCase("addOrganization")) { methodName = "addChildOrganization"; } if (currentRegistryObject.getObjectType().equalsIgnoreCase("Organization") && methodName.equalsIgnoreCase("removeOrganization")) { methodName = "removeChildOrganization"; } } try { m = clazz.getMethod(methodName, argsClass); } catch (NoSuchMethodException ex) { try { m = RegistryObjectImpl.class.getMethod(methodName, argsClass); } catch (NoSuchMethodException ex2) { try { m = IdentifiableImpl.class.getMethod(methodName, argsClass); } catch (NoSuchMethodException ex3) { try { m = ExtensibleObjectImpl.class.getMethod(methodName, argsClass); } catch (NoSuchMethodException ex4) { throw ex4; } } } } Object args[] = new Object[1]; args[0] = currentRO; m.invoke(drilldownRO, args); }
From source file:android.support.v71.widget.RecyclerView.java
/** * Instantiate and set a LayoutManager, if specified in the attributes. * LayotManager/*w w w. j a va 2 s. co m*/ */ private void createLayoutManager(Context context, String className, AttributeSet attrs, int defStyleAttr, int defStyleRes) { if (className != null) { className = className.trim(); if (className.length() != 0) { // Can't use isEmpty since it was added in API 9. className = getFullClassName(context, className); try { ClassLoader classLoader; if (isInEditMode()) { // Stupid layoutlib cannot handle simple class loaders. classLoader = this.getClass().getClassLoader(); } else { classLoader = context.getClassLoader(); } Class<? extends LayoutManager> layoutManagerClass = classLoader.loadClass(className) .asSubclass(LayoutManager.class); Constructor<? extends LayoutManager> constructor; Object[] constructorArgs = null; try { constructor = layoutManagerClass.getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE); constructorArgs = new Object[] { context, attrs, defStyleAttr, defStyleRes }; } catch (NoSuchMethodException e) { try { constructor = layoutManagerClass.getConstructor(); } catch (NoSuchMethodException e1) { e1.initCause(e); throw new IllegalStateException( attrs.getPositionDescription() + ": Error creating LayoutManager " + className, e1); } } constructor.setAccessible(true); setLayoutManager(constructor.newInstance(constructorArgs)); } catch (ClassNotFoundException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Unable to find LayoutManager " + className, e); } catch (InvocationTargetException e) { throw new IllegalStateException(attrs.getPositionDescription() + ": Could not instantiate the LayoutManager: " + className, e); } catch (InstantiationException e) { throw new IllegalStateException(attrs.getPositionDescription() + ": Could not instantiate the LayoutManager: " + className, e); } catch (IllegalAccessException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Cannot access non-public constructor " + className, e); } catch (ClassCastException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Class is not a LayoutManager " + className, e); } } } }