List of usage examples for java.net URLClassLoader URLClassLoader
URLClassLoader(URL[] urls, AccessControlContext acc)
From source file:org.argouml.moduleloader.ModuleLoader2.java
/** * Find and enable a module from a given directory. * * @param dirname/*from w w w . j av a 2 s.c o m*/ * The name of the directory. */ private void huntModulesFromNamedDirectory(String dirname) { File extensionDir = new File(dirname); if (extensionDir.isDirectory()) { File[] files = extensionDir.listFiles(new JarFileFilter()); for (File file : files) { JarFile jarfile = null; // Try-catch only the JarFile instantiation so we // don't accidentally mask anything in ArgoJarClassLoader // or processJarFile. try { jarfile = new JarFile(file); if (jarfile != null) { ClassLoader classloader = new URLClassLoader(new URL[] { file.toURI().toURL(), }, getClass().getClassLoader()); try { processJarFile(classloader, file); } catch (ClassNotFoundException e) { LOG.log(Level.SEVERE, "The class is not found.", e); return; } } } catch (IOException ioe) { LOG.log(Level.SEVERE, "Cannot open Jar file " + file, ioe); } } } }
From source file:com.kjt.service.common.SoafwTesterMojo.java
public static void main(String[] args) { String[] path = { "/Users/alexzhu/soa/projects/tsl/tsl-service-impl/target/classes", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-service-impl/1.0-SNAPSHOT/soafw-common-service-impl-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-dao/1.0-SNAPSHOT/soafw-common-dao-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-config/1.0-SNAPSHOT/soafw-common-config-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/org/apache/maven/maven-plugin-api/2.0/maven-plugin-api-2.0.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-log/1.0-SNAPSHOT/soafw-common-log-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/ch/qos/logback/logback-classic/1.1.2/logback-classic-1.1.2.jar", "/Users/alexzhu/.m2/repository/ch/qos/logback/logback-core/1.1.2/logback-core-1.1.2.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-cache/1.0-SNAPSHOT/soafw-common-cache-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/danga/memcached/2.0.1/memcached-2.0.1.jar", "/Users/alexzhu/.m2/repository/redis/clients/jedis/2.6.2/jedis-2.6.2.jar", "/Users/alexzhu/.m2/repository/org/apache/commons/commons-pool2/2.0/commons-pool2-2.0.jar", "/Users/alexzhu/.m2/repository/org/aspectj/aspectjrt/1.8.4/aspectjrt-1.8.4.jar", "/Users/alexzhu/.m2/repository/org/aspectj/aspectjweaver/1.8.4/aspectjweaver-1.8.4.jar", "/Users/alexzhu/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar", "/Users/alexzhu/.m2/repository/org/mybatis/mybatis/3.2.8/mybatis-3.2.8.jar", "/Users/alexzhu/.m2/repository/commons-pool/commons-pool/1.5.4/commons-pool-1.5.4.jar", "/Users/alexzhu/.m2/repository/commons-dbcp/commons-dbcp/1.4/commons-dbcp-1.4.jar", "/Users/alexzhu/.m2/repository/org/mybatis/mybatis-spring/1.2.2/mybatis-spring-1.2.2.jar", "/Users/alexzhu/.m2/repository/org/freemarker/freemarker/2.3.16/freemarker-2.3.16.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-core/4.0.7.RELEASE/spring-core-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-context/4.0.7.RELEASE/spring-context-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-aop/4.0.7.RELEASE/spring-aop-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-beans/4.0.7.RELEASE/spring-beans-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-expression/4.0.7.RELEASE/spring-expression-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-test/4.0.7.RELEASE/spring-test-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-jdbc/4.0.7.RELEASE/spring-jdbc-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-tx/4.0.7.RELEASE/spring-tx-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-concurrent/1.0-SNAPSHOT/soafw-common-concurrent-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-mq/1.0-SNAPSHOT/soafw-common-mq-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/rabbitmq/amqp-client/3.5.0/amqp-client-3.5.0.jar", "/Users/alexzhu/.m2/repository/org/springframework/amqp/spring-amqp/1.4.3.RELEASE/spring-amqp-1.4.3.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/amqp/spring-rabbit/1.4.3.RELEASE/spring-rabbit-1.4.3.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-messaging/4.1.3.RELEASE/spring-messaging-4.1.3.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/springframework/retry/spring-retry/1.1.2.RELEASE/spring-retry-1.1.2.RELEASE.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-rpc/1.0-SNAPSHOT/soafw-common-rpc-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-service/1.0-SNAPSHOT/soafw-common-service-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-domain/1.0-SNAPSHOT/soafw-common-domain-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/common/soafw-common-util/1.0-SNAPSHOT/soafw-common-util-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/commons-lang/commons-lang/2.5/commons-lang-2.5.jar", "/Users/alexzhu/.m2/repository/commons-configuration/commons-configuration/1.6/commons-configuration-1.6.jar", "/Users/alexzhu/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar", "/Users/alexzhu/.m2/repository/commons-digester/commons-digester/1.8/commons-digester-1.8.jar", "/Users/alexzhu/.m2/repository/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar", "/Users/alexzhu/.m2/repository/commons-beanutils/commons-beanutils-core/1.8.0/commons-beanutils-core-1.8.0.jar", "/Users/alexzhu/.m2/repository/javax/mail/mail/1.4.1/mail-1.4.1.jar", "/Users/alexzhu/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar", "/Users/alexzhu/.m2/repository/org/springframework/spring-context-support/4.0.7.RELEASE/spring-context-support-4.0.7.RELEASE.jar", "/Users/alexzhu/.m2/repository/org/apache/curator/curator-framework/2.4.0/curator-framework-2.4.0.jar", "/Users/alexzhu/.m2/repository/org/apache/curator/curator-client/2.4.0/curator-client-2.4.0.jar", "/Users/alexzhu/.m2/repository/com/google/guava/guava/18.0/guava-18.0.jar", "/Users/alexzhu/.m2/repository/org/apache/curator/curator-recipes/2.4.0/curator-recipes-2.4.0.jar", "/Users/alexzhu/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-service/1.0-SNAPSHOT/tsl-service-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-domain/1.0-SNAPSHOT/tsl-domain-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-dao/1.0-SNAPSHOT/tsl-dao-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-cache/1.0-SNAPSHOT/tsl-cache-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-rpc/1.0-SNAPSHOT/tsl-rpc-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-config/1.0-SNAPSHOT/tsl-config-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-common/1.0-SNAPSHOT/tsl-common-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/kjt/service/tsl/tsl-mq/1.0-SNAPSHOT/tsl-mq-1.0-SNAPSHOT.jar", "/Users/alexzhu/.m2/repository/com/alibaba/dubbo/2.5.3/dubbo-2.5.3.jar", "/Users/alexzhu/.m2/repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar", "/Users/alexzhu/.m2/repository/org/jboss/netty/netty/3.2.5.Final/netty-3.2.5.Final.jar", "/Users/alexzhu/.m2/repository/org/apache/zookeeper/zookeeper/3.4.6/zookeeper-3.4.6.jar", "/Users/alexzhu/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar", "/Users/alexzhu/.m2/repository/jline/jline/0.9.94/jline-0.9.94.jar", "/Users/alexzhu/.m2/repository/io/netty/netty/3.7.0.Final/netty-3.7.0.Final.jar", "/Users/alexzhu/.m2/repository/com/101tec/zkclient/0.4/zkclient-0.4.jar", "/Users/alexzhu/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar", "/Users/alexzhu/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar" }; String basedPath = "/Users/alexzhu/soa/projects/tsl/tsl-service-impl"; URL[] runtimeUrls = new URL[path.length + 1]; try {/*w w w . j a va 2s . c om*/ for (int i = 0; i < path.length; i++) { runtimeUrls[i] = new File(path[i]).toURI().toURL(); // ?classpath } runtimeUrls[path.length] = new File( basedPath + File.separator + "target" + File.separator + "test-classes").toURI().toURL(); SoafwTesterMojo mojo = new SoafwTesterMojo(); mojo.cl = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader()); mojo.appendTest("com.kjt.service.tsl.CfOrderInfoServiceImpl"); } catch (Exception e2) { } }
From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java
private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException { /** Compilation Requirements *********************************************************************************************/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null); // This sets up the class path that the compiler will use. // I've added the .jar file that contains the DoStuff interface within // in it.../*from w w w.j av a 2 s . c o m*/ List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(getAllJarsClassPathInMavenLocalRepo()); optionList.add("-verbose"); File helloWorldJava = new File(classFilePathName); Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /********************************************************************************************* Compilation Requirements **/ if (task.call()) { /** Load and execute *************************************************************************************************/ // Create a new custom class loader, pointing to the directory that // contains the compiled // classes, this should point to the top of the package structure! //TODO the / separator needs to be revised to platform awared URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() }, Thread.currentThread().getContextClassLoader()); String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/"; ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent()); classLoader.loadClass(className); classLoader.close(); /************************************************************************************************* Load and execute **/ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(), diagnostic.getSource(), diagnostic.getMessage(new Locale("en"))); } } }
From source file:com.web.server.EJBDeployer.java
@Override public void fileChanged(FileChangeEvent arg0) throws Exception { try {//from w ww.j ava2 s .co m FileObject baseFile = arg0.getFile(); EJBContext ejbContext; if (baseFile.getName().getURI().endsWith(".jar")) { fileDeleted(arg0); URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config); container.inject(); Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (cls.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(baseFile.getName().getURI()); ejbContext.setJarDeployed(baseFile.getName().getBaseName()); for (Class<?> ejbInterface : cls) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put(baseFile.getName().getURI(), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(baseFile.getName().getURI()) != null) { mdbContexts = jarMDBMap.get(baseFile.getName().getURI()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(baseFile.getName().getURI(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); System.out.println(baseFile.getName().getURI() + " Deployed"); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.pentaho.platform.repository.solution.filebased.FileBasedSolutionRepository.java
protected String getLocaleString(final String key, String baseName, final ISolutionFile baseFile) { File searchDir = ((FileSolutionFile) baseFile.retrieveParent()).getFile(); try {/*from ww w . j a va 2s. c om*/ boolean searching = true; while (searching) { // look to see if this exists URLClassLoader loader = new URLClassLoader(new URL[] { searchDir.toURL() }, null); String localeText = null; try { ResourceBundle rb = ResourceBundle.getBundle(baseName, getLocale(), loader); localeText = rb.getString(key.substring(1)); } catch (Exception e) { // couldn't load bundle, move along } if (localeText != null) { return localeText; } // if we get to here, we couldn't use the resource bundle to find the string, so we will use this another approach // change the basename to messages (messages.properties) and go up a directory in our searching if (searching) { if (!baseName.equals("messages")) { //$NON-NLS-1$ baseName = "messages"; //$NON-NLS-1$ } else { if (searchDir.equals(rootFile)) { searching = false; } else { searchDir = searchDir.getParentFile(); } } } } return null; } catch (Exception e) { error(Messages.getErrorString("SolutionRepository.ERROR_0007_COULD_NOT_READ_PROPERTIES", //$NON-NLS-1$ baseFile.getFullPath()), e); } return null; }
From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java
/** * Set up a classloader for the execution of the main class. * //w w w . jav a 2 s.c o m * @return the classloader * @throws MojoExecutionException if a problem happens */ private ClassLoader getClassLoader() throws MojoExecutionException { List<URL> classpathURLs = new ArrayList<URL>(); this.addRelevantPluginDependenciesToClasspath(classpathURLs); this.addRelevantProjectDependenciesToClasspath(classpathURLs); this.addAdditionalClasspathElements(classpathURLs); if (outputDirectory.isDirectory()) { // load compiled classes Collection listFiles = FileUtils.listFiles(outputDirectory, new String[] { "class" }, true); for (Object object : listFiles) { if (object instanceof File) { File f = (File) object; if (f.isFile()) { try { classpathURLs.add(f.toURI().toURL()); } catch (Exception e) { // TODO: handle exception } } } } } return new URLClassLoader(classpathURLs.toArray(new URL[classpathURLs.size()]), getClass().getClassLoader()); }
From source file:azkaban.webapp.AzkabanWebServer.java
private void loadPluginCheckersAndActions(String pluginPath) { logger.info("Loading plug-in checker and action types"); File triggerPluginPath = new File(pluginPath); if (!triggerPluginPath.exists()) { logger.error("plugin path " + pluginPath + " doesn't exist!"); return;/* www .j ava 2 s . c om*/ } ClassLoader parentLoader = this.getClassLoader(); File[] pluginDirs = triggerPluginPath.listFiles(); ArrayList<String> jarPaths = new ArrayList<String>(); for (File pluginDir : pluginDirs) { if (!pluginDir.exists()) { logger.error("Error! Trigger plugin path " + pluginDir.getPath() + " doesn't exist."); continue; } if (!pluginDir.isDirectory()) { logger.error("The plugin path " + pluginDir + " is not a directory."); continue; } // Load the conf directory File propertiesDir = new File(pluginDir, "conf"); Props pluginProps = null; if (propertiesDir.exists() && propertiesDir.isDirectory()) { File propertiesFile = new File(propertiesDir, "plugin.properties"); File propertiesOverrideFile = new File(propertiesDir, "override.properties"); if (propertiesFile.exists()) { if (propertiesOverrideFile.exists()) { pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile); } else { pluginProps = PropsUtils.loadProps(null, propertiesFile); } } else { logger.error("Plugin conf file " + propertiesFile + " not found."); continue; } } else { logger.error("Plugin conf path " + propertiesDir + " not found."); continue; } List<String> extLibClasspath = pluginProps.getStringList("trigger.external.classpaths", (List<String>) null); String pluginClass = pluginProps.getString("trigger.class"); if (pluginClass == null) { logger.error("Trigger class is not set."); } else { logger.error("Plugin class " + pluginClass); } URLClassLoader urlClassLoader = null; File libDir = new File(pluginDir, "lib"); if (libDir.exists() && libDir.isDirectory()) { File[] files = libDir.listFiles(); ArrayList<URL> urls = new ArrayList<URL>(); for (int i = 0; i < files.length; ++i) { try { URL url = files[i].toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { logger.error(e); } } if (extLibClasspath != null) { for (String extLib : extLibClasspath) { try { File file = new File(pluginDir, extLib); URL url = file.toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { logger.error(e); } } } urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader); } else { logger.error("Library path " + propertiesDir + " not found."); continue; } Class<?> triggerClass = null; try { triggerClass = urlClassLoader.loadClass(pluginClass); } catch (ClassNotFoundException e) { logger.error("Class " + pluginClass + " not found."); continue; } String source = FileIOUtils.getSourcePathFromClass(triggerClass); logger.info("Source jar " + source); jarPaths.add("jar:file:" + source); try { Utils.invokeStaticMethod(urlClassLoader, pluginClass, "initiateCheckerTypes", pluginProps, app); } catch (Exception e) { logger.error("Unable to initiate checker types for " + pluginClass); continue; } try { Utils.invokeStaticMethod(urlClassLoader, pluginClass, "initiateActionTypes", pluginProps, app); } catch (Exception e) { logger.error("Unable to initiate action types for " + pluginClass); continue; } } }
From source file:com.flipkart.phantom.runtime.impl.spring.ServiceProxyComponentContainer.java
/** * Loads the proxy handler context from path specified in the HandlerConfigInfo. Looks for file by name ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG. * @param handlerConfigInfo containing absolute path to the proxy handler's configuration location i.e. folder *//*from w ww. j ava 2 s . c o m*/ private void loadProxyHandlerContext(HandlerConfigInfo handlerConfigInfo) { // check if a context exists already for this config path for (HandlerConfigInfo loadedHandlerConfigInfo : this.handlerConfigInfoList) { if (loadedHandlerConfigInfo.equals(handlerConfigInfo)) { handlerConfigInfo = loadedHandlerConfigInfo; break; } } if (handlerConfigInfo.getProxyHandlerContext() != null) { // close the context and remove from list handlerConfigInfo.getProxyHandlerContext().close(); this.handlerConfigInfoList.remove(handlerConfigInfo); } ClassLoader proxyHandlerCL = this.tccl; // check to see if the proxy has handler and dependent binaries deployed outside of the runtime class path. If yes, include them using a custom URL classloader. File customLibPath = new File(handlerConfigInfo.getXmlConfigFile().getParentFile(), HandlerConfigInfo.BINARIES_PATH); if (customLibPath.exists() && customLibPath.isDirectory()) { try { File[] libFiles = customLibPath.listFiles(); URL[] libURLs = new URL[libFiles.length]; for (int i = 0; i < libFiles.length; i++) { libURLs[i] = new URL(HandlerConfigInfo.FILE_PREFIX + libFiles[i].getAbsolutePath()); } proxyHandlerCL = new URLClassLoader(libURLs, this.tccl); } catch (MalformedURLException e) { throw new PlatformException(e); } } // now load the proxy handler context and add it into the handlerConfigInfoList list handlerConfigInfo.loadProxyHandlerContext(proxyHandlerCL, ServiceProxyComponentContainer.getCommonProxyHandlerBeansContext()); this.handlerConfigInfoList.add(handlerConfigInfo); }
From source file:com.aliyun.odps.mapred.LocalJobRunner.java
@SuppressWarnings("deprecation") private void processResources() throws IOException, OdpsException { String[] resources = conf.getResources(); if (resources == null || resources.length == 0) { LOG.debug("No resources to process"); return;/*from www. j a v a2s .co m*/ } Set<String> names = new HashSet<String>(Arrays.asList(resources)); LOG.info("Start to process resources: " + StringUtils.join(resources, ',')); URLClassLoader loader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); ArrayList<URL> cp = new ArrayList<URL>(Arrays.asList(loader.getURLs())); String curProjName = wareHouse.getOdps().getDefaultProject(); File resDir = jobDirecotry.getResourceDir(); for (String name : names) { List<String> res = LocalRunUtils.parseResourceName(name, curProjName); String projName = res.get(0); String resName = res.get(1); if (!wareHouse.existsResource(projName, resName) || wareHouse.getDownloadMode() == DownloadMode.ALWAYS) { DownloadUtils.downloadResource(odps, projName, resName, wareHouse.getLimitDownloadRecordCount(), wareHouse.getInputColumnSeperator()); } wareHouse.copyResource(projName, resName, resDir, wareHouse.getLimitDownloadRecordCount(), wareHouse.getInputColumnSeperator()); cp.add(new File(resDir, resName).toURI().toURL()); } URLClassLoader newLoader = new URLClassLoader(cp.toArray(new URL[0]), loader); Thread.currentThread().setContextClassLoader(newLoader); conf.setClassLoader(newLoader); }
From source file:com.ikanow.infinit.e.core.mapreduce.HadoopJobRunner.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private String runHadoopJob(CustomMapReduceJobPojo job, String tempJarLocation) throws IOException, SAXException, ParserConfigurationException { StringWriter xml = new StringWriter(); createConfigXML(xml, job.jobtitle, job.inputCollection, getQueryOrProcessing(job.query, QuerySpec.INPUTFIELDS), job.isCustomTable, job.getOutputDatabase(), job._id.toString(), job.outputCollectionTemp, job.mapper, job.reducer, job.combiner, getQueryOrProcessing(job.query, QuerySpec.QUERY), job.communityIds, job.outputKey, job.outputValue, job.arguments);// www . ja va 2 s. c o m ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader child = new URLClassLoader(new URL[] { new File(tempJarLocation).toURI().toURL() }, savedClassLoader); Thread.currentThread().setContextClassLoader(child); // Now load the XML into a configuration object: Configuration config = new Configuration(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(xml.toString().getBytes())); NodeList nList = doc.getElementsByTagName("property"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String name = getTagValue("name", eElement); String value = getTagValue("value", eElement); if ((null != name) && (null != value)) { config.set(name, value); } } } } catch (Exception e) { throw new IOException(e.getMessage()); } // Now run the JAR file try { config.setBoolean("mapred.used.genericoptionsparser", true); // (just stops an annoying warning from appearing) if (bLocalMode) { config.set("mapred.job.tracker", "local"); config.set("fs.default.name", "local"); } else { String trackerUrl = HadoopUtils.getXMLProperty( prop_custom.getHadoopConfigPath() + "/hadoop/mapred-site.xml", "mapred.job.tracker"); String fsUrl = HadoopUtils.getXMLProperty( prop_custom.getHadoopConfigPath() + "/hadoop/core-site.xml", "fs.default.name"); config.set("mapred.job.tracker", trackerUrl); config.set("fs.default.name", fsUrl); } Job hj = new Job(config); Class<?> classToLoad = Class.forName(job.mapper, true, child); hj.setJarByClass(classToLoad); hj.setInputFormatClass((Class<? extends InputFormat>) Class .forName("com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat", true, child)); if ((null != job.exportToHdfs) && job.exportToHdfs) { hj.setOutputFormatClass((Class<? extends OutputFormat>) Class .forName("org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat", true, child)); Path outPath = this.ensureOutputDirectory(job); SequenceFileOutputFormat.setOutputPath(hj, outPath); } else { // normal case, stays in MongoDB hj.setOutputFormatClass((Class<? extends OutputFormat>) Class .forName("com.mongodb.hadoop.MongoOutputFormat", true, child)); } hj.setMapperClass((Class<? extends Mapper>) Class.forName(job.mapper, true, child)); if ((null != job.reducer) && !job.reducer.equalsIgnoreCase("null") && !job.reducer.equalsIgnoreCase("none")) { hj.setReducerClass((Class<? extends Reducer>) Class.forName(job.reducer, true, child)); } else { hj.setNumReduceTasks(0); } if ((null != job.combiner) && !job.combiner.equalsIgnoreCase("null") && !job.combiner.equalsIgnoreCase("none")) { hj.setCombinerClass((Class<? extends Reducer>) Class.forName(job.combiner, true, child)); } hj.setOutputKeyClass(Class.forName(job.outputKey, true, child)); hj.setOutputValueClass(Class.forName(job.outputValue, true, child)); hj.setJobName(job.jobtitle); if (bLocalMode) { hj.waitForCompletion(false); return "local_done"; } else { hj.submit(); String jobId = hj.getJobID().toString(); return jobId; } } catch (Exception e) { e.printStackTrace(); Thread.currentThread().setContextClassLoader(savedClassLoader); return "Error: " + HarvestExceptionUtils.createExceptionMessage(e); } finally { Thread.currentThread().setContextClassLoader(savedClassLoader); } }