List of usage examples for java.net URL getFile
public String getFile()
From source file:net.firejack.platform.core.utils.FileUtils.java
/** * @param child// ww w .j a va2 s. c om * * @return */ public static File getResource(String... child) { URL url = Thread.currentThread().getContextClassLoader().getResource(""); String file = url.getFile(); try { file = URLDecoder.decode(file, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return FileUtils.create(file, child); }
From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java
/** * /*from w w w .j a va 2 s .co m*/ * Extract a directory in a JAR on the classpath to an output folder. * * Note: User's responsibility to ensure that the files are actually in a JAR. * * @param classInJar A class in the JAR file which is on the classpath * @param resourceDirectory Path to resource directory in JAR * @param outputDirectory Directory to write to * @return String containing the path to the outputDirectory * @throws IOException */ private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory, String outputDirectory) throws IOException { resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator; URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation(); JarFile jarFile = new JarFile(new File(jar.getFile())); byte[] buf = new byte[1024]; Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) { continue; } String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName()); //Create directories if they don't exist new File(FilenameUtils.getFullPath(outputFileName)).mkdirs(); //Write file FileOutputStream fileOutputStream = new FileOutputStream(outputFileName); int n; InputStream is = jarFile.getInputStream(jarEntry); while ((n = is.read(buf, 0, 1024)) > -1) { fileOutputStream.write(buf, 0, n); } is.close(); fileOutputStream.close(); } jarFile.close(); String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory); return fullPath; }
From source file:com.bfd.harpc.common.configure.PathUtils.java
/** * ???//w w w .j a va 2 s .c om * <p> * windows"\"Unix*"/" * * @param originalUrl * URL * @return ? */ public static String getRealPath(URL originalUrl) { String fs = SeparatorUtils.getFileSeparator(); String file = originalUrl.getFile(); if (fs.equals("\\")) { return file.replace("/", fs); } return file; }
From source file:com.cloud.utils.PropertiesUtil.java
/** * Searches the class path and local paths to find the config file. * @param path path to find. if it starts with / then it's absolute path. * @return File or null if not found at all. *///w ww . j ava 2 s.com public static File findConfigFile(String path) { ClassLoader cl = PropertiesUtil.class.getClassLoader(); URL url = cl.getResource(path); if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } url = ClassLoader.getSystemResource(path); if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } File file = new File(path); if (file.exists()) { return file; } String newPath = "conf" + (path.startsWith(File.separator) ? "" : "/") + path; url = ClassLoader.getSystemResource(newPath); if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } url = cl.getResource(newPath); if (url != null && "file".equals(url.getProtocol())) { return new File(url.getFile()); } newPath = "conf" + (path.startsWith(File.separator) ? "" : File.separator) + path; file = new File(newPath); if (file.exists()) { return file; } newPath = System.getProperty("catalina.home"); if (newPath == null) { newPath = System.getenv("CATALINA_HOME"); } if (newPath == null) { newPath = System.getenv("CATALINA_BASE"); } if (newPath == null) { return null; } file = new File(newPath + File.separator + "conf" + File.separator + path); if (file.exists()) { return file; } return null; }
From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java
public static String printClasspath() { StringBuilder sb = new StringBuilder(); try {/*from ww w . j a va 2s .c o m*/ ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader) systemClassLoader).getURLs(); for (URL url : urls) { sb.append(url.getFile()).append("\n"); } } catch (Exception e) { logger.warning("printClasspath failed for: ", e); } return sb.toString(); }
From source file:com.streamsets.pipeline.stage.destination.mapreduce.MapreduceUtils.java
@VisibleForTesting static void addJarsToJob(Configuration conf, boolean allowMultiple, URL[] jarUrls, String... jarPatterns) { final List<String> allMatches = new LinkedList<>(); final List<URL> patternMatches = new LinkedList<>(); for (String pattern : jarPatterns) { if (LOG.isTraceEnabled()) { LOG.trace("Looking for pattern {}", pattern); }//from w w w . j a v a 2 s . c o m for (URL url : jarUrls) { if (LOG.isTraceEnabled()) { LOG.trace("Looking in jar {}", url); } final String file = url.getFile(); if (StringUtils.endsWithIgnoreCase(file, ".jar") && StringUtils.containsIgnoreCase(file, pattern)) { allMatches.add(url.toString()); patternMatches.add(url); if (LOG.isDebugEnabled()) { LOG.debug("Found jar {} for pattern {}", url, pattern); } } } if (patternMatches.isEmpty()) { throw new IllegalArgumentException(String.format("Did not find any jars for pattern %s", pattern)); } else if (!allowMultiple && patternMatches.size() > 1) { throw new IllegalArgumentException(String.format("Found multiple jars for pattern %s: %s", pattern, StringUtils.join(patternMatches, JAR_SEPARATOR))); } patternMatches.clear(); } appendJars(conf, allMatches); }
From source file:com.dosport.system.utils.ReflectionUtils.java
/** * ??/*from w w w . j av a2 s . c o m*/ * * @param cls * @return * @throws IOException * @throws ClassNotFoundException */ public static List<Class<?>> getClasses(Class<?> cls) throws IOException, ClassNotFoundException { String pk = cls.getPackage().getName(); String path = pk.replace('.', '/'); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URL url = classloader.getResource(path); return getClasses(new File(url.getFile()), pk); }
From source file:org.mule.providers.soap.axis.wsdl.wsrf.util.AdviceAdderHelper.java
/** * list Classes inside a given package./*from ww w .ja v a2 s . c o m*/ * * @param pckgname String name of a Package, EG "java.lang" * @return Class[] classes inside the root of the given package * @throws ClassNotFoundException if the Package is invalid */ private static Class[] getClasses(String pckgname) throws ClassNotFoundException { ArrayList classes = new ArrayList(); // Get a File object for the package File directory = null; try { URL str = Thread.currentThread().getContextClassLoader().getResource(pckgname.replace('.', '/')); System.out.println("instance advice..." + new File(str.getFile()).getName()); directory = new File(str.getFile()); } catch (NullPointerException x) { throw new ClassNotFoundException(pckgname + " does not appear to be a valid package"); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in *Advice.class files if (files[i].endsWith("Advice.class")) { // removes the .class extension classes.add(Class.forName( pckgname + '.' + files[i].substring(0, files[i].length() - SUFFIX_CLASS_LENGTH))); } } } else { throw new ClassNotFoundException(pckgname + " does not appear to be a valid package"); } Class[] classesA = new Class[classes.size()]; classes.toArray(classesA); return classesA; }
From source file:net.ontopia.utils.TestFileUtils.java
public static void transferTestInputDirectory(ResourcesDirectoryReader directoryReader, String path) throws IOException { for (URL resource : directoryReader.getResources()) { String relative = resource.getFile(); relative = relative.substring(relative.lastIndexOf(path)); File file = new File(new File(getTestdataOutputDirectory()), relative); file.getParentFile().mkdirs();// w w w .ja v a 2s.c o m try (InputStream in = resource.openStream(); OutputStream out = new FileOutputStream(file)) { IOUtils.copy(in, out); } } }
From source file:com.hurence.logisland.classloading.PluginLoader.java
/** * Scan for plugins./*w ww.j av a2 s . c om*/ */ private static void scanAndRegisterPlugins() { Set<URL> urls = new HashSet<>(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); while (cl != null) { if (cl instanceof URLClassLoader) { urls.addAll(Arrays.asList(((URLClassLoader) cl).getURLs())); cl = cl.getParent(); } } for (URL url : urls) { try { Archive archive = null; try { archive = new JarFileArchive( new File(URLDecoder.decode(url.getFile(), Charset.defaultCharset().name())), url); } catch (Exception e) { //silently swallowing exception. just skip the archive since not an archive } if (archive == null) { continue; } Manifest manifest = archive.getManifest(); if (manifest != null) { String exportedPlugins = manifest.getMainAttributes() .getValue(ManifestAttributes.MODULE_EXPORTS); if (exportedPlugins != null) { String version = StringUtils.defaultIfEmpty( manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION), "UNKNOWN"); logger.info("Loading components from module {}", archive.getUrl().toExternalForm()); final Archive arc = archive; if (StringUtils.isNotBlank(exportedPlugins)) { Arrays.stream(exportedPlugins.split(",")).map(String::trim).forEach(s -> { if (registry.putIfAbsent(s, PluginClassloaderBuilder.build(arc)) == null) { logger.info("Registered component '{}' version '{}'", s, version); } }); } } } } catch (Exception e) { logger.error("Unable to load components from " + url.toExternalForm(), e); } } }