List of usage examples for java.net JarURLConnection getJarFile
public abstract JarFile getJarFile() throws IOException;
From source file:org.b3log.latke.ioc.ClassPathResolver.java
/** * scan the jar to get the URLS of the Classes. * * @param rootDirResource which is "Jar" * @param subPattern subPattern/*from w ww. ja v a2s . c o m*/ * @return the URLs of all the matched classes */ private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource, final String subPattern) { final Set<URL> result = new LinkedHashSet<URL>(); JarFile jarFile = null; String jarFileUrl; String rootEntryPath = null; URLConnection con; boolean newJarFile = false; try { con = rootDirResource.openConnection(); if (con instanceof JarURLConnection) { final JarURLConnection jarCon = (JarURLConnection) con; jarCon.setUseCaches(false); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); final JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = jarEntry != null ? jarEntry.getName() : ""; } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the // protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" // prefix. final String urlFile = rootDirResource.getFile(); final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } } catch (final IOException e) { LOGGER.log(Level.ERROR, "reslove jar File error", e); return result; } try { if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { // Root entry path must end with slash to allow for proper // matching. // The Sun JRE does not return a slash here, but BEA JRockit // does. rootEntryPath = rootEntryPath + "/"; } for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { final JarEntry entry = (JarEntry) entries.nextElement(); final String entryPath = entry.getName(); String relativePath = null; if (entryPath.startsWith(rootEntryPath)) { relativePath = entryPath.substring(rootEntryPath.length()); if (AntPathMatcher.match(subPattern, relativePath)) { if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } result.add(new URL(rootDirResource, relativePath)); } } } return result; } catch (final IOException e) { LOGGER.log(Level.ERROR, "parse the JarFile error", e); } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { try { jarFile.close(); } catch (final IOException e) { LOGGER.log(Level.WARN, " occur error when closing jarFile", e); } } } return result; }
From source file:org.mule.util.FileUtils.java
/** * Extract recources contain if jar (have to in classpath) * * @param connection JarURLConnection to jar library * @param outputDir Directory for unpack recources * @param keepParentDirectory true - full structure of directories is kept; false - file - removed all directories, directory - started from resource point * @throws IOException if any error/*w w w . j av a2 s. c om*/ */ private static void extractJarResources(JarURLConnection connection, File outputDir, boolean keepParentDirectory) throws IOException { JarFile jarFile = connection.getJarFile(); JarEntry jarResource = connection.getJarEntry(); Enumeration entries = jarFile.entries(); InputStream inputStream = null; OutputStream outputStream = null; int jarResourceNameLenght = jarResource.getName().length(); for (; entries.hasMoreElements();) { JarEntry entry = (JarEntry) entries.nextElement(); if (entry.getName().startsWith(jarResource.getName())) { String path = outputDir.getPath() + File.separator + entry.getName(); //remove directory struct for file and first dir for directory if (!keepParentDirectory) { if (entry.isDirectory()) { if (entry.getName().equals(jarResource.getName())) { continue; } path = outputDir.getPath() + File.separator + entry.getName().substring(jarResourceNameLenght, entry.getName().length()); } else { if (entry.getName().length() > jarResourceNameLenght) { path = outputDir.getPath() + File.separator + entry.getName().substring(jarResourceNameLenght, entry.getName().length()); } else { path = outputDir.getPath() + File.separator + entry.getName() .substring(entry.getName().lastIndexOf("/"), entry.getName().length()); } } } File file = FileUtils.newFile(path); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new IOException("Could not create directory: " + file.getParentFile()); } } if (entry.isDirectory()) { if (!file.exists() && !file.mkdirs()) { throw new IOException("Could not create directory: " + file); } } else { try { inputStream = jarFile.getInputStream(entry); outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } } }
From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java
static String[] scanJar(JarURLConnection conn, String namespaceURL) throws IOException { JarFile jarFile = null;//from w w w .jav a 2 s . c om String resourcePath = conn.getJarFileURL().toString(); if (log.isTraceEnabled()) { log.trace("Fallback Scanning Jar " + resourcePath); } jarFile = conn.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { try { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (!name.startsWith("META-INF/")) { continue; } if (!name.endsWith(".tld")) { continue; } InputStream stream = jarFile.getInputStream(entry); try { String uri = getUriFromTld(resourcePath, stream); if ((uri != null) && (uri.equals(namespaceURL))) { return (new String[] { resourcePath, name }); } } catch (JasperException jpe) { if (log.isDebugEnabled()) { log.debug(jpe.getMessage(), jpe); } } finally { if (stream != null) { stream.close(); } } } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug(t.getMessage(), t); } } } return null; }
From source file:com.amalto.core.query.SystemStorageTest.java
private static Collection<String> getConfigFiles() throws Exception { URL data = InitDBUtil.class.getResource("data"); //$NON-NLS-1$ List<String> result = new ArrayList<String>(); if ("jar".equals(data.getProtocol())) { //$NON-NLS-1$ JarURLConnection connection = (JarURLConnection) data.openConnection(); JarEntry entry = connection.getJarEntry(); JarFile file = connection.getJarFile(); Enumeration<JarEntry> entries = file.entries(); while (entries.hasMoreElements()) { JarEntry e = entries.nextElement(); if (e.getName().startsWith(entry.getName()) && !e.isDirectory()) { result.add(IOUtils.toString(file.getInputStream(e))); }/*from ww w .ja v a 2 s .co m*/ } } else { Collection<File> files = FileUtils.listFiles(new File(data.toURI()), new IOFileFilter() { @Override public boolean accept(File file) { return true; } @Override public boolean accept(File file, String s) { return true; } }, new IOFileFilter() { @Override public boolean accept(File file) { return !".svn".equals(file.getName()); //$NON-NLS-1$ } @Override public boolean accept(File file, String s) { return !".svn".equals(file.getName()); //$NON-NLS-1$ } }); for (File f : files) { result.add(IOUtils.toString(new FileInputStream(f))); } } return result; }
From source file:org.junit.extensions.dynamicsuite.engine.ClassPathScanner.java
private JarFile loadJarFile(File jarFile) { try {/*from w ww . j a v a 2s. c o m*/ URL jarURL = new URL("file:" + jarFile.getCanonicalPath()); jarURL = new URL("jar:" + jarURL.toExternalForm() + "!/"); JarURLConnection conn = (JarURLConnection) jarURL.openConnection(); return conn.getJarFile(); } catch (Exception e) { return null; } }
From source file:de.uni.bremen.monty.moco.util.MontyJar.java
public MontyJar(URL url) throws IOException { JarURLConnection urlConnection = (JarURLConnection) url.openConnection(); jarFile = urlConnection.getJarFile(); jarEntry = urlConnection.getJarEntry(); }
From source file:edu.stanford.epadd.launcher.Splash.java
private static void copyResourcesRecursively(String sourceDirectory, String writeDirectory) throws IOException { final URL dirURL = ePADD.class.getClassLoader().getResource(sourceDirectory); //final String path = sourceDirectory.substring( 1 ); if ((dirURL != null) && dirURL.getProtocol().equals("jar")) { final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection(); //System.out.println( "jarConnection is " + jarConnection ); final ZipFile jar = jarConnection.getJarFile(); final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final String name = entry.getName(); // System.out.println( name ); if (!name.startsWith(sourceDirectory)) { // entry in wrong subdir -- don't copy continue; }//from w w w . j av a2s .c o m final String entryTail = name.substring(sourceDirectory.length()); final File f = new File(writeDirectory + File.separator + entryTail); if (entry.isDirectory()) { // if its a directory, create it final boolean bMade = f.mkdir(); System.out.println((bMade ? " creating " : " unable to create ") + name); } else { System.out.println(" writing " + name); final InputStream is = jar.getInputStream(entry); final OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); final byte buffer[] = new byte[4096]; int readCount; // write contents of 'is' to 'os' while ((readCount = is.read(buffer)) > 0) { os.write(buffer, 0, readCount); } os.close(); is.close(); } } } else if (dirURL == null) { throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath"); } else { // not a "jar" protocol URL throw new IllegalStateException("don't know how to handle extracting from " + dirURL); } }
From source file:it.polito.tellmefirst.web.rest.utils.LangDetectUtils.java
/** A private Constructor prevents any other class from instantiating. */ private LangDetectUtils() { try {/*w w w. j a v a 2 s.c om*/ String dirname = "profiles/"; Enumeration<URL> en = Detector.class.getClassLoader().getResources(dirname); List<String> profiles = new ArrayList<String>(); if (en.hasMoreElements()) { URL url = en.nextElement(); JarURLConnection urlcon = (JarURLConnection) url.openConnection(); JarFile jar = urlcon.getJarFile(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String entry = entries.nextElement().getName(); if (entry.startsWith(dirname)) { InputStream in = Detector.class.getClassLoader().getResourceAsStream(entry); profiles.add(IOUtils.toString(in)); } } } DetectorFactory.loadProfile(profiles); } catch (LangDetectException e) { LOG.error("Error loading profiles directory " + e.getMessage()); } catch (Exception e) { LOG.error("Error loading profiles directory " + e.getMessage()); } }
From source file:org.apache.hadoop.hive.ql.exec.tez.HivePreWarmProcessor.java
@Override public void run(Map<String, LogicalInput> inputs, Map<String, LogicalOutput> outputs) throws Exception { if (prewarmed) { /* container reuse */ return;//from ww w .ja v a 2s . co m } for (LogicalInput input : inputs.values()) { input.start(); } for (LogicalOutput output : outputs.values()) { output.start(); } /* these are things that goes through singleton initialization on most queries */ FileSystem fs = FileSystem.get(conf); Mac mac = Mac.getInstance("HmacSHA1"); ReadaheadPool rpool = ReadaheadPool.getInstance(); ShimLoader.getHadoopShims(); URL hiveurl = new URL("jar:" + DagUtils.getInstance().getExecJarPathLocal() + "!/"); JarURLConnection hiveconn = (JarURLConnection) hiveurl.openConnection(); JarFile hivejar = hiveconn.getJarFile(); try { Enumeration<JarEntry> classes = hivejar.entries(); while (classes.hasMoreElements()) { JarEntry je = classes.nextElement(); if (je.getName().endsWith(".class")) { String klass = je.getName().replace(".class", "").replaceAll("/", "\\."); if (klass.indexOf("ql.exec") != -1 || klass.indexOf("ql.io") != -1) { /* several hive classes depend on the metastore APIs, which is not included * in hive-exec.jar. These are the relatively safe ones - operators & io classes. */ if (klass.indexOf("vector") != -1 || klass.indexOf("Operator") != -1) { JavaUtils.loadClass(klass); } } } } } finally { hivejar.close(); } prewarmed = true; }
From source file:br.com.uol.runas.classloader.JarClassLoader.java
private void addUrlsFromJar(URL url) throws IOException, MalformedURLException { final JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarFile = jarConnection.getJarFile(); final Enumeration<JarEntry> entries = jarFile.entries(); final URL jarUrl = new File(jarFile.getName()).toURI().toURL(); final String base = jarUrl.toString(); addURL(jarUrl);//from w w w . j a va 2s . c o m while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory() || endsWithAny(entry.getName(), ".jar", ".war", ".ear")) { addURL(new URL(base + entry.getName())); } } }