List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.peter.mavenrunner.MavenRunnerTopComponent.java
private void runGoal() { if (projectTree.getSelectionPath() != null) { MyTreeNode node = (MyTreeNode) projectTree.getSelectionPath().getLastPathComponent(); log("node.type=" + node.type); if (node.type.equals("goal") || node.type.equals("default goal")) { try { ClassLoader syscl = Lookup.getDefault().lookup(ClassLoader.class); List<String> goals = new ArrayList<String>(); //goals.add("-Dmaven.tomcat.port=8082"); String goalsStr[] = node.goals.split(" "); for (String goal : goalsStr) { goals.add(goal);/*w ww . ja v a 2 s. co m*/ } Class runUtils = syscl.loadClass("org.netbeans.modules.maven.api.execute.RunUtils"); Method createRunConfig = runUtils.getMethod("createRunConfig", new Class[] { File.class, Project.class, String.class, List.class }); Object rc = createRunConfig.invoke(null, FileUtil.toFile(node.project.getProjectDirectory()), node.project, node.projectInformation.getDisplayName(), goals); Class runConfig = syscl.loadClass("org.netbeans.modules.maven.api.execute.RunConfig"); // maven properties Method setProperty = runConfig.getMethod("addProperties", new Class[] { Map.class }); Map<String, String> properties = new HashMap<String, String>(); for (String property : node.properties) { String s[] = property.split("="); if (s.length >= 2) { properties.put(s[0], s[1]); } } if (node.skipTests) { properties.put("maven.test.skip", "true"); } setProperty.invoke(rc, properties); // maven profile log("node.profile=" + node.profile); if (!node.profile.trim().equals("")) { Method setActivatedProfiles = runConfig.getMethod("setActivatedProfiles", new Class[] { java.util.List.class }); List<String> profiles = new ArrayList<String>(); profiles.add(node.profile); setActivatedProfiles.invoke(rc, profiles); } Method executeMaven = runUtils.getMethod("executeMaven", new Class[] { runConfig }); executeMaven.invoke(null, rc); } catch (Exception ex) { log(ExceptionUtils.getStackTrace(ex)); ex.printStackTrace(); } } else { //JOptionPane.showMessageDialog(this, "Wrong tree node type, it is not a maven goal", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Please select a goal in tree", "Error", JOptionPane.ERROR_MESSAGE); } }
From source file:com.wavemaker.tools.project.upgrade.five_dot_zero.AddServiceWireUpgradeTask.java
/** * Actually do the upgrade.// w w w .ja va2 s .co m */ private void upgradeServices(DesignServiceManager dsm, Project project, UpgradeInfo upgradeInfo) { List<String> touchedServices = new ArrayList<String>(); ClassLoader cl = ProjectUtils.getClassLoaderForProject(project); for (Service service : dsm.getServices()) { // ignore runtimeService if (DesignServiceManager.RUNTIME_SERVICE_ID.equals(service.getId())) { continue; } if (service.getSpringFile() == null) { throw new WMRuntimeException(MessageResource.ADD_SRV_UPGRADE_NO_SPRING_FILE, project.getProjectName()); } try { File springFile = dsm.getServiceRuntimeFolder(service.getId()).getFile(service.getSpringFile()); if (!springFile.exists()) { DesignServiceManager.generateSpringServiceConfig(service.getId(), service.getClazz(), dsm.getDesignServiceType(service.getType()), springFile, project); continue; } Beans beans = SpringConfigSupport.readBeans(springFile); boolean foundServiceWire = false; for (Bean bean : beans.getBeanList()) { if (bean.getClazz() != null) { Class<?> klass = cl.loadClass(bean.getClazz()); Class<?> serviceWireClass = cl.loadClass(ServiceWire.class.getName()); if (serviceWireClass.isAssignableFrom(klass)) { foundServiceWire = true; break; } } } if (!foundServiceWire) { Bean serviceWireBean = DesignServiceManager .generateServiceWireBean(dsm.getDesignServiceType(service.getType()), service.getId()); beans.addBean(serviceWireBean); SpringConfigSupport.writeBeans(beans, springFile); touchedServices.add(service.getId()); } } catch (JAXBException e) { throw new WMRuntimeException(e); } catch (IOException e) { throw new WMRuntimeException(e); } catch (ClassNotFoundException e) { throw new WMRuntimeException(e); } } if (!touchedServices.isEmpty()) { upgradeInfo.addMessage("New ServiceWire added to services: " + StringUtils.join(touchedServices, ", ")); } }
From source file:hermes.impl.LoaderSupport.java
/** * Return ClassLoader given the list of ClasspathConfig instances. The * resulting loader can then be used to instantiate providers from those * libraries./*from ww w.ja v a 2 s. co m*/ */ static List lookForFactories(final List loaderConfigs, final ClassLoader baseLoader) throws IOException { final List rval = new ArrayList(); for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) { final ClasspathConfig lConfig = (ClasspathConfig) iter.next(); if (lConfig.getFactories() != null) { log.debug("using cached " + lConfig.getFactories()); for (StringTokenizer tokens = new StringTokenizer(lConfig.getFactories(), ","); tokens .hasMoreTokens();) { rval.add(tokens.nextToken()); } } else if (lConfig.isNoFactories()) { log.debug("previously scanned " + lConfig.getJar()); } else { Runnable r = new Runnable() { public void run() { final List localFactories = new ArrayList(); boolean foundFactory = false; StringBuffer factoriesAsString = null; try { log.debug("searching " + lConfig.getJar()); ClassLoader l = createClassLoader(loaderConfigs, baseLoader); JarFile jarFile = new JarFile(lConfig.getJar()); ProgressMonitor monitor = null; int entryNumber = 0; if (HermesBrowser.getBrowser() != null) { monitor = new ProgressMonitor(HermesBrowser.getBrowser(), "Looking for factories in " + lConfig.getJar(), "Scanning...", 0, jarFile.size()); monitor.setMillisToDecideToPopup(0); monitor.setMillisToPopup(0); monitor.setProgress(0); } for (Enumeration iter = jarFile.entries(); iter.hasMoreElements();) { ZipEntry entry = (ZipEntry) iter.nextElement(); entryNumber++; if (monitor != null) { monitor.setProgress(entryNumber); monitor.setNote("Checking entry " + entryNumber + " of " + jarFile.size()); } if (entry.getName().endsWith(".class")) { String s = entry.getName().substring(0, entry.getName().indexOf(".class")); s = s.replaceAll("/", "."); try { if (s.startsWith("hermes.browser") || s.startsWith("hermes.impl") || s.startsWith("javax.jms")) { // NOP } else { Class clazz = l.loadClass(s); if (!clazz.isInterface()) { if (implementsOrExtends(clazz, ConnectionFactory.class)) { foundFactory = true; localFactories.add(s); if (factoriesAsString == null) { factoriesAsString = new StringBuffer(); factoriesAsString.append(clazz.getName()); } else { factoriesAsString.append(",").append(clazz.getName()); } log.debug("found " + clazz.getName()); } } /** * TODO: remove Class clazz = l.loadClass(s); * Class[] interfaces = clazz.getInterfaces(); * for (int i = 0; i < interfaces.length; i++) { * if * (interfaces[i].equals(TopicConnectionFactory.class) || * interfaces[i].equals(QueueConnectionFactory.class) || * interfaces[i].equals(ConnectionFactory.class)) { * foundFactory = true; localFactories.add(s); * if (factoriesAsString == null) { * factoriesAsString = new * StringBuffer(clazz.getName()); } else { * factoriesAsString.append(",").append(clazz.getName()); } * log.debug("found " + clazz.getName()); } } */ } } catch (Throwable t) { // NOP } } } } catch (IOException e) { log.error("unable to access jar/zip " + lConfig.getJar() + ": " + e.getMessage(), e); } if (!foundFactory) { lConfig.setNoFactories(true); } else { lConfig.setFactories(factoriesAsString.toString()); rval.addAll(localFactories); } } }; r.run(); } } return rval; }
From source file:com.moviejukebox.scanner.artwork.ArtworkScanner.java
/** * Set the Image Plugin// w w w . jav a 2s . co m * * @param classNameString */ protected void setImagePlugin(String classNameString) { String className; if (StringTools.isNotValidString(classNameString)) { // Use the default image plugin className = PropertiesUtil.getProperty("mjb.image.plugin", "com.moviejukebox.plugin.DefaultImagePlugin"); } else { className = classNameString; } try { Thread artThread = Thread.currentThread(); ClassLoader cl = artThread.getContextClassLoader(); Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className) .asSubclass(MovieImagePlugin.class); artworkImagePlugin = pluginClass.newInstance(); return; } catch (ClassNotFoundException ex) { LOG.error("Error instantiating imagePlugin: {} - class not found!", className); LOG.error(SystemTools.getStackTrace(ex)); } catch (InstantiationException ex) { LOG.error("Failed instantiating imagePlugin: {}", className); LOG.error(SystemTools.getStackTrace(ex)); } catch (IllegalAccessException ex) { LOG.error("Unable instantiating imagePlugin: {}", className); LOG.error(SystemTools.getStackTrace(ex)); } LOG.error("Default plugin will be used instead."); // Use the background plugin for fanart, the image plugin for all others if (artworkType == ArtworkType.FANART) { artworkImagePlugin = new DefaultBackgroundPlugin(); } else { artworkImagePlugin = new DefaultImagePlugin(); } }
From source file:com.amalto.core.storage.hibernate.SystemScatteredTypeMapping.java
private Object getReferencedObject(ClassLoader storageClassLoader, Session session, ComplexTypeMetadata referencedType, Object referencedIdValue) { Class<?> referencedClass; try {//from www .j a v a 2 s.co m referencedClass = ((StorageClassLoader) storageClassLoader).getClassFromType(referencedType); } catch (Exception e) { throw new RuntimeException("Could not get class for type '" + referencedType.getName() + "'", e); } try { if (referencedIdValue == null) { return null; // Means no reference (reference is null). } if (referencedIdValue instanceof Wrapper) { return referencedIdValue; // It's already the referenced object. } // Try to load object from current session if (referencedIdValue instanceof List) { // Handle composite id values Serializable result; try { Class<?> idClass = storageClassLoader.loadClass(referencedClass.getName() + "_ID"); //$NON-NLS-1$ Class[] parameterClasses = new Class[((List) referencedIdValue).size()]; int i = 0; for (Object o : (List) referencedIdValue) { if (o == null) { throw new IllegalStateException("Id cannot have a null value."); } parameterClasses[i++] = o.getClass(); } Constructor<?> constructor = idClass.getConstructor(parameterClasses); result = (Serializable) constructor.newInstance(((List) referencedIdValue).toArray()); } catch (Exception e) { throw new RuntimeException(e); } Serializable referencedValueId = result; Object sessionObject = session.load(referencedClass, referencedValueId); if (sessionObject != null) { return sessionObject; } } else if (referencedIdValue instanceof Serializable) { Object sessionObject = session.load(referencedClass, (Serializable) referencedIdValue); if (sessionObject != null) { return sessionObject; } } else { throw new NotImplementedException("Unexpected state."); } Class<?> fieldJavaType = referencedIdValue.getClass(); // Null package might happen with proxy classes generated by Hibernate if (fieldJavaType.getPackage() != null && fieldJavaType.getPackage().getName().startsWith("java.")) { //$NON-NLS-1$ Wrapper referencedObject = (Wrapper) referencedClass.newInstance(); for (FieldMetadata fieldMetadata : referencedType.getFields()) { if (fieldMetadata.isKey()) { referencedObject.set(fieldMetadata.getName(), referencedIdValue); } } return referencedObject; } else { return referencedIdValue; } } catch (Exception e) { throw new RuntimeException("Could not create referenced object of type '" + referencedClass + "' with id '" + String.valueOf(referencedIdValue) + "'", e); } }
From source file:com.redhat.rhn.frontend.taglibs.list.ListTag.java
private ListDecorator getDecorator(String decName) throws JspException { if (decName != null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try {//from w w w . j av a2 s.c o m if (decName.indexOf('.') == -1) { decName = "com.redhat.rhn.frontend.taglibs.list.decorators." + decName; } ListDecorator dec = (ListDecorator) cl.loadClass(decName).newInstance(); ListSetTag parent = (ListSetTag) BodyTagSupport.findAncestorWithClass(this, ListSetTag.class); dec.setEnvironment(pageContext, parent, getUniqueName()); return dec; } catch (Exception e) { String msg = "Exception while adding Decorator [" + decName + "]"; throw new JspException(msg, e); } } return null; }
From source file:com.sureassert.uc.runtime.PersistentDataFactory.java
private List<SaUCStub> getCurrentUCMethodStubs(Signature method) { List<SaUCStub> stubs = null; if (currentTestType == TestType.USE_CASE) { // Check for method stub defined using full class name stubs = ucRuntimeStoreByMethodName.get(CURRENT_UC).getStubs(method.getClassMethodNameKey()); if (stubs == null) { // Check for method stub defined for superclasses try { ClassLoader cl = PersistentDataFactory.getInstance().getCurrentProjectClassLoader(); Class<?> clazz = cl.loadClass(method.getClassName()); Set<Class<?>> superClasses = BasicUtils.getSuperClassAndInterfaces(clazz, true, false); for (Class<?> superClass : superClasses) { if (stubs == null) { stubs = ucRuntimeStoreByMethodName.get(CURRENT_UC).getStubs(// Signature.getClassMethodNameKey(superClass, method.getMemberName())); }/*from ww w .ja va2s .c o m*/ } } catch (Exception e) { BasicUtils.debug(ExceptionUtils.getFullStackTrace(e)); } } } else { if (ucRuntimeStoreByMethodName.isEmpty()) { return null; } // Determine which test method is being executed UCRuntimeStore methodStubStore = ucRuntimeStoreByMethodName.get(currentJUnitMethodName); if (methodStubStore != null && method != null) { stubs = methodStubStore.getStubs(method.getClassMethodNameKey()); if (stubs == null) { stubs = methodStubStore.getStubs(method.getSimpleClassMethodNameKey()); } } } return stubs; }
From source file:com.buaa.cfs.security.UserGroupInformation.java
@SuppressWarnings("unchecked") private static Class<? extends Principal> getOsPrincipalClass() { ClassLoader cl = ClassLoader.getSystemClassLoader(); try {//from w w w . j a va 2 s . c o m String principalClass = null; if (IBM_JAVA) { if (is64Bit) { principalClass = "com.ibm.security.auth.UsernamePrincipal"; } else { if (windows) { principalClass = "com.ibm.security.auth.NTUserPrincipal"; } else if (aix) { principalClass = "com.ibm.security.auth.AIXPrincipal"; } else { principalClass = "com.ibm.security.auth.LinuxPrincipal"; } } } else { principalClass = windows ? "com.sun.security.auth.NTUserPrincipal" : "com.sun.security.auth.UnixPrincipal"; } return (Class<? extends Principal>) cl.loadClass(principalClass); } catch (ClassNotFoundException e) { LOG.error("Unable to find JAAS classes:" + e.getMessage()); } return null; }
From source file:com.bfd.harpc.config.ClientConfig.java
/** * client/*from w w w . j a v a 2 s . c om*/ * <p> * * @param classLoader * @param ifaceClass * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException */ @SuppressWarnings("unchecked") protected GenericKeyedObjectPool<ServerNode, T> bulidClientPool(ClassLoader classLoader, Class<?> ifaceClass) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // poolConfig GenericKeyedObjectPool.Config poolConfig = new GenericKeyedObjectPool.Config(); poolConfig.maxActive = maxActive; poolConfig.maxIdle = maxIdle; poolConfig.minIdle = minIdle; poolConfig.maxWait = maxWait; poolConfig.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; poolConfig.testWhileIdle = testWhileIdle; if (StringUtils.equalsIgnoreCase(protocol, "thrift")) { // Client.Factory Class<TServiceClientFactory<TServiceClient>> fi = (Class<TServiceClientFactory<TServiceClient>>) classLoader .loadClass(findOutClassName() + "$Client$Factory"); TServiceClientFactory<TServiceClient> clientFactory = fi.newInstance(); TServiceClientPoolFactory<T> clientPool = new TServiceClientPoolFactory<T>(clientFactory, timeout); return new GenericKeyedObjectPool<ServerNode, T>(clientPool, poolConfig); } else if (StringUtils.equalsIgnoreCase(protocol, "avro")) { AvroClientPoolFactory<T> clientPool = new AvroClientPoolFactory<T>(timeout, ifaceClass); return new GenericKeyedObjectPool<ServerNode, T>(clientPool, poolConfig); } else { throw new RpcException(RpcException.CONFIG_EXCEPTION, "Unsupport protocal,please check the params 'protocal'!"); } }
From source file:org.bytesoft.bytetcc.supports.dubbo.DubboConfigPostProcessor.java
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); List<BeanDefinition> appNameList = new ArrayList<BeanDefinition>(); List<BeanDefinition> providerList = new ArrayList<BeanDefinition>(); List<BeanDefinition> consumerList = new ArrayList<BeanDefinition>(); List<BeanDefinition> protocolList = new ArrayList<BeanDefinition>(); List<BeanDefinition> registryList = new ArrayList<BeanDefinition>(); Map<String, BeanDefinition> serviceMap = new HashMap<String, BeanDefinition>(); Map<String, BeanDefinition> referenceMap = new HashMap<String, BeanDefinition>(); Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>(); Map<String, BeanDefinition> compensableMap = new HashMap<String, BeanDefinition>(); 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 {/* w w w . j a v a2 s . c o m*/ beanClass = cl.loadClass(beanClassName); } catch (Exception ex) { logger.warn("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex); continue; } clazzMap.put(beanClassName, beanClass); if (beanClass.getAnnotation(Compensable.class) != null) { compensableMap.put(beanName, beanDef); } } for (int i = 0; i < beanNameArray.length; i++) { String beanName = beanNameArray[i]; BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); String beanClassName = beanDef.getBeanClassName(); Class<?> beanClass = clazzMap.get(beanClassName); if (com.alibaba.dubbo.config.ApplicationConfig.class.equals(beanClass)) { appNameList.add(beanDef); } else if (com.alibaba.dubbo.config.ProtocolConfig.class.equals(beanClass)) { protocolList.add(beanDef); } else if (com.alibaba.dubbo.config.RegistryConfig.class.equals(beanClass)) { registryList.add(beanDef); } else if (com.alibaba.dubbo.config.ProviderConfig.class.equals(beanClass)) { providerList.add(beanDef); } else if (com.alibaba.dubbo.config.ConsumerConfig.class.equals(beanClass)) { consumerList.add(beanDef); } else if (com.alibaba.dubbo.config.spring.ServiceBean.class.equals(beanClass)) { MutablePropertyValues mpv = beanDef.getPropertyValues(); PropertyValue ref = mpv.getPropertyValue("ref"); RuntimeBeanReference beanRef = (RuntimeBeanReference) ref.getValue(); String refBeanName = beanRef.getBeanName(); if (compensableMap.containsKey(refBeanName) == false) { continue; } serviceMap.put(beanName, beanDef); } else if (com.alibaba.dubbo.config.spring.ReferenceBean.class.equals(beanClass)) { MutablePropertyValues mpv = beanDef.getPropertyValues(); PropertyValue group = mpv.getPropertyValue("group"); if (group == null || group.getValue() == null || "org.bytesoft.bytetcc".equals(group.getValue()) == false) { continue; } referenceMap.put(beanName, beanDef); } } Set<BeanDefinition> providerSet = new HashSet<BeanDefinition>(); Set<BeanDefinition> protocolSet = new HashSet<BeanDefinition>(); for (Iterator<Map.Entry<String, BeanDefinition>> itr = serviceMap.entrySet().iterator(); itr.hasNext();) { Map.Entry<String, BeanDefinition> entry = itr.next(); BeanDefinition beanDef = entry.getValue(); MutablePropertyValues mpv = beanDef.getPropertyValues(); PropertyValue provider = mpv.getPropertyValue("provider"); PropertyValue protocol = mpv.getPropertyValue("protocol"); String providerValue = provider == null ? null : String.valueOf(provider.getValue()); if (providerValue == null) { if (providerList.size() > 0) { providerSet.add(providerList.get(0)); } } else if ("N/A".equals(providerValue) == false) { String[] keyArray = providerValue.split("\\s*,\\s*"); for (int j = 0; j < keyArray.length; j++) { String key = keyArray[j]; BeanDefinition def = beanFactory.getBeanDefinition(key); providerSet.add(def); } } String protocolValue = protocol == null ? null : String.valueOf(protocol.getValue()); if (protocolValue == null) { if (protocolList.size() > 0) { protocolSet.add(protocolList.get(0)); } } else if ("N/A".equals(protocolValue) == false) { String[] keyArray = protocolValue.split("\\s*,\\s*"); for (int i = 0; i < keyArray.length; i++) { String key = keyArray[i]; BeanDefinition def = beanFactory.getBeanDefinition(key); protocolSet.add(def); } } } ApplicationConfigValidator appConfigValidator = new ApplicationConfigValidator(); appConfigValidator.setDefinitionList(appNameList); appConfigValidator.validate(); if (protocolList.size() == 0) { throw new FatalBeanException("There is no protocol config specified!"); } for (Iterator<BeanDefinition> itr = protocolSet.iterator(); itr.hasNext();) { BeanDefinition beanDef = itr.next(); ProtocolConfigValidator validator = new ProtocolConfigValidator(); validator.setBeanDefinition(beanDef); validator.validate(); } for (Iterator<BeanDefinition> itr = providerSet.iterator(); itr.hasNext();) { BeanDefinition beanDef = itr.next(); ProviderConfigValidator validator = new ProviderConfigValidator(); validator.setBeanDefinition(beanDef); validator.validate(); } for (Iterator<Map.Entry<String, BeanDefinition>> itr = serviceMap.entrySet().iterator(); itr.hasNext();) { Map.Entry<String, BeanDefinition> entry = itr.next(); ServiceConfigValidator validator = new ServiceConfigValidator(); validator.setBeanName(entry.getKey()); validator.setBeanDefinition(entry.getValue()); validator.validate(); // retries, loadbalance, cluster, filter, group } for (Iterator<Map.Entry<String, BeanDefinition>> itr = referenceMap.entrySet().iterator(); itr.hasNext();) { Map.Entry<String, BeanDefinition> entry = itr.next(); ReferenceConfigValidator validator = new ReferenceConfigValidator(); validator.setBeanName(entry.getKey()); validator.setBeanDefinition(entry.getValue()); validator.validate(); // retries, loadbalance, cluster, filter } }