List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine2.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {//from ww w . j a v a2 s. c om Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:org.apache.tez.client.TestTezClientUtils.java
/** * //from ww w . j a v a 2 s . c o m * @throws Exception */ @Test(timeout = 5000) public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnoredSetToFalse() throws Exception { URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs(); StringBuffer buffer = new StringBuffer(); for (URL url : cp) { buffer.append(url.toExternalForm()); buffer.append(","); } TezConfiguration conf = new TezConfiguration(); conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString()); conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false); Credentials credentials = new Credentials(); Map<String, LocalResource> localizedMap = new HashMap<String, LocalResource>(); Assert.assertFalse(TezClientUtils.setupTezJarsLocalResources(conf, credentials, localizedMap)); assertFalse(localizedMap.isEmpty()); }
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {/*from w ww .j a va2 s. c o m*/ Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:io.dstream.tez.utils.HadoopUtils.java
/** * *//* ww w . j a v a 2 s . c o m*/ private static boolean generateConfigJarFromHadoopConfDir(FileSystem fs, String applicationName, List<Path> provisionedPaths, List<File> generatedJars) { boolean generated = false; String hadoopConfDir = System.getenv().get("HADOOP_CONF_DIR"); if (hadoopConfDir != null && hadoopConfDir.trim().length() > 0) { String jarFileName = ClassPathUtils.generateJarFileName("conf_"); File confDir = new File(hadoopConfDir.trim()); File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (HADOOP_CONF_DIR)"); String destinationFilePath = applicationName + "/" + jarFile.getName(); Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath); try { provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath); provisionedPaths.add(provisionedPath); generated = true; } catch (Exception e) { logger.warn("Failed to provision " + provisionedPath + "; " + e.getMessage()); if (logger.isDebugEnabled()) { logger.warn("Failed to provision " + provisionedPath, e); } throw new IllegalStateException(e); } } String tezConfDir = System.getenv().get("TEZ_CONF_DIR"); if (tezConfDir != null && tezConfDir.trim().length() > 0) { String jarFileName = ClassPathUtils.generateJarFileName("conf_tez"); File confDir = new File(tezConfDir.trim()); File jarFile = doGenerateJar(confDir, jarFileName, generatedJars, "configuration (TEZ_CONF_DIR)"); try { URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m.setAccessible(true); m.invoke(cl, jarFile.toURI().toURL()); } catch (Exception e) { throw new IllegalStateException(e); } String destinationFilePath = applicationName + "/" + jarFile.getName(); Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath); try { provisioinResourceToFs(fs, new Path(jarFile.getAbsolutePath()), provisionedPath); provisionedPaths.add(provisionedPath); generated = true; } catch (Exception e) { logger.warn("Failed to provision " + provisionedPath + "; " + e.getMessage()); if (logger.isDebugEnabled()) { logger.warn("Failed to provision " + provisionedPath, e); } throw new IllegalStateException(e); } } return generated; }
From source file:org.objectstyle.cayenne.util.ResourceLocator.java
/** * Returns a base URL as a String from which this class was loaded. * This is normally a JAR or a file URL, but it is ClassLoader dependent. *//* w ww . j a v a2 s .c o m*/ public static String classBaseUrl(Class aClass) { String pathToClass = aClass.getName().replace('.', '/') + ".class"; ClassLoader classLoader = aClass.getClassLoader(); if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } URL selfUrl = classLoader.getResource(pathToClass); if (selfUrl == null) { return null; } String urlString = selfUrl.toExternalForm(); return urlString.substring(0, urlString.length() - pathToClass.length()); }
From source file:de.thetaphi.forbiddenapis.cli.CliMain.java
public void run() throws ExitException { final File classesDirectory = new File(cmd.getOptionValue(dirOpt.getLongOpt())).getAbsoluteFile(); // parse classpath given as argument; add -d to classpath, too final String[] classpath = cmd.getOptionValues(classpathOpt.getLongOpt()); final URL[] urls; try {// w ww. j av a2 s.c o m if (classpath == null) { urls = new URL[] { classesDirectory.toURI().toURL() }; } else { urls = new URL[classpath.length + 1]; int i = 0; for (final String cpElement : classpath) { urls[i++] = new File(cpElement).toURI().toURL(); } urls[i++] = classesDirectory.toURI().toURL(); assert i == urls.length; } } catch (MalformedURLException mfue) { throw new ExitException(EXIT_ERR_OTHER, "The given classpath is invalid: " + mfue); } // System.err.println("Classpath: " + Arrays.toString(urls)); final URLClassLoader loader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader()); try { final EnumSet<Checker.Option> options = EnumSet.of(FAIL_ON_VIOLATION); if (!cmd.hasOption(allowmissingclassesOpt.getLongOpt())) options.add(FAIL_ON_MISSING_CLASSES); if (!cmd.hasOption(allowunresolvablesignaturesOpt.getLongOpt())) options.add(FAIL_ON_UNRESOLVABLE_SIGNATURES); final Checker checker = new Checker(LOG, loader, options); if (!checker.isSupportedJDK) { throw new ExitException(EXIT_UNSUPPORTED_JDK, String.format(Locale.ENGLISH, "Your Java runtime (%s %s) is not supported by forbiddenapis. Please run the checks with a supported JDK!", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"))); } final String[] suppressAnnotations = cmd.getOptionValues(suppressannotationsOpt.getLongOpt()); if (suppressAnnotations != null) for (String a : suppressAnnotations) { checker.addSuppressAnnotation(a); } LOG.info("Scanning for classes to check..."); if (!classesDirectory.exists()) { throw new ExitException(EXIT_ERR_OTHER, "Directory with class files does not exist: " + classesDirectory); } String[] includes = cmd.getOptionValues(includesOpt.getLongOpt()); if (includes == null || includes.length == 0) { includes = new String[] { "**/*.class" }; } final String[] excludes = cmd.getOptionValues(excludesOpt.getLongOpt()); final DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(classesDirectory); ds.setCaseSensitive(true); ds.setIncludes(includes); ds.setExcludes(excludes); ds.addDefaultExcludes(); ds.scan(); final String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new ExitException(EXIT_ERR_OTHER, String.format(Locale.ENGLISH, "No classes found in directory %s (includes=%s, excludes=%s).", classesDirectory, Arrays.toString(includes), Arrays.toString(excludes))); } try { final String[] bundledSignatures = cmd.getOptionValues(bundledsignaturesOpt.getLongOpt()); if (bundledSignatures != null) for (String bs : new LinkedHashSet<String>(Arrays.asList(bundledSignatures))) { checker.addBundledSignatures(bs, null); } if (cmd.hasOption(internalruntimeforbiddenOpt.getLongOpt())) { LOG.warn(DEPRECATED_WARN_INTERNALRUNTIME); checker.addBundledSignatures(BS_JDK_NONPORTABLE, null); } final String[] signaturesFiles = cmd.getOptionValues(signaturesfileOpt.getLongOpt()); if (signaturesFiles != null) for (String sf : new LinkedHashSet<String>(Arrays.asList(signaturesFiles))) { final File f = new File(sf).getAbsoluteFile(); checker.parseSignaturesFile(f); } } catch (IOException ioe) { throw new ExitException(EXIT_ERR_OTHER, "IO problem while reading files with API signatures: " + ioe); } catch (ParseException pe) { throw new ExitException(EXIT_ERR_OTHER, "Parsing signatures failed: " + pe.getMessage()); } if (checker.hasNoSignatures()) { throw new ExitException(EXIT_ERR_CMDLINE, String.format(Locale.ENGLISH, "No API signatures found; use parameters '--%s', '--%s', and/or '--%s' to define those!", bundledsignaturesOpt.getLongOpt(), signaturesfileOpt.getLongOpt(), internalruntimeforbiddenOpt.getLongOpt())); } try { checker.addClassesToCheck(classesDirectory, files); } catch (IOException ioe) { throw new ExitException(EXIT_ERR_OTHER, "Failed to load one of the given class files: " + ioe); } try { checker.run(); } catch (ForbiddenApiException fae) { throw new ExitException(EXIT_VIOLATION, fae.getMessage()); } } finally { // Java 7 supports closing URLClassLoader, so check for Closeable interface: if (loader instanceof Closeable) try { ((Closeable) loader).close(); } catch (IOException ioe) { // ignore } } }
From source file:org.apache.axiom.util.stax.dialect.StAXDialectDetector.java
private static Class loadClass(ClassLoader classLoader, URL rootUrl, String name) { try {/*from w w w . j a v a2 s. c o m*/ if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } Class cls = classLoader.loadClass(name); // Cross check if the class was loaded from the same location (JAR) return rootUrl.equals(getRootUrlForClass(cls)) ? cls : null; } catch (ClassNotFoundException ex) { return null; } }
From source file:sx.blah.discord.modules.ModuleLoader.java
/** * Loads a jar file and automatically adds any modules. * To avoid high overhead recursion, specify the attribute "Discord4J-ModuleClass" in your jar manifest. * Multiple classes should be separated by a semicolon ";". * * @param file The jar file to load./*from w w w .j a v a 2s . co m*/ */ public static synchronized void loadExternalModules(File file) { // A bit hacky, but oracle be dumb and encapsulates URLClassLoader#addUrl() if (file.isFile() && file.getName().endsWith(".jar")) { // Can't be a directory and must be a jar try (JarFile jar = new JarFile(file)) { Manifest man = jar.getManifest(); String moduleAttrib = man == null ? null : man.getMainAttributes().getValue("Discord4J-ModuleClass"); String[] moduleClasses = new String[0]; if (moduleAttrib != null) { moduleClasses = moduleAttrib.split(";"); } // Executes would should be URLCLassLoader.addUrl(file.toURI().toURL()); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL url = file.toURI().toURL(); for (URL it : Arrays.asList(loader.getURLs())) { // Ensures duplicate libraries aren't loaded if (it.equals(url)) { return; } } Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(loader, url); if (moduleClasses.length == 0) { // If the Module Developer has not specified the Implementing Class, revert to recursive search // Scans the jar file for classes which have IModule as a super class List<String> classes = new ArrayList<>(); jar.stream() .filter(jarEntry -> !jarEntry.isDirectory() && jarEntry.getName().endsWith(".class")) .map(path -> path.getName().replace('/', '.').substring(0, path.getName().length() - ".class".length())) .forEach(classes::add); for (String clazz : classes) { try { Class classInstance = loadClass(clazz); if (IModule.class.isAssignableFrom(classInstance) && !classInstance.equals(IModule.class)) { addModuleClass(classInstance); } } catch (NoClassDefFoundError ignored) { /* This can happen. Looking recursively looking through the classpath is hackish... */ } } } else { for (String moduleClass : moduleClasses) { Discord4J.LOGGER.info(LogMarkers.MODULES, "Loading Class from Manifest Attribute: {}", moduleClass); Class classInstance = loadClass(moduleClass); if (IModule.class.isAssignableFrom(classInstance)) addModuleClass(classInstance); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException | ClassNotFoundException e) { Discord4J.LOGGER.error(LogMarkers.MODULES, "Unable to load module " + file.getName() + "!", e); } } }
From source file:de.thetaphi.forbiddenapis.CliMain.java
public void run() throws ExitException { final File classesDirectory = new File(cmd.getOptionValue(dirOpt.getLongOpt())).getAbsoluteFile(); // parse classpath given as argument; add -d to classpath, too final String[] classpath = cmd.getOptionValues(classpathOpt.getLongOpt()); final URL[] urls; try {/* w w w. j a v a 2 s.co m*/ if (classpath == null) { urls = new URL[] { classesDirectory.toURI().toURL() }; } else { urls = new URL[classpath.length + 1]; int i = 0; for (final String cpElement : classpath) { urls[i++] = new File(cpElement).toURI().toURL(); } urls[i++] = classesDirectory.toURI().toURL(); assert i == urls.length; } } catch (MalformedURLException mfue) { throw new ExitException(EXIT_ERR_OTHER, "The given classpath is invalid: " + mfue); } // System.err.println("Classpath: " + Arrays.toString(urls)); final URLClassLoader loader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader()); try { final EnumSet<Checker.Option> options = EnumSet.of(FAIL_ON_VIOLATION); if (cmd.hasOption(internalruntimeforbiddenOpt.getLongOpt())) options.add(INTERNAL_RUNTIME_FORBIDDEN); if (!cmd.hasOption(allowmissingclassesOpt.getLongOpt())) options.add(FAIL_ON_MISSING_CLASSES); if (!cmd.hasOption(allowunresolvablesignaturesOpt.getLongOpt())) options.add(FAIL_ON_UNRESOLVABLE_SIGNATURES); final Checker checker = new Checker(loader, options) { @Override protected void logError(String msg) { CliMain.this.logError(msg); } @Override protected void logWarn(String msg) { CliMain.this.logWarn(msg); } @Override protected void logInfo(String msg) { CliMain.this.logInfo(msg); } }; if (!checker.isSupportedJDK) { throw new ExitException(EXIT_UNSUPPORTED_JDK, String.format(Locale.ENGLISH, "Your Java runtime (%s %s) is not supported by forbiddenapis. Please run the checks with a supported JDK!", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"))); } final String[] suppressAnnotations = cmd.getOptionValues(suppressannotationsOpt.getLongOpt()); if (suppressAnnotations != null) for (String a : suppressAnnotations) { checker.addSuppressAnnotation(a); } logInfo("Scanning for classes to check..."); if (!classesDirectory.exists()) { throw new ExitException(EXIT_ERR_OTHER, "Directory with class files does not exist: " + classesDirectory); } String[] includes = cmd.getOptionValues(includesOpt.getLongOpt()); if (includes == null || includes.length == 0) { includes = new String[] { "**/*.class" }; } final String[] excludes = cmd.getOptionValues(excludesOpt.getLongOpt()); final DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(classesDirectory); ds.setCaseSensitive(true); ds.setIncludes(includes); ds.setExcludes(excludes); ds.addDefaultExcludes(); ds.scan(); final String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new ExitException(EXIT_ERR_OTHER, String.format(Locale.ENGLISH, "No classes found in directory %s (includes=%s, excludes=%s).", classesDirectory, Arrays.toString(includes), Arrays.toString(excludes))); } try { final String[] bundledSignatures = cmd.getOptionValues(bundledsignaturesOpt.getLongOpt()); if (bundledSignatures != null) for (String bs : bundledSignatures) { logInfo("Reading bundled API signatures: " + bs); checker.parseBundledSignatures(bs, null); } final String[] signaturesFiles = cmd.getOptionValues(signaturesfileOpt.getLongOpt()); if (signaturesFiles != null) for (String sf : signaturesFiles) { final File f = new File(sf).getAbsoluteFile(); logInfo("Reading API signatures: " + f); checker.parseSignaturesFile(new FileInputStream(f)); } } catch (IOException ioe) { throw new ExitException(EXIT_ERR_OTHER, "IO problem while reading files with API signatures: " + ioe); } catch (ParseException pe) { throw new ExitException(EXIT_ERR_OTHER, "Parsing signatures failed: " + pe.getMessage()); } if (checker.hasNoSignatures()) { throw new ExitException(EXIT_ERR_CMDLINE, String.format(Locale.ENGLISH, "No API signatures found; use parameters '--%s', '--%s', and/or '--%s' to define those!", bundledsignaturesOpt.getLongOpt(), signaturesfileOpt.getLongOpt(), internalruntimeforbiddenOpt.getLongOpt())); } logInfo("Loading classes to check..."); try { for (String f : files) { checker.addClassToCheck(new FileInputStream(new File(classesDirectory, f))); } } catch (IOException ioe) { throw new ExitException(EXIT_ERR_OTHER, "Failed to load one of the given class files: " + ioe); } logInfo("Scanning for API signatures and dependencies..."); try { checker.run(); } catch (ForbiddenApiException fae) { throw new ExitException(EXIT_VIOLATION, fae.getMessage()); } } finally { // Java 7 supports closing URLClassLoader, so check for Closeable interface: if (loader instanceof Closeable) try { ((Closeable) loader).close(); } catch (IOException ioe) { // ignore } } }
From source file:info.novatec.testit.livingdoc.maven.plugin.SpecificationRunnerMojo.java
private ClassLoader createClassLoader() throws MojoExecutionException { List<URL> urls = new ArrayList<URL>(); for (Iterator<?> it = classpathElements.iterator(); it.hasNext();) { String s = (String) it.next(); urls.add(toURL(new File(s))); }/*from ww w.j a v a 2s . c o m*/ urls.add(toURL(fixtureOutputDirectory)); if (!containsLivingDocCore(urls)) { urls.add(getDependencyURL("livingdoc-core")); } urls.add(getDependencyURL("commons-codec")); URL[] classpath = urls.toArray(new URL[urls.size()]); return new URLClassLoader(classpath, ClassLoader.getSystemClassLoader()); }