List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:de.erdesignerng.dialect.Dialect.java
/** * Create a connection to a database./* www . j a v a 2 s .co m*/ * * @param aClassLoader the classloader * @param aDriver the name of the driver * @param aUrl the url * @param aUser the user * @param aPassword the password * @param aPromptForPassword shall be prompted for the password * @return the connection * @throws ClassNotFoundException is thrown in case of an error * @throws InstantiationException is thrown in case of an error * @throws IllegalAccessException is thrown in case of an error * @throws SQLException is thrown in case of an error */ public Connection createConnection(ClassLoader aClassLoader, String aDriver, String aUrl, String aUser, String aPassword, boolean aPromptForPassword) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { Class<Driver> theDriverClass = (Class<Driver>) aClassLoader.loadClass(aDriver); Driver theDriver = theDriverClass.newInstance(); if (aPromptForPassword) { aPassword = DialogUtils.promptForPassword(); if (aPassword == null) { return null; } } Properties theProperties = new Properties(); theProperties.put("user", aUser); theProperties.put("password", aPassword); return theDriver.connect(aUrl, theProperties); }
From source file:net.contextfw.web.application.internal.servlet.UriMappingFactory.java
@SuppressWarnings("unchecked") public SortedSet<UriMapping> createMappings(Collection<Class<?>> origClasses, ClassLoader classLoader, InitializerProvider initializerProvider, InitHandler initHandler, PropertyProvider properties, RequestInvocationFilter filter) { // Note: This process creates some phantom chains from // views that do not have any url. Those chains are // however ingnored and are not such problem. SortedSet<UriMapping> mappings = new TreeSet<UriMapping>(); try {/*from w ww.j a v a 2s . c om*/ for (Class<?> origClass : origClasses) { Class<?> cl = classLoader.loadClass(origClass.getCanonicalName()); View annotation = cl.getAnnotation(View.class); if (annotation != null) { if (!Component.class.isAssignableFrom(cl)) { throw new WebApplicationException( "Class " + cl.getName() + " annotated with @View does " + "not extend Component"); } List<Class<? extends Component>> chain = initializerProvider.getInitializerChain(cl); InitServlet servlet = new InitServlet(initHandler, chain, filter); for (String url : annotation.url()) { if (!"".equals(url)) { mappings.add(this.getMapping((Class<? extends Component>) cl, servlet, url)); } } for (String property : annotation.property()) { if (!"".equals(property)) { if (!properties.get().containsKey(property)) { throw new WebApplicationException("No url bound to property: " + property); } String url = properties.get().getProperty(property); if (url != null && !"".equals(url)) { mappings.add(this.getMapping((Class<? extends Component>) cl, servlet, url)); } else { throw new WebApplicationException("No url bound to view component. (class=" + cl.getSimpleName() + ", property=" + property + ")"); } } } } } } catch (ClassNotFoundException e) { throw new WebApplicationException(e); } return mappings; }
From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java
protected List<String> getToolsClassPath() throws Exception { List<String> toolsClassPath = new ArrayList<String>(); if ((appServerLibGlobalDir != null) && appServerLibGlobalDir.exists()) { Collection<File> globalJarFiles = FileUtils.listFiles(appServerLibGlobalDir, new String[] { "jar" }, false);/*from w ww . j a v a2 s . c o m*/ for (File file : globalJarFiles) { URI uri = file.toURI(); URL url = uri.toURL(); toolsClassPath.add(url.toString()); } Dependency jalopyDependency = createDependency("jalopy", "jalopy", "1.5rc3", "", "jar"); addDependencyToClassPath(toolsClassPath, jalopyDependency); Dependency qdoxDependency = createDependency("com.thoughtworks.qdox", "qdox", "1.12", "", "jar"); addDependencyToClassPath(toolsClassPath, qdoxDependency); ClassLoader globalClassLoader = toClassLoader(toolsClassPath); try { globalClassLoader.loadClass("javax.activation.MimeType"); } catch (ClassNotFoundException cnfe) { Dependency activationDependency = createDependency("javax.activation", "activation", "1.1", "", "jar"); addDependencyToClassPath(toolsClassPath, activationDependency); } try { globalClassLoader.loadClass("javax.mail.Message"); } catch (ClassNotFoundException cnfe) { Dependency mailDependency = createDependency("javax.mail", "mail", "1.4", "", "jar"); addDependencyToClassPath(toolsClassPath, mailDependency); } try { globalClassLoader.loadClass("com.liferay.portal.kernel.util.ReleaseInfo"); } catch (ClassNotFoundException cnfe) { Dependency portalServiceDependency = createDependency("com.liferay.portal", "portal-service", liferayVersion, "", "jar"); addDependencyToClassPath(toolsClassPath, portalServiceDependency); } try { globalClassLoader.loadClass("javax.portlet.Portlet"); } catch (ClassNotFoundException cnfe) { Dependency portletApiDependency = createDependency("javax.portlet", "portlet-api", "2.0", "", "jar"); addDependencyToClassPath(toolsClassPath, portletApiDependency); } try { globalClassLoader.loadClass("javax.servlet.ServletRequest"); } catch (ClassNotFoundException cnfe) { Dependency servletApiDependency = createDependency("javax.servlet", "servlet-api", "2.5", "", "jar"); addDependencyToClassPath(toolsClassPath, servletApiDependency); } try { globalClassLoader.loadClass("javax.servlet.jsp.JspPage"); } catch (ClassNotFoundException cnfe) { Dependency jspApiDependency = createDependency("javax.servlet.jsp", "jsp-api", "2.1", "", "jar"); addDependencyToClassPath(toolsClassPath, jspApiDependency); } } else { Dependency jalopyDependency = createDependency("jalopy", "jalopy", "1.5rc3", "", "jar"); addDependencyToClassPath(toolsClassPath, jalopyDependency); Dependency qdoxDependency = createDependency("com.thoughtworks.qdox", "qdox", "1.12", "", "jar"); addDependencyToClassPath(toolsClassPath, qdoxDependency); Dependency activationDependency = createDependency("javax.activation", "activation", "1.1", "", "jar"); addDependencyToClassPath(toolsClassPath, activationDependency); Dependency mailDependency = createDependency("javax.mail", "mail", "1.4", "", "jar"); addDependencyToClassPath(toolsClassPath, mailDependency); Dependency portalServiceDependency = createDependency("com.liferay.portal", "portal-service", liferayVersion, "", "jar"); addDependencyToClassPath(toolsClassPath, portalServiceDependency); Dependency portletApiDependency = createDependency("javax.portlet", "portlet-api", "2.0", "", "jar"); addDependencyToClassPath(toolsClassPath, portletApiDependency); Dependency servletApiDependency = createDependency("javax.servlet", "servlet-api", "2.5", "", "jar"); addDependencyToClassPath(toolsClassPath, servletApiDependency); Dependency jspApiDependency = createDependency("javax.servlet.jsp", "jsp-api", "2.1", "", "jar"); addDependencyToClassPath(toolsClassPath, jspApiDependency); } Collection<File> portalJarFiles = FileUtils.listFiles(appServerLibPortalDir, new String[] { "jar" }, false); for (File file : portalJarFiles) { URI uri = file.toURI(); URL url = uri.toURL(); toolsClassPath.add(url.toString()); } getLog().debug("Tools class path:"); for (String path : toolsClassPath) { getLog().debug("\t" + path); } return toolsClassPath; }
From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java
protected void doLaunch(FirebaseDirectory dir) throws MojoExecutionException { ClassLoader loader = createClassLoader(dir); try {/*from ww w .ja v a 2s . c o m*/ Class<?> serverClass = loader.loadClass(SERVER_CLASS); String[] cmds = createCommandLine(dir); getLog().info("Attempting to start Firebase server."); Method method = serverClass.getMethod("main", cmds.getClass()); method.invoke(null, (Object) cmds); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Server class '" + SERVER_CLASS + "' not found", e); } catch (Exception e) { throw new MojoExecutionException("Reflection error", e); } /* * Major hack here, we'll find the server main thread and wait for it... */ Thread th = findServerMainThread(); if (th == null) throw new MojoExecutionException( "Firebase Server sub-process did not start correctly; Please check the logs (" + new File(dir.firebaseDirectory, "logs/") + ")."); else { try { th.join(); } catch (InterruptedException e) { } } }
From source file:com.edgenius.wiki.service.impl.WidgetServiceImpl.java
/** * This method is executed in Spring init-method. *//*from w w w . ja v a 2s.c om*/ public void loadWidgetTemplates() { ClassLoader classLoader = WidgetTemplate.class.getClassLoader(); BufferedReader is = null; try { is = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(widgetResource))); String widgetClz; while ((widgetClz = is.readLine()) != null) { //get macro class if (StringUtils.isBlank(widgetClz) || widgetClz.trim().startsWith("#")) { //skip comment continue; } try { Object obj = classLoader.loadClass(widgetClz.trim()).newInstance(); if (obj instanceof WidgetTemplate) { WidgetTemplate widget = ((WidgetTemplate) obj); widget.init(applicationContext); String type = widget.getType(); container.put(type, widget); log.info("Widget class loading success:" + type); } } catch (Exception e) { log.error("Initial widget class " + widgetClz + " failed. This widget is ignored!!!", e); } } } catch (IOException e) { log.error("Widget resource file " + widgetResource + " not found.", e); } finally { IOUtils.closeQuietly(is); } }
From source file:com.ocpsoft.pretty.faces.el.resolver.SpringBeanNameResolver.java
public boolean init(ServletContext servletContext, ClassLoader classLoader) { // try to get WebApplicationContext from ServletContext webAppContext = servletContext.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT"); // Not found? Disable resolver! if (webAppContext == null) { if (log.isDebugEnabled()) { log.debug("WebApplicationContext not found in ServletContext. Resolver has been disabled."); }/*from w w w.ja v a 2 s. com*/ return false; } // catch reflection failures try { // get findBeanNamesByType method Class<?> webAppContextClass = classLoader.loadClass(WEB_APP_CONTEXT_CLASS); getBeanNamesMethod = webAppContextClass.getMethod(GET_BEAN_NAMES_METHOD, Class.class); // init successful if (log.isDebugEnabled()) { log.debug("Spring detected. Enabling Spring bean name resolving."); } return true; } catch (ClassNotFoundException e) { // will happen when Spring is not on the classpath if (log.isDebugEnabled()) { log.debug("WebApplicationContext class could not be found. Resolver has been disabled."); } } catch (NoSuchMethodException e) { // Spring is expected to offer this methods log.warn("Cannot find getBeanNamesByType() method.", e); } catch (SecurityException e) { // security issues log.warn("Unable to init resolver due to security restrictions", e); } // resolver will be disabled return false; }
From source file:org.apache.servicemix.jbi.deployer.impl.ComponentInstaller.java
private Bootstrap createBootstrap() throws DeploymentException { ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); ComponentDesc descriptor = installationContext.getDescriptor(); try {//from w w w .j a va 2 s . c o m ClassLoader cl = createClassLoader(getBundle(), installationContext.getInstallRoot(), descriptor.getBootstrapClassPath().getPathElements(), descriptor.isBootstrapClassLoaderDelegationParentFirst(), null); Thread.currentThread().setContextClassLoader(cl); Class bootstrapClass = cl.loadClass(descriptor.getBootstrapClassName()); return (Bootstrap) bootstrapClass.newInstance(); } catch (ClassNotFoundException e) { LOGGER.error("Class not found: " + descriptor.getBootstrapClassName(), e); throw new DeploymentException(e); } catch (InstantiationException e) { LOGGER.error("Could not instantiate : " + descriptor.getBootstrapClassName(), e); throw new DeploymentException(e); } catch (IllegalAccessException e) { LOGGER.error("Illegal access on: " + descriptor.getBootstrapClassName(), e); throw new DeploymentException(e); } finally { Thread.currentThread().setContextClassLoader(oldCl); } }
From source file:com.moss.nomad.core.packager.Packager.java
private MigrationResources createMigrationResources(MigrationDef def) throws Exception { ResolvedMigrationInfo info = resolver.resolve(def); /*/*w ww . j a v a 2 s .co m*/ * Determine the classpath for this migration package. */ List<ResolvedDependencyInfo> dependencyArtifacts = new ArrayList<ResolvedDependencyInfo>(); dependencyArtifacts.add(new ResolvedDependencyInfo(def.groupId(), def.artifactId(), def.version(), def.type(), def.classifier(), info.migrationArtifact())); dependencyArtifacts.addAll(info.dependencyArtifacts()); List<String> handlerClassPath = new ArrayList<String>(); for (ResolvedDependencyInfo dep : dependencyArtifacts) { StringBuilder sb = new StringBuilder(); sb.append(dep.groupId()); sb.append("/").append(dep.artifactId()); sb.append("/").append(dep.version()); sb.append("/").append(dep.artifactId()); if (dep.classifier() != null) { sb.append("-").append(dep.classifier()); } sb.append("-").append(dep.version()); sb.append(".").append(dep.type()); String pathName = sb.toString(); handlerClassPath.add(pathName); if (!dependencies.containsKey(pathName)) { dependencies.put(pathName, dep); } } /* * Determine which class is the migration handler. There can only be * one, any other case will cause an exception to be thrown. */ URL[] cp; { List<URL> urls = new ArrayList<URL>(); urls.add(info.migrationArtifact().toURL()); for (ResolvedDependencyInfo d : dependencyArtifacts) { urls.add(d.file().toURL()); } cp = urls.toArray(new URL[0]); } ClassLoader cl = new URLClassLoader(cp, null); List<String> handlerClassNames = new ArrayList<String>(); for (String jarPath : listJarPaths(info.migrationArtifact())) { if (!jarPath.endsWith(".class")) { continue; } String className = jarPath.replaceAll("\\/", ".").substring(0, jarPath.length() - 6); Class clazz = cl.loadClass(className); for (Class iface : clazz.getInterfaces()) { if (iface.getName().equals(MigrationHandler.class.getName())) { handlerClassNames.add(className); break; } } } String handlerClassName; if (handlerClassNames.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append("Could not find an implementation of "); sb.append(MigrationHandler.class.getName()); sb.append(" in migration def jar "); sb.append(def.toString()); sb.append(": there must be exactly one.\n"); throw new RuntimeException(sb.toString()); } else if (handlerClassNames.size() > 1) { StringBuilder sb = new StringBuilder(); sb.append("Found more than one implementation of "); sb.append(MigrationHandler.class.getName()); sb.append(" in migration def jar "); sb.append(def.toString()); sb.append(": there must be exactly one.\n"); for (String n : handlerClassNames) { sb.append(" --> ").append(n).append("\n"); } throw new RuntimeException(sb.toString()); } else { handlerClassName = handlerClassNames.get(0); } return new MigrationResources(handlerClassName, handlerClassPath); }
From source file:org.bytesoft.bytetcc.supports.spring.CompensableManagerPostProcessor.java
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String compensableManagerBeanName = null; String userCompensableBeanName = null; String transactionManagerBeanName = null; final List<String> beanNameList = new ArrayList<String>(); String[] beanNameArray = beanFactory.getBeanDefinitionNames(); for (int i = 0; i < beanNameArray.length; i++) { String beanName = beanNameArray[i]; BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); String beanClassName = beanDef.getBeanClassName(); Class<?> beanClass = null; try {//from w w w .ja va 2 s.c o m beanClass = cl.loadClass(beanClassName); } catch (Exception ex) { logger.debug("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex); continue; } if (org.bytesoft.bytejta.supports.jdbc.LocalXADataSource.class.equals(beanClass)) { beanNameList.add(beanName); } else if (org.bytesoft.bytetcc.UserCompensableImpl.class.equals(beanClass)) { beanNameList.add(beanName); userCompensableBeanName = beanName; } else if (org.bytesoft.bytetcc.TransactionManagerImpl.class.equals(beanClass)) { compensableManagerBeanName = beanName; } else if (org.springframework.transaction.jta.JtaTransactionManager.class.equals(beanClass)) { beanNameList.add(beanName); transactionManagerBeanName = beanName; } } if (compensableManagerBeanName == null) { throw new FatalBeanException( "No configuration of class org.bytesoft.bytetcc.TransactionManagerImpl was found."); } if (transactionManagerBeanName == null) { throw new FatalBeanException( "No configuration of org.springframework.transaction.jta.JtaTransactionManager was found."); } for (int i = 0; i < beanNameList.size(); i++) { String beanName = beanNameList.get(i); BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); MutablePropertyValues mpv = beanDef.getPropertyValues(); RuntimeBeanReference beanRef = new RuntimeBeanReference(compensableManagerBeanName); mpv.addPropertyValue("transactionManager", beanRef); } BeanDefinition transactionManagerBeanDef = beanFactory.getBeanDefinition(transactionManagerBeanName); MutablePropertyValues transactionManagerMPV = transactionManagerBeanDef.getPropertyValues(); RuntimeBeanReference userCompensableBeanRef = new RuntimeBeanReference(userCompensableBeanName); transactionManagerMPV.addPropertyValue("userTransaction", userCompensableBeanRef); }