List of usage examples for java.net JarURLConnection getJarFileURL
public URL getJarFileURL()
From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java
private void downloadLocalStormCode(Map conf, String stormId, String masterCodeDir, Localizer localizer) throws Exception { String tmproot = ConfigUtils.supervisorTmpDir(conf) + Utils.FILE_PATH_SEPARATOR + Utils.uuid(); String stormroot = ConfigUtils.supervisorStormDistRoot(conf, stormId); BlobStore blobStore = Utils.getNimbusBlobStore(conf, masterCodeDir, null); FileOutputStream codeOutStream = null; FileOutputStream confOutStream = null; try {/*w ww. j a va 2 s. c o m*/ FileUtils.forceMkdir(new File(tmproot)); String stormCodeKey = ConfigUtils.masterStormCodeKey(stormId); String stormConfKey = ConfigUtils.masterStormConfKey(stormId); String codePath = ConfigUtils.supervisorStormCodePath(tmproot); String confPath = ConfigUtils.supervisorStormConfPath(tmproot); codeOutStream = new FileOutputStream(codePath); blobStore.readBlobTo(stormCodeKey, codeOutStream, null); confOutStream = new FileOutputStream(confPath); blobStore.readBlobTo(stormConfKey, confOutStream, null); } finally { if (codeOutStream != null) codeOutStream.close(); if (confOutStream != null) codeOutStream.close(); blobStore.shutdown(); } FileUtils.moveDirectory(new File(tmproot), new File(stormroot)); SupervisorUtils.setupStormCodeDir(conf, ConfigUtils.readSupervisorStormConf(conf, stormId), stormroot); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String resourcesJar = resourcesJar(); URL url = classloader.getResource(ConfigUtils.RESOURCES_SUBDIR); String targetDir = stormroot + Utils.FILE_PATH_SEPARATOR + ConfigUtils.RESOURCES_SUBDIR; if (resourcesJar != null) { LOG.info("Extracting resources from jar at {} to {}", resourcesJar, targetDir); Utils.extractDirFromJar(resourcesJar, ConfigUtils.RESOURCES_SUBDIR, stormroot); } else if (url != null) { LOG.info("Copying resources at {} to {} ", url.toString(), targetDir); if (url.getProtocol() == "jar") { JarURLConnection urlConnection = (JarURLConnection) url.openConnection(); Utils.extractDirFromJar(urlConnection.getJarFileURL().getFile(), ConfigUtils.RESOURCES_SUBDIR, stormroot); } else { FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir))); } } }
From source file:org.apache.storm.localizer.LocallyCachedTopologyBlob.java
@Override public long downloadToTempLocation(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException { if (isLocalMode && type == TopologyBlobType.TOPO_JAR) { LOG.debug("DOWNLOADING LOCAL JAR to TEMP LOCATION... {}", topologyId); //This is a special case where the jar was not uploaded so we will not download it (it is already on the classpath) ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String resourcesJar = resourcesJar(); URL url = classloader.getResource(ServerConfigUtils.RESOURCES_SUBDIR); Path extractionDest = topologyBasicBlobsRootDir .resolve(type.getTempExtractionDir(LOCAL_MODE_JAR_VERSION)); if (resourcesJar != null) { LOG.info("Extracting resources from jar at {} to {}", resourcesJar, extractionDest); extractDirFromJar(resourcesJar, ServerConfigUtils.RESOURCES_SUBDIR, extractionDest); } else if (url != null) { LOG.info("Copying resources at {} to {}", url, extractionDest); if ("jar".equals(url.getProtocol())) { JarURLConnection urlConnection = (JarURLConnection) url.openConnection(); extractDirFromJar(urlConnection.getJarFileURL().getFile(), ServerConfigUtils.RESOURCES_SUBDIR, extractionDest); } else { fsOps.copyDirectory(new File(url.getFile()), extractionDest.toFile()); }//from w w w . jav a 2 s . c o m } return LOCAL_MODE_JAR_VERSION; } long newVersion; Path tmpLocation; String key = type.getKey(topologyId); try (InputStreamWithMeta in = store.getBlob(key)) { newVersion = in.getVersion(); long expectedSize = in.getFileLength(); if (newVersion == version) { throw new RuntimeException( "The version did not change, but we tried to download it. " + version + " " + key); } tmpLocation = topologyBasicBlobsRootDir.resolve(type.getTempFileName(newVersion)); long totalRead = 0; //Make sure the parent directory is there and ready to go fsOps.forceMkdir(tmpLocation.getParent()); try (OutputStream outStream = fsOps.getOutputStream(tmpLocation.toFile())) { byte[] buffer = new byte[4096]; int read = 0; while ((read = in.read(buffer)) > 0) { outStream.write(buffer, 0, read); totalRead += read; } } if (totalRead != expectedSize) { throw new IOException( "We expected to download " + expectedSize + " bytes but found we got " + totalRead); } } if (type.needsExtraction()) { Path extractionDest = topologyBasicBlobsRootDir.resolve(type.getTempExtractionDir(newVersion)); extractDirFromJar(tmpLocation.toAbsolutePath().toString(), ServerConfigUtils.RESOURCES_SUBDIR, extractionDest); } return newVersion; }
From source file:org.apache.struts2.jasper.compiler.TldLocationsCache.java
/** * Scans the given JarURLConnection for TLD files located in META-INF * (or a subdirectory of it), adding an implicit map entry to the taglib * map for any TLD that has a <uri> element. * * @param conn The JarURLConnection to the JAR file to scan * @param ignore true if any exceptions raised when processing the given * JAR should be ignored, false otherwise *//*from w w w . j av a 2 s . c o m*/ private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException { JarFile jarFile = null; String resourcePath = conn.getJarFileURL().toString(); try { if (redeployMode) { conn.setUseCaches(false); } jarFile = conn.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { 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); // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { mappings.put(uri, new String[] { resourcePath, name }); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { // do nothing } } } } } catch (Exception ex) { if (!redeployMode) { // if not in redeploy mode, close the jar in case of an error if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } if (!ignore) { throw new JasperException(ex); } } finally { if (redeployMode) { // if in redeploy mode, always close the jar if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } } }
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. jav a 2 s .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.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java
/** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher./* w w w . j av a 2s . c o m*/ * @param rootDirResource the root directory as Resource * @param subPattern the sub pattern to match (below the root directory) * @return the Set of matching Resource instances * @throws IOException in case of I/O errors * @see java.net.JarURLConnection */ protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException { URLConnection con = rootDirResource.getURL().openConnection(); JarFile jarFile; String jarFileUrl; String rootEntryPath; boolean newJarFile = false; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; GrailsResourceUtils.useCachesIfNecessary(jarCon); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); 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. String urlFile = rootDirResource.getURL().getFile(); int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } try { if (logger.isDebugEnabled()) { logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]"); } 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 + "/"; } Set<Resource> result = new LinkedHashSet<Resource>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (getPathMatcher().match(subPattern, relativePath)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { jarFile.close(); } } }
From source file:org.grails.io.support.PathMatchingResourcePatternResolver.java
/** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher./* w ww . java2s. c o m*/ * @param rootDirResource the root directory as Resource * @param subPattern the sub pattern to match (below the root directory) * @return the Set of matching Resource instances * @throws IOException in case of I/O errors * @see java.net.JarURLConnection */ protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException { URLConnection con = rootDirResource.getURL().openConnection(); JarFile jarFile; String jarFileUrl; String rootEntryPath; boolean newJarFile = false; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; GrailsResourceUtils.useCachesIfNecessary(jarCon); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); 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. String urlFile = rootDirResource.getURL().getFile(); int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } 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 + "/"; } Set<Resource> result = new LinkedHashSet<Resource>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (getPathMatcher().match(subPattern, relativePath)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { jarFile.close(); } } }
From source file:org.jbpm.bpel.tools.WscompileTool.java
/** * Gets the directory, JAR file or remote URL from which the given class was loaded. * @param c the class to be located// ww w.j ava2 s .c o m * @return the location from which the class was loaded, or <code>null</code> if the origin of * the class is unknown */ private static String getLocation(Class c) { CodeSource codeSource = c.getProtectionDomain().getCodeSource(); if (codeSource == null) { /* * The code source of a domain may be null. This is the case for classes included in the Java * platform. For example, the javax.xml.soap package is part of Java SE 6. Not much more can * be done here, so we just tell the caller the location is unknown. * * Thanks to Bernd Ruecker of Camunda GmbH for catching this one. */ return null; } URL url = codeSource.getLocation(); if ("jar".equals(url.getProtocol())) { try { JarURLConnection urlConnection = (JarURLConnection) url.openConnection(); url = urlConnection.getJarFileURL(); } catch (IOException e) { log.debug("could not open connection to " + url, e); } } if (!"file".equals(url.getProtocol())) return url.toString(); String fileName = url.getFile(); try { fileName = URLDecoder.decode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { log.debug("UTF-8 not supported", e); } return new File(fileName).getAbsolutePath(); }
From source file:org.nuxeo.theme.jsf.facelets.vendor.Util.java
public static long getLastModified(URL url) { long lastModified; URLConnection conn;//from ww w . j a va2 s .c om InputStream is = null; try { conn = url.openConnection(); if (conn instanceof JarURLConnection) { /* * Note this is a work around for JarURLConnection since the getLastModified method is buggy. See * JAVASERVERFACES-2725 and JAVASERVERFACES-2734. */ JarURLConnection jarUrlConnection = (JarURLConnection) conn; URL jarFileUrl = jarUrlConnection.getJarFileURL(); URLConnection jarFileConnection = jarFileUrl.openConnection(); lastModified = jarFileConnection.getLastModified(); jarFileConnection.getInputStream().close(); } else if (conn instanceof Connection) { // Nuxeo patch: do not bother opening connection to get last // modified time lastModified = conn.getLastModified(); } else { is = conn.getInputStream(); lastModified = conn.getLastModified(); } } catch (IOException e) { throw new FacesException(LAST_MODIFIED_ERROR + url, e); } finally { IOUtils.closeQuietly(is); } return lastModified; }
From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java
/** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher.//from ww w. jav a 2 s .co m * @param rootDirResource the root directory as Resource * @param rootDirURL the pre-resolved root directory URL * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set of matching Resource instances * @throws IOException in case of I/O errors * @since 4.3 * @see java.net.JarURLConnection * @see org.springframework.util.PathMatcher */ protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, URL rootDirURL, String subPattern) throws IOException { URLConnection con = rootDirURL.openConnection(); JarFile jarFile; String jarFileUrl; String rootEntryPath; boolean closeJarFile; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; ResourceUtils.useCachesIfNecessary(jarCon); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); closeJarFile = !jarCon.getUseCaches(); } 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. String urlFile = rootDirURL.getFile(); try { int separatorIndex = urlFile.indexOf(ResourceUtils.WAR_URL_SEPARATOR); if (separatorIndex == -1) { separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR); } if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + 2); // both separators are 2 chars jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } closeJarFile = true; } catch (ZipException ex) { if (logger.isDebugEnabled()) { logger.debug("Skipping invalid jar classpath entry [" + urlFile + "]"); } return Collections.emptySet(); } } try { if (logger.isDebugEnabled()) { logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]"); } 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 + "/"; } Set<Resource> result = new LinkedHashSet<>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (getPathMatcher().match(subPattern, relativePath)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { if (closeJarFile) { jarFile.close(); } } }
From source file:org.springframework.extensions.config.source.UrlConfigSource.java
/** * Processes the given JAR file pattern source. The classpath * will be searched for JAR files that contain files that match * the given pattern./*from w w w . j a v a 2 s .c om*/ * * NOTE: Currently only files within the META-INF folder are supported * i.e. patterns that look like "jar:*!/META-INF/[filename]" * * @param sourcePattern The wildcard pattern for files to find within JARs */ protected void processWildcardJarSource(String sourcePattern) { String file = sourcePattern.substring(7); if (file.startsWith(META_INF) == false) { throw new UnsupportedOperationException( "Only JAR file wildcard searches within the META-INF folder are currently supported"); } try { if (applicationContext == null) { // get a list of all the JAR files that have the META-INF folder Enumeration<URL> urls = this.getClass().getClassLoader().getResources(META_INF); while (urls.hasMoreElements()) { URL url = urls.nextElement(); // only add the item if is a reference to a JAR file if (url.getProtocol().equals(JarConfigSource.JAR_PROTOCOL)) { URLConnection conn = url.openConnection(); if (conn instanceof JarURLConnection) { // open the jar file and see if it contains what we're looking for JarURLConnection jarConn = (JarURLConnection) conn; JarFile jar = ((JarURLConnection) conn).getJarFile(); ZipEntry entry = jar.getEntry(file); if (entry != null) { if (logger.isInfoEnabled()) logger.info("Found " + file + " in " + jarConn.getJarFileURL()); String sourceString = JarConfigSource.JAR_PROTOCOL + ":" + jarConn.getJarFileURL().toExternalForm() + JarConfigSource.JAR_PATH_SEPARATOR + file; super.addSourceString(sourceString); } else if (logger.isDebugEnabled()) { logger.debug("Did not find " + file + " in " + jarConn.getJarFileURL()); } } } } } else { Resource[] resources = applicationContext.getResources(PREFIX_CLASSPATH_ALL + file); for (Resource resource : resources) { URL resourceUrl = resource.getURL(); if (ResourceUtils.isJarURL(resourceUrl) || ResourceUtils.URL_PROTOCOL_VFSZIP.equals(resourceUrl.getProtocol())) { URL jarURL = extractJarFileURL(resourceUrl); String sourceString = JarConfigSource.JAR_PROTOCOL + ":" + jarURL.toString() + JarConfigSource.JAR_PATH_SEPARATOR + file; super.addSourceString(sourceString); } else if (ResourceUtils.URL_PROTOCOL_VFS.equals(resourceUrl.getProtocol())) { super.addSourceString(resourceUrl.toString()); } } } } catch (IOException ioe) { if (logger.isDebugEnabled()) logger.debug("Failed to process JAR file wildcard: " + sourcePattern, ioe); } }