List of usage examples for java.net URLClassLoader URLClassLoader
URLClassLoader(URL[] urls, AccessControlContext acc)
From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java
private static Class<?> compileClassJavac(String name, String src) { try {// ww w . j a va 2s. com //create working dir on demand if (_workingDir == null) createWorkingDir(); //write input file (for debugging / classpath handling) File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java"); if (!ftmp.getParentFile().exists()) ftmp.getParentFile().mkdirs(); LocalFileUtils.writeTextFile(ftmp, src); //get system java compiler JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) throw new RuntimeException("Unable to obtain system java compiler."); //prepare file manager DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); //prepare input source code Iterable<? extends JavaFileObject> sources = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(ftmp)); //prepare class path URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation(); String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath(); List<String> options = Arrays.asList("-classpath", classpath); //compile source code CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources); Boolean success = task.call(); //output diagnostics and error handling for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if (tmp.getKind() == Kind.ERROR) System.err.println("ERROR: " + tmp.toString()); if (success == null || !success) throw new RuntimeException("Failed to compile class " + name); //dynamically load compiled class URLClassLoader classLoader = null; try { classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir }, CodegenUtils.class.getClassLoader()); return classLoader.loadClass(name); } finally { IOUtilFunctions.closeSilently(classLoader); } } catch (Exception ex) { LOG.error("Failed to compile class " + name + ": \n" + src); throw new DMLRuntimeException("Failed to compile class " + name + ".", ex); } }
From source file:org.gradle.groovy.scripts.DefaultScriptCompilationHandler.java
public <T extends Script> Class<? extends T> loadFromDir(ScriptSource source, ClassLoader classLoader, File scriptCacheDir, Class<T> scriptBaseClass) { if (new File(scriptCacheDir, EMPTY_SCRIPT_MARKER_FILE_NAME).isFile()) { return new AsmBackedEmptyScriptGenerator().generate(scriptBaseClass); }//w ww .j a v a 2 s . c o m try { URLClassLoader urlClassLoader = new URLClassLoader(WrapUtil.toArray(scriptCacheDir.toURI().toURL()), classLoader); return urlClassLoader.loadClass(source.getClassName()).asSubclass(scriptBaseClass); } catch (Exception e) { throw new GradleException(String.format( "Could not load compiled classes for %s from cache.\n" + "*****\n" + "Sometimes this error occurs when the cache was tinkered with.\n" + "You may try to resolve it by deleting this folder:\n" + "%s\n" + "*****\n", source.getDisplayName(), scriptCacheDir.getAbsolutePath()), e); } }
From source file:org.assertj.maven.AssertJAssertionsGeneratorMojo.java
@SuppressWarnings("unchecked") private ClassLoader getProjectClassLoader() throws DependencyResolutionRequiredException, MalformedURLException { List<String> classpathElements = new ArrayList<String>(project.getCompileClasspathElements()); classpathElements.addAll(project.getTestClasspathElements()); List<URL> classpathElementUrls = new ArrayList<URL>(classpathElements.size()); for (int i = 0; i < classpathElements.size(); i++) { classpathElementUrls.add(new File(classpathElements.get(i)).toURI().toURL()); }//from ww w.j a v a 2 s .com return new URLClassLoader(classpathElementUrls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader()); }
From source file:com.googlecode.psiprobe.AbstractTomcatContainer.java
/** * Compiles a list of JSPs. Names of JSP files are expected to be relative to the webapp root. The method * updates summary with compilation details. * * @param context// w ww. j a v a 2 s .c o m * @param summary * @param names */ public void recompileJsps(Context context, Summary summary, List names) { ServletConfig servletConfig = (ServletConfig) context.findChild("jsp"); if (servletConfig != null) { if (summary != null) { synchronized (servletConfig) { ServletContext sctx = context.getServletContext(); Options opt = new EmbeddedServletOptions(servletConfig, sctx); JspRuntimeContext jrctx = new JspRuntimeContext(sctx, opt); try { // // we need to pass context classloader here, so the jsps can reference /WEB-INF/classes and // /WEB-INF/lib. JspCompilationContext would only take URLClassLoader, so we fake it // URLClassLoader classLoader = new URLClassLoader(new URL[] {}, context.getLoader().getClassLoader()); for (Iterator it = names.iterator(); it.hasNext();) { String name = (String) it.next(); long time = System.currentTimeMillis(); JspCompilationContext jcctx = createJspCompilationContext(name, false, opt, sctx, jrctx, classLoader); ClassLoader prevCl = ClassUtils.overrideThreadContextClassLoader(classLoader); try { Item item = (Item) summary.getItems().get(name); if (item != null) { try { org.apache.jasper.compiler.Compiler c = jcctx.createCompiler(); c.compile(); item.setState(Item.STATE_READY); item.setException(null); logger.info("Compiled " + name + ": OK"); } catch (Exception e) { item.setState(Item.STATE_FAILED); item.setException(e); logger.info("Compiled " + name + ": FAILED", e); } item.setCompileTime(System.currentTimeMillis() - time); } else { logger.error(name + " is not on the summary list, ignored"); } } finally { ClassUtils.overrideThreadContextClassLoader(prevCl); } } } finally { jrctx.destroy(); } } } else { logger.error("summary is null for " + context.getName() + ", request ignored"); } } else { logger.error("Context " + context.getName() + " does not have \"jsp\" servlet"); } }
From source file:org.mc4j.ems.connection.support.classloader.ClassLoaderFactory.java
public ClassLoader buildClassLoader(ConnectionSettings settings) { String tempDirString = (String) settings.getControlProperties().get(ConnectionFactory.JAR_TEMP_DIR); File tempDir = null;//from w w w.jav a 2 s . c om if (tempDirString != null) { tempDir = new File(tempDirString); } Boolean useContextClassLoader = Boolean.valueOf( settings.getAdvancedProperties().getProperty(ConnectionFactory.USE_CONTEXT_CLASSLOADER, "false")); if (useContextClassLoader.booleanValue()) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); URL implURL = storeImplToTemp("org-mc4j-ems-impl.jar", tempDir); ClassLoader loader = new URLClassLoader(new URL[] { implURL }, contextClassLoader); return loader; } List<URL> entries = new ArrayList<URL>(); if (settings.getClassPathEntries() != null) { for (File file : settings.getClassPathEntries()) { try { if (Boolean.valueOf(settings.getControlProperties() .getProperty(ConnectionFactory.COPY_JARS_TO_TEMP, "false"))) { entries.add(getCachedTempForFile(file, tempDir)); } else { entries.add(file.toURI().toURL()); } } catch (MalformedURLException e) { throw new EmsConnectException("Unable to read class path library url", e); } } } // Now load in the implementation jar // URL implURL = new URL(null, "deepjar://org-mc4j-ems-impl.jar", new Handler()); URL implURL = storeImplToTemp("org-mc4j-ems-impl.jar", tempDir); entries.add(implURL); if (settings.getConnectionType() instanceof LocalVMTypeDescriptor) { // Need tools.jar if its not already loaded try { Class.forName("com.sun.tools.attach.VirtualMachine"); } catch (ClassNotFoundException e) { // Try to load tools.jar File toolsJar = null; toolsJar = findToolsJarForHome(System.getProperty("java.home")); if (toolsJar == null) { toolsJar = findToolsJarForHome(System.getProperty("env_java_home")); } if (toolsJar != null) { try { log.debug("Found tools.jar at " + toolsJar.getPath()); entries.add(toolsJar.toURI().toURL()); } catch (MalformedURLException e1) { /* Unnexpected */ } } else { throw new EmsConnectException( "Unable to find tools.jar. Add it to your classpath to use Sun local vm connections."); } } } // Add internal support jars for JSR160 on < jdk5 if ((settings.getConnectionType() instanceof JSR160ConnectionTypeDescriptor) && settings.getConnectionType().getConnectionClasspathEntries() == null && Double.parseDouble(System.getProperty("java.version").substring(0, 3)) < 1.5) { entries.add(storeImplToTemp("lib/jsr160-includes/mx4j.jar", tempDir)); entries.add(storeImplToTemp("lib/jsr160-includes/mx4j-remote.jar", tempDir)); } // TODO: Check if file exists, log warning if not URL[] entryArray = entries.toArray(new URL[entries.size()]); ClassLoader loader = null; long key = Arrays.hashCode(entryArray); WeakReference<ClassLoader> loaderReference = classLoaderCache.get(key); if (loaderReference != null) { loader = classLoaderCache.get(key).get(); } if (loader == null) { // WARNING: Relatively disgusting hack. hiding classes is not a good thing if (settings.getConnectionType().isUseChildFirstClassLoader()) { loader = new ChildFirstClassloader(entryArray, ClassLoaderFactory.class.getClassLoader()); } else { // TODO was NestedJarClassLoader //loader = new ChildFirstClassloader(entryArray, ClassLoaderFactory.class.getClassLoader()); loader = new URLClassLoader(entryArray, ClassLoaderFactory.class.getClassLoader()); //loader = new NestedJarClassLoader(entryArray, ClassLoaderFactory.class.getClassLoader()); } classLoaderCache.put(key, new WeakReference<ClassLoader>(loader)); if (log.isDebugEnabled()) { StringBuffer buf = new StringBuffer("Classloader built with: \n"); for (URL url : entries) { buf.append("\t").append(url).append("\n"); } log.info(buf.toString()); } } return loader; }
From source file:org.forgerock.openidm.servletregistration.impl.ServletRegistrationSingleton.java
/** * Registers a servlet filter configuration * @param config the filter configuration * @return the registered Filter/*from www . ja v a 2 s. co m*/ * @throws Exception */ private Filter registerFilterWithWebContainer(JsonValue config) throws Exception { // Get required info from config String filterClass = config.get(SERVLET_FILTER_CLASS).required().asString(); logger.info("Using filter class: {}", filterClass); List<URL> urls = config.get(SERVLET_FILTER_CLASS_PATH_URLS) .asList(new Function<JsonValue, URL, JsonValueException>() { @Override public URL apply(JsonValue jsonValue) throws JsonValueException { return jsonValue.asURL(); } }); logger.info("Added URLs { {} })) to filter classpath", StringUtils.join(urls, ", ")); Map<String, Object> preInvokeReqAttributes = config.get(SERVLET_FILTER_PRE_INVOKE_ATTRIBUTES).asMap(); // Servlet names this filter should apply to, e.g. one could also add "OpenIDM Web" List<String> servletNames = config.get(SERVLET_FILTER_SERVLET_NAMES) .defaultTo(Arrays.asList(DEFAULT_SERVLET_NAME)).asList(String.class); // URL patterns to apply the filter to, e.g. one could also add "/openidmui/*"); List<String> urlPatterns = config.get(SERVLET_FILTER_URL_PATTERNS) .defaultTo(Arrays.asList(DEFAULT_SERVLET_URL_PATTERNS)).asList(String.class); // Filter init params, a string to string map JsonValue rawInitParams = config.get("initParams"); Map<String, String> initParams = new HashMap<>(); for (String initParamKey : rawInitParams.keys()) { initParams.put(initParamKey, rawInitParams.get(initParamKey).asString()); } // Create a classloader and dynamically create the requested filter Filter filter = null; ClassLoader filterCL = null; ClassLoader origCL = Thread.currentThread().getContextClassLoader(); try { filterCL = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(filterCL); filter = (Filter) (Class.forName(filterClass, true, filterCL).newInstance()); } catch (Exception ex) { logger.warn("Configured class {} failed to load from configured class path URLs {}", new Object[] { filterClass, urls, ex }); throw ex; } finally { Thread.currentThread().setContextClassLoader(origCL); } // Create filter Filter proxiedFilter = (Filter) Proxy.newProxyInstance(filter.getClass().getClassLoader(), new Class[] { Filter.class }, new FilterProxy(filter, filterCL, preInvokeReqAttributes)); // Register filter webContainer.registerFilter(proxiedFilter, urlPatterns.toArray(new String[urlPatterns.size()]), servletNames.toArray(new String[servletNames.size()]), new Hashtable<String, Object>(initParams), webContainer.getDefaultSharedHttpContext()); return proxiedFilter; }
From source file:org.mitre.ccv.mapred.CalculateKmerProbabilities.java
@Override public int run(String[] args) throws Exception { JobConf conf = new JobConf(getConf()); boolean cleanLogs = false; int start = CalculateKmerCounts.DEFAULT_START; int end = CalculateKmerCounts.DEFAULT_END; int length = -1; // @TODO: use commons getopts List<String> other_args = new ArrayList<String>(); for (int i = 0; i < args.length; ++i) { try {/*from ww w . j a v a 2 s .c o m*/ if ("-m".equals(args[i])) { conf.setNumMapTasks(Integer.parseInt(args[++i])); } else if ("-r".equals(args[i])) { conf.setNumReduceTasks(Integer.parseInt(args[++i])); } else if ("-s".equals(args[i])) { start = Integer.parseInt(args[++i]); } else if ("-e".equals(args[i])) { end = Integer.parseInt(args[++i]); } else if ("-c".equals(args[i])) { cleanLogs = true; } else if ("-l".equals(args[i])) { length = Integer.parseInt(args[++i]); } else if ("-libjars".equals(args[i])) { conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf)); URL[] libjars = FileUtils.getLibJars(conf); if (libjars != null && libjars.length > 0) { // Add libjars to client/tasks classpath conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader())); // Adds libjars to our classpath Thread.currentThread().setContextClassLoader( new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader())); } } else { other_args.add(args[i]); } } catch (NumberFormatException except) { System.out.println("ERROR: Integer expected instead of " + args[i]); return printUsage(); } catch (ArrayIndexOutOfBoundsException except) { System.out.println("ERROR: Required parameter missing from " + args[i - 1]); return printUsage(); } } // Make sure there are exactly 2 parameters left. if (other_args.size() != 2) { System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2."); return printUsage(); } if (length <= 0) { System.out.println("ERROR: Requires total length of sequence to be > 0"); return printUsage(); } //return initJob(conf, inTable, sb.toString().trim(), new Path(other_args.get(1))); return initJob(conf, start, end, length, other_args.get(0), other_args.get(1), cleanLogs); }
From source file:org.mitre.ccv.mapred.CalculateKmerPiValues.java
@Override public int run(String[] args) throws Exception { JobConf conf = new JobConf(getConf()); boolean cleanLogs = false; Integer start = CalculateKmerCounts.DEFAULT_START; Integer end = CalculateKmerCounts.DEFAULT_END; List<String> other_args = new ArrayList<String>(); for (int i = 0; i < args.length; ++i) { try {//w ww.j a va 2s . com if ("-m".equals(args[i])) { conf.setNumMapTasks(Integer.parseInt(args[++i])); } else if ("-r".equals(args[i])) { conf.setNumReduceTasks(Integer.parseInt(args[++i])); } else if ("-c".equals(args[i])) { cleanLogs = true; } else if ("-s".equals(args[i])) { start = Integer.parseInt(args[++i]); } else if ("-e".equals(args[i])) { end = Integer.parseInt(args[++i]); } else if ("-libjars".equals(args[i])) { conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf)); URL[] libjars = FileUtils.getLibJars(conf); if (libjars != null && libjars.length > 0) { // Add libjars to client/tasks classpath conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader())); // Adds libjars to our classpath Thread.currentThread().setContextClassLoader( new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader())); } } else { other_args.add(args[i]); } } catch (NumberFormatException except) { System.out.println("ERROR: Integer expected instead of " + args[i]); return printUsage(); } catch (ArrayIndexOutOfBoundsException except) { System.out.println("ERROR: Required parameter missing from " + args[i - 1]); return printUsage(); } } // Make sure there are exactly 2 parameters left. if (other_args.size() != 2) { System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2."); return printUsage(); } return initJob(conf, start, end, other_args.get(0), other_args.get(1), cleanLogs); }
From source file:com.liferay.portal.servlet.PortletContextListener.java
public void contextInitialized(ServletContextEvent sce) { try {/*from w w w. ja va2s. c o 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:org.apache.sqoop.core.SqoopConfiguration.java
/** * Load extra classpath from sqoop configuration. *///from w w w .j a va2 s . c o m private synchronized void configureClassLoader() { LOG.info("Adding jars to current classloader from property: " + ConfigurationConstants.CLASSPATH); List<URL> urls = getJarsForProperty(ConfigurationConstants.CLASSPATH); // Chain the current thread classloader so that // configured classpath adds to existing classloader. // Existing classpath is not changed. ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader(); if (currentThreadClassLoader == null) { throw new SqoopException(CoreError.CORE_0009, "No thread context classloader to override."); } URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), currentThreadClassLoader); Thread.currentThread().setContextClassLoader(classLoader); }