List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:org.apache.servicemix.jbi.deployer.impl.ComponentInstaller.java
private ObjectName initComponent() throws Exception { ComponentDesc componentDesc = installationContext.getDescriptor(); List<SharedLibrary> libs = new ArrayList<SharedLibrary>(); if (componentDesc.getSharedLibraries() != null) { for (SharedLibraryList sll : componentDesc.getSharedLibraries()) { SharedLibrary lib = deployer.getSharedLibrary(sll.getName()); if (lib == null) { // TODO: throw exception here ? } else { libs.add(lib);/* w w w .j ava 2s. c o m*/ } } } SharedLibrary[] aLibs = libs.toArray(new SharedLibrary[libs.size()]); if (innerComponent == null) { ClassLoader classLoader = createClassLoader(getBundle(), componentDesc.getIdentification().getName(), (String[]) installationContext.getClassPathElements() .toArray(new String[installationContext.getClassPathElements().size()]), componentDesc.isComponentClassLoaderDelegationParentFirst(), aLibs); ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); Class clazz = classLoader.loadClass(componentDesc.getComponentClassName()); innerComponent = (javax.jbi.component.Component) clazz.newInstance(); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } Component component = deployer.registerComponent(getBundle(), componentDesc, innerComponent, aLibs); return deployer.getManagementStrategy().getManagedObjectName(component, null, ObjectName.class); }
From source file:com.citytechinc.cq.component.touchuidialog.util.TouchUIDialogUtil.java
public static final List<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option> getOptionsForSelection( Selection selectionAnnotation, Class<?> type, ClassLoader classLoader, ClassPool classPool) throws InvalidComponentFieldException { List<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option> options = new ArrayList<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option>(); /*//from w w w.j a v a 2s.co m * Options specified in the annotation take precedence */ if (selectionAnnotation != null && selectionAnnotation.options().length > 0) { int i = 0; for (com.citytechinc.cq.component.annotations.Option curOptionAnnotation : selectionAnnotation .options()) { if (StringUtils.isEmpty(curOptionAnnotation.value())) { throw new InvalidComponentFieldException( "Selection Options specified in the selectionOptions Annotation property must include a non-empty text and value attribute"); } OptionParameters optionParameters = new OptionParameters(); optionParameters.setText(curOptionAnnotation.text()); optionParameters.setValue(curOptionAnnotation.value()); optionParameters.setSelected(curOptionAnnotation.selected()); optionParameters.setFieldName(OPTION_FIELD_NAME_PREFIX + (i++)); options.add(new com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option( optionParameters)); } } /* * If options were not specified by the annotation then we check to see * if the field is an Enum and if so, the options are pulled from the * Enum definition */ else if (type.isEnum()) { int i = 0; try { for (Object curEnumObject : classLoader.loadClass(type.getName()).getEnumConstants()) { Enum<?> curEnum = (Enum<?>) curEnumObject; options.add(buildSelectionOptionForEnum(curEnum, classPool, OPTION_FIELD_NAME_PREFIX + (i++))); } } catch (Exception e) { throw new InvalidComponentFieldException("Error generating selection from enum", e); } } return options; }
From source file:com.liferay.portal.servlet.PortletContextListener.java
public void contextInitialized(ServletContextEvent sce) { try {/* w ww. j av a 2 s .co m*/ // Servlet context ServletContext ctx = sce.getServletContext(); _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE, StringPool.UNDERLINE); // Company ids _companyIds = StringUtil.split(ctx.getInitParameter("company_id")); // Class loader ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Initialize portlets String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) }; _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls); // Portlet context wrapper Iterator itr1 = _portlets.iterator(); while (itr1.hasNext()) { Portlet portlet = (Portlet) itr1.next(); javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader .loadClass(portlet.getPortletClass()).newInstance(); Indexer indexerInstance = null; if (Validator.isNotNull(portlet.getIndexerClass())) { indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass()) .newInstance(); } Scheduler schedulerInstance = null; if (Validator.isNotNull(portlet.getSchedulerClass())) { schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass()) .newInstance(); } PreferencesValidator prefsValidator = null; if (Validator.isNotNull(portlet.getPreferencesValidator())) { prefsValidator = (PreferencesValidator) contextClassLoader .loadClass(portlet.getPreferencesValidator()).newInstance(); try { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { prefsValidator.validate( PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences())); } } catch (Exception e1) { _log.warn("Portlet with the name " + portlet.getPortletId() + " does not have valid default preferences"); } } Map resourceBundles = null; if (Validator.isNotNull(portlet.getResourceBundle())) { resourceBundles = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getSupportedLocales().iterator(); while (itr2.hasNext()) { String supportedLocale = (String) itr2.next(); Locale locale = new Locale(supportedLocale); try { ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(), locale, contextClassLoader); resourceBundles.put(locale.getLanguage(), resourceBundle); } catch (MissingResourceException mre) { _log.warn(mre.getMessage()); } } } Map customUserAttributes = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator(); while (itr2.hasNext()) { Map.Entry entry = (Map.Entry) itr2.next(); String attrName = (String) entry.getKey(); String attrCustomClass = (String) entry.getValue(); customUserAttributes.put(attrCustomClass, contextClassLoader.loadClass(attrCustomClass).newInstance()); } PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance, indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes); PortletContextPool.put(portlet.getPortletId(), pcw); } // Portlet class loader String servletPath = ctx.getRealPath("/"); if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) { servletPath += "/"; } File servletClasses = new File(servletPath + "WEB-INF/classes"); File servletLib = new File(servletPath + "WEB-INF/lib"); List urls = new ArrayList(); if (servletClasses.exists()) { urls.add(new URL("file:" + servletClasses + "/")); } if (servletLib.exists()) { String[] jars = FileUtil.listFiles(servletLib); for (int i = 0; i < jars.length; i++) { urls.add(new URL("file:" + servletLib + "/" + jars[i])); } } URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]), contextClassLoader); ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader); // Portlet display String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml); for (int i = 0; i < _companyIds.length; i++) { String companyId = _companyIds[i]; Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY); Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories); WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories); } // Reinitialize portal properties PropsUtil.init(); } catch (Exception e2) { Logger.error(this, e2.getMessage(), e2); } }
From source file:hudson.gridmaven.MavenBuilder.java
private void callSetListenerWithReflectOnInterceptors(PluginManagerListener pluginManagerListener, ClassLoader cl) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // This patched code is required to run more instances of Maven-type plugin if (pluginManagerInterceptorClazz == null) { pluginManagerInterceptorClazz = cl.loadClass("hudson.maven.agent.PluginManagerInterceptor"); }//w w w.j a v a 2 s . c o m if (pluginManagerInterceptorListenerClazz == null) { pluginManagerInterceptorListenerClazz = new Class[] { cl.loadClass("hudson.maven.agent.PluginManagerListener") }; } Method setListenerMethod = pluginManagerInterceptorClazz.getMethod("setListener", pluginManagerInterceptorListenerClazz); setListenerMethod.invoke(null, new Object[] { pluginManagerListener }); if (lifecycleInterceptorClazz == null) { lifecycleInterceptorClazz = cl.loadClass("org.apache.maven.lifecycle.LifecycleExecutorInterceptor"); } if (lifecycleInterceptorListenerClazz == null) { lifecycleInterceptorListenerClazz = new Class[] { cl.loadClass("org.apache.maven.lifecycle.LifecycleExecutorListener") }; } setListenerMethod = lifecycleInterceptorClazz.getMethod("setListener", lifecycleInterceptorListenerClazz); setListenerMethod.invoke(null, new Object[] { pluginManagerListener }); }
From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java
/** * Auto-detect the class names of the implementation of <code>com.sun.tools.doclets.Taglet</code> class from a * given jar file./*from w w w . j a v a 2 s. com*/ * <br/> * <b>Note</b>: <code>JAVA_HOME/lib/tools.jar</code> is a requirement to find * <code>com.sun.tools.doclets.Taglet</code> class. * * @param jarFile not null * @return the list of <code>com.sun.tools.doclets.Taglet</code> class names from a given jarFile. * @throws IOException if jarFile is invalid or not found, or if the <code>JAVA_HOME/lib/tools.jar</code> * is not found. * @throws ClassNotFoundException if any * @throws NoClassDefFoundError if any */ protected static List<String> getTagletClassNames(File jarFile) throws IOException, ClassNotFoundException, NoClassDefFoundError { List<String> classes = getClassNamesFromJar(jarFile); ClassLoader cl; // Needed to find com.sun.tools.doclets.Taglet class File tools = new File(System.getProperty("java.home"), "../lib/tools.jar"); if (tools.exists() && tools.isFile()) { cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL(), tools.toURI().toURL() }, null); } else { cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }, null); } List<String> tagletClasses = new ArrayList<String>(); Class<?> tagletClass = cl.loadClass("com.sun.tools.doclets.Taglet"); for (String s : classes) { Class<?> c = cl.loadClass(s); if (tagletClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) { tagletClasses.add(c.getName()); } } return tagletClasses; }
From source file:io.github.divinespear.maven.plugin.JpaSchemaGeneratorMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip) { log.info("schema generation is skipped."); return;// ww w . ja v a 2 s. com } if (this.outputDirectory != null && !this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } final ClassLoader classLoader = this.getProjectClassLoader(); // driver load hack // http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-from-an-arbitrary-location if (StringUtils.isNotBlank(this.jdbcDriver)) { try { Driver driver = (Driver) classLoader.loadClass(this.jdbcDriver).newInstance(); DriverManager.registerDriver(driver); } catch (Exception e) { throw new MojoExecutionException("Dependency for driver-class " + this.jdbcDriver + " is missing!", e); } } // generate schema Thread thread = Thread.currentThread(); ClassLoader currentClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); this.generate(); } catch (Exception e) { throw new MojoExecutionException("Error while running", e); } finally { thread.setContextClassLoader(currentClassLoader); } // post-process try { this.postProcess(); } catch (IOException e) { throw new MojoExecutionException("Error while post-processing script file", e); } }
From source file:hu.bme.mit.sette.common.descriptors.java.JavaSourceFile.java
/** * Creates an instance of the {@link JavaSourceFile} object by using the * specified source and binary directories and the specified source file. * * @param pSourceDirectory//from w w w .j a va 2s . c om * the source directory (e.g. /path/to/project/src) * @param pSourceFile * the source file (e.g. * /path/to/project/src/hu/bme/mit/sette/MyClass.java) * @param classLoader * the class loader to be used to load the class * @return A {@link JavaSourceFile} object representing the Java file. * @throws SetteConfigurationException * If an error occurred, e.g. not enough permissions to access * the directory or the file, cannot retrieve canonical file * names, file is in the specified directory or cannot load the * Java class contained by the file. */ public static JavaSourceFile fromFile(final File pSourceDirectory, final File pSourceFile, final ClassLoader classLoader) throws SetteConfigurationException { Validate.notNull(pSourceDirectory, "The source directory must not be null"); Validate.notNull(pSourceFile, "The source file must not be null"); Validate.notNull(classLoader, "The class loader must not be null"); try { // validate permissions GeneralValidator v = new GeneralValidator(JavaSourceFile.class); FileValidator v1 = new FileValidator(pSourceDirectory); v1.type(FileType.DIRECTORY).readable(true).executable(true); v.addChildIfInvalid(v1); FileValidator v2 = new FileValidator(pSourceFile); v2.type(FileType.REGULAR_FILE).readable(true); v2.extension(JavaFileUtils.JAVA_SOURCE_EXTENSION); v.addChildIfInvalid(v2); v.validate(); // get canonical file objects File sourceDirectory = pSourceDirectory.getCanonicalFile(); File sourceFile = pSourceFile.getCanonicalFile(); // get paths // like "/path/to/project/src" String sourceDirectoryPath = FilenameUtils.normalizeNoEndSeparator(sourceDirectory.getAbsolutePath()); // like "/path/to/project/src/pkg/path/here/MyClass.java" String sourceFilePath = FilenameUtils.normalizeNoEndSeparator(sourceFile.getAbsolutePath()); // check whether the file is under the specified directory if (FilenameUtils.directoryContains(sourceDirectoryPath, sourceFilePath)) { // get relative path and class name // like "pkg/path/here/MyClass.java" String classPath = sourceFilePath.substring(sourceDirectoryPath.length() + 1); // like "pkg.path.here.MyClass" String className = JavaFileUtils.filenameToClassName(classPath); // load class Class<?> javaClass = classLoader.loadClass(className); // create object and return with it return new JavaSourceFile(sourceFile, javaClass); } else { String message = String.format("The source file is not in the " + "source directory\n" + "(sourceDirectory: [%s])\n(sourceFile: [%s])", sourceDirectory, sourceFile); throw new SetteConfigurationException(message); } } catch (ValidatorException e) { throw new SetteConfigurationException("A validation exception occurred", e); } catch (IOException e) { throw new SetteConfigurationException("An IO exception occurred", e); } catch (ClassNotFoundException e) { throw new SetteConfigurationException("The Java class could not have been loaded", e); } }
From source file:org.pegadi.client.ApplicationLauncher.java
/** * This method registers a listener for the Quit-menuitem on OS X application menu. * To avoid platform dependent compilation, reflection is utilized. * <p/>// w ww . j av a 2s.c om * Basically what happens, is this: * <p/> * Application app = Application.getApplication(); * app.addApplicationListener(new ApplicationAdapter() { * public void handleQuit(ApplicationEvent e) { * e.setHandled(false); * conditionalExit(); * } * }); */ private void registerOSXApplicationMenu() { try { ClassLoader cl = getClass().getClassLoader(); // Create class-objects for the classes and interfaces we need final Class comAppleEawtApplicationClass = cl.loadClass("com.apple.eawt.Application"); final Class comAppleEawtApplicationListenerInterface = cl .loadClass("com.apple.eawt.ApplicationListener"); final Class comAppleEawtApplicationEventClass = cl.loadClass("com.apple.eawt.ApplicationEvent"); final Method applicationEventSetHandledMethod = comAppleEawtApplicationEventClass .getMethod("setHandled", new Class[] { boolean.class }); // Set up invocationhandler-object to recieve events from OS X application menu InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("handleQuit")) { applicationEventSetHandledMethod.invoke(args[0], new Object[] { Boolean.FALSE }); conditionalExit(); } return null; } }; // Create applicationlistener proxy Object applicationListenerProxy = Proxy.newProxyInstance(cl, new Class[] { comAppleEawtApplicationListenerInterface }, handler); // Get a real Application-object Method applicationGetApplicationMethod = comAppleEawtApplicationClass.getMethod("getApplication", new Class[0]); Object theApplicationObject = applicationGetApplicationMethod.invoke(null, new Object[0]); // Add the proxy application object as listener Method addApplicationListenerMethod = comAppleEawtApplicationClass.getMethod("addApplicationListener", new Class[] { comAppleEawtApplicationListenerInterface }); addApplicationListenerMethod.invoke(theApplicationObject, new Object[] { applicationListenerProxy }); } catch (Exception e) { log.info("we are not on OSX"); } }
From source file:com.quinsoft.zeidon.dbhandler.JdbcHandler.java
@SuppressWarnings("unchecked") public JdbcDomainTranslator getTranslator() { if (translator == null) { String transName = getConfigValue("Translator"); // If translator name isn't defined, use the standard one. if (StringUtils.isBlank(transName)) { // Translator isn't specified. Let's try to be smart and determine the // correct translator from the transaction string. String connStr = options.getOiSourceUrl(); if (!StringUtils.isBlank(connStr)) { if (connStr.contains("sqlite")) return new SqliteJdbcTranslator(task, this); }// w ww . ja v a 2 s. co m return new StandardJdbcTranslator(task, this); } try { ObjectEngine oe = task.getObjectEngine(); ClassLoader classLoader = oe.getClassLoader(transName); Class<? extends JdbcDomainTranslator> translatorClass; translatorClass = (Class<? extends JdbcDomainTranslator>) classLoader.loadClass(transName); Constructor<? extends JdbcDomainTranslator> constructor = translatorClass .getConstructor(translatorConstructorArgs); translator = constructor.newInstance(task, this); } catch (Throwable t) { throw ZeidonException.prependMessage(t, "Error trying to load translator class = '%s', DB=%s", transName, options.getOiSourceUrl()); } } return translator; }