List of usage examples for java.net JarURLConnection getJarFile
public abstract JarFile getJarFile() throws IOException;
From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java
private void loadMetaClassesFromPath(String pathName) { try {// w w w . ja v a 2 s . com URL url = MetadataDataLoader.class.getResource(pathName); URI uri = url.toURI(); BasicDBList metas = new BasicDBList(); if (uri.isOpaque()) { JarURLConnection connection = (JarURLConnection) url.openConnection(); JarFile jar = connection.getJarFile(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(pathName.substring(1)) && entry.getName().endsWith(".json")) { InputStream is = jar.getInputStream(entry); readMetaClass(is, metas); } } } else { File dir = new File(url.toURI()); Collection<File> files = FileUtils.listFiles(dir, new String[] { "json" }, true); for (File f : files) { InputStream is = new FileInputStream(f); readMetaClass(is, metas); } } loadMetaClasses(metas); } catch (Exception e) { logger.error("error in loading metadata: ", e); } }
From source file:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java
@Override public void retrieveBuildInformation() { try {/*from www. ja va 2 s . c o m*/ URL urlToMavenPom = JahiaLogAnalyzerImpl.class.getClassLoader() .getResource("/META-INF/jahia-loganalyzer-marker.txt"); if (urlToMavenPom != null) { URLConnection urlConnection = urlToMavenPom.openConnection(); if (urlConnection instanceof JarURLConnection) { JarURLConnection conn = (JarURLConnection) urlConnection; JarFile jarFile = conn.getJarFile(); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); buildNumber = attributes.getValue("Implementation-Build"); version = attributes.getValue("Implementation-Version"); String buildTimestampValue = attributes.getValue("Implementation-Timestamp"); if (buildTimestampValue != null) { try { long buildTimestampTime = Long.parseLong(buildTimestampValue); buildTimestamp = new Date(buildTimestampTime); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } } } } catch (IOException ioe) { log.error("Error while trying to retrieve build information", ioe); } catch (NumberFormatException nfe) { log.error("Error while trying to retrieve build information", nfe); } }
From source file:org.ops4j.pax.scanner.dir.internal.DirScanner.java
/** * Reads the bundles from the file specified by the urlSpec. * {@inheritDoc}//from ww w . j a v a2 s . com */ public List<ScannedBundle> scan(final ProvisionSpec provisionSpec) throws MalformedSpecificationException, ScannerException { NullArgumentException.validateNotNull(provisionSpec, "Provision spec"); LOGGER.debug("Scanning [" + provisionSpec.getPath() + "]"); final ScannerConfiguration config = createConfiguration(); final Pattern filter = provisionSpec.getFilterPattern(); final String spec = provisionSpec.getPath(); final Integer defaultStartLevel = getDefaultStartLevel(provisionSpec, config); final Boolean defaultStart = getDefaultStart(provisionSpec, config); final Boolean defaultUpdate = getDefaultUpdate(provisionSpec, config); // try out an url LOGGER.trace("Searching for [" + spec + "]"); URL url = null; try { url = new URL(spec); } catch (MalformedURLException ignore) { // ignore this as the spec may be resolved other way LOGGER.trace("Specification is not a valid url: " + ignore.getMessage() + ". Continue discovery..."); } File file = null; if (url != null && "file".equals(url.getProtocol())) // if we have an url and it's a file url { try { final URI uri = new URI(url.toExternalForm().replaceAll(" ", "%20")); file = new File(uri); } catch (Exception ignore) { // ignore this as the spec may be resolved other way LOGGER.trace("Specification is not a valid file url: " + ignore.getMessage() + ". Continue discovery..."); } } else // if we don't have an url then let's try out a direct file { file = new File(spec); } if (file != null && file.exists()) // if we have a directory { if (file.isDirectory()) { try { return list(new DirectoryLister(file, filter), defaultStartLevel, defaultStart, defaultUpdate); } catch (MalformedURLException e) { throw new MalformedSpecificationException(e); } } else { LOGGER.trace("Specification is not a directory. Continue discovery..."); } } else { LOGGER.trace("Specification is not a valid file. Continue discovery..."); } // on this point we may have a zip try { ZipFile zip = null; URL baseUrl = null; if (file != null && file.exists()) // try out a zip from the file we have { zip = new ZipFile(file); baseUrl = file.toURL(); } else if (url != null) { zip = new ZipFile(url.toExternalForm()); baseUrl = url; } if (zip != null && baseUrl != null) { try { return list(new ZipLister(baseUrl, zip.entries(), filter), defaultStartLevel, defaultStart, defaultUpdate); } catch (MalformedURLException e) { throw new MalformedSpecificationException(e); } } } catch (IOException ignore) { // ignore for the moment LOGGER.trace("Specification is not a valid zip: " + ignore.getMessage() + "Continue discovery..."); } // finaly try with a zip protocol if (url != null && !url.toExternalForm().startsWith("jar")) { try { final URL jarUrl = new URL("jar:" + url.toURI().toASCIIString() + "!/"); final JarURLConnection jar = (JarURLConnection) jarUrl.openConnection(); return list(new ZipLister(url, jar.getJarFile().entries(), filter), defaultStartLevel, defaultStart, defaultUpdate); } catch (Exception ignore) { LOGGER.trace("Specification is not a valid jar: " + ignore.getMessage()); } } // if we got to this point then we cannot go further LOGGER.trace("Specification urlSpec cannot be used. Stopping."); throw new MalformedSpecificationException( "Specification [" + provisionSpec.getPath() + "] could not be used"); }
From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java
public void contextInitialized(ServletContextEvent sce) { ServletContext application = sce.getServletContext(); Map<String, String> bundles = new HashMap<String, String>(); Map<String, Toc> contents = new LinkedHashMap<String, Toc>(); List<IndexEntry> keywords = new ArrayList<IndexEntry>(); Directory index = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer); IndexWriter indexWriter;/* www . j a v a 2s .com*/ try { indexWriter = new IndexWriter(index, indexWriterConfig); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); indexWriter = null; } for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) { if (path.endsWith(".jar")) { String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar")); application.log("Parsing " + path); URLConnection connection = null; try { URL url = new URL("jar:" + application.getResource(path) + "!/"); connection = url.openConnection(); if (!(connection instanceof JarURLConnection)) { application.log(path + " is not a jar file, ignoring"); continue; } JarURLConnection jarConnection = (JarURLConnection) connection; JarFile jarFile = jarConnection.getJarFile(); Manifest manifest = jarFile.getManifest(); if (manifest != null) { String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName != null) { int i = symbolicName.indexOf(';'); if (i != -1) { symbolicName = symbolicName.substring(0, i); } bundles.put(symbolicName, key); key = symbolicName; } } JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml"); if (pluginEntry == null) { application.log(path + " does not contain a plugin.xml file, ignoring"); continue; } Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry)); Extension tocExtension = plugin.getExtension("org.eclipse.help.toc"); if (tocExtension == null || tocExtension.getFile("toc") == null) { application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring"); continue; } JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc")); if (tocEntry == null) { application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc") + ", ignoring"); continue; } Toc toc; try { toc = Toc.read(jarFile.getInputStream(tocEntry)); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); continue; } contents.put(key, toc); Extension indexExtension = plugin.getExtension("org.eclipse.help.index"); if (indexExtension != null && indexExtension.getFile("index") != null) { JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index")); if (indexEntry != null) { try { keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren()); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } } else { application.log( path + " is missing the referenced index: " + indexExtension.getFile("index")); } } application.log(path + " successfully parsed and added as " + key); if (indexWriter != null) { application.log("Indexing content of " + path); Set<String> files = new HashSet<String>(); Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>(); stack.push(Collections.singleton(toc).iterator()); while (!stack.empty()) { Iterator<? extends TocEntry> cur = stack.pop(); if (cur.hasNext()) { TocEntry entry = cur.next(); stack.push(cur); if (!entry.getChildren().isEmpty()) { stack.push(entry.getChildren().iterator()); } String file = entry.getHref(); if (file == null) { continue; } int hashIndex = file.indexOf('#'); if (hashIndex != -1) { file = file.substring(0, hashIndex); } if (files.contains(file)) { // already indexed // todo work out whether to just pull the section continue; } Document document = new Document(); document.add(new Field("title", entry.getLabel(), Field.Store.YES, Field.Index.ANALYZED)); document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES, Field.Index.NO)); JarEntry docEntry = jarFile.getJarEntry(file); if (docEntry == null) { // ignore missing file continue; } InputStream inputStream = null; try { inputStream = jarFile.getInputStream(docEntry); org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream)); document.add(new Field("contents", docDoc.body().text(), Field.Store.NO, Field.Index.ANALYZED)); indexWriter.addDocument(document); } finally { IOUtils.closeQuietly(inputStream); } } } } } catch (XMLStreamException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (MalformedURLException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (IOException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } finally { if (connection instanceof HttpURLConnection) { // should never be the case, but we should try to be sure ((HttpURLConnection) connection).disconnect(); } } } } if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); } application.setAttribute("index", index); } application.setAttribute("toc", Collections.unmodifiableMap(contents)); application.setAttribute("keywords", new Index(keywords)); application.setAttribute("bundles", Collections.unmodifiableMap(bundles)); application.setAttribute("analyzer", analyzer); application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer)); }
From source file:org.doctester.rendermachine.RenderMachineImpl.java
private void unzipFromJar(String classpathLocation, String destinationDirectory) { try {//from w ww .j a va 2s . c o m URL url = this.getClass().getClassLoader().getResource(classpathLocation); JarURLConnection urlcon = (JarURLConnection) (url.openConnection()); try (JarFile jar = urlcon.getJarFile();) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.isDirectory()) { new File(destinationDirectory + File.separator + jarEntry.getName()).mkdirs(); } else { ByteStreams.copy(jar.getInputStream(jarEntry), new FileOutputStream( new File(destinationDirectory + File.separator + jarEntry.getName()))); } } } } catch (IOException e) { logger.error("An error occurred while copying from webjars archive to site directory", e); } }
From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java
public DefaultClassFinder(ClassLoaderInterface classLoaderInterface, Collection<URL> urls, boolean extractBaseInterfaces, Set<String> protocols, Test<String> classNameFilter) { this.classLoaderInterface = classLoaderInterface; this.extractBaseInterfaces = extractBaseInterfaces; this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager(); List<String> classNames = new ArrayList<String>(); for (URL location : urls) { try {// ww w. ja v a2s. c om if (protocols.contains(location.getProtocol())) { classNames.addAll(jar(location)); } else if ("file".equals(location.getProtocol())) { try { // See if it's actually a jar URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/"); JarURLConnection juc = (JarURLConnection) jarUrl.openConnection(); juc.getJarFile(); classNames.addAll(jar(jarUrl)); } catch (IOException e) { classNames.addAll(file(location)); } } } catch (Exception e) { LOG.error("Unable to read URL [{}]", location.toExternalForm(), e); } } for (String className : classNames) { try { if (classNameFilter.test(className)) readClassDef(className); } catch (Throwable e) { LOG.error("Unable to read class [{}]", className, e); } } }
From source file:org.apache.struts2.convention.Java8ClassFinder.java
public Java8ClassFinder(ClassLoaderInterface classLoaderInterface, Collection<URL> urls, boolean extractBaseInterfaces, Set<String> protocols, Test<String> classNameFilter) { this.classLoaderInterface = classLoaderInterface; this.extractBaseInterfaces = extractBaseInterfaces; this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager(); List<String> classNames = new ArrayList<String>(); for (URL location : urls) { try {/* w w w. j a v a 2s . c o m*/ if (protocols.contains(location.getProtocol())) { classNames.addAll(jar(location)); } else if ("file".equals(location.getProtocol())) { try { // See if it's actually a jar URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/"); JarURLConnection juc = (JarURLConnection) jarUrl.openConnection(); juc.getJarFile(); classNames.addAll(jar(jarUrl)); } catch (IOException e) { classNames.addAll(file(location)); } } } catch (Exception e) { LOG.error("Unable to read URL [{}]", location.toExternalForm(), e); } } for (String className : classNames) { try { if (classNameFilter.test(className)) readClassDef(className); } catch (Throwable e) { LOG.error("Unable to read class [{}]", className, e); } } }
From source file:org.apache.struts2.convention.DefaultClassFinder.java
public DefaultClassFinder(ClassLoaderInterface classLoaderInterface, Collection<URL> urls, boolean extractBaseInterfaces, Set<String> protocols, Test<String> classNameFilter) { this.classLoaderInterface = classLoaderInterface; this.extractBaseInterfaces = extractBaseInterfaces; this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager(); List<String> classNames = new ArrayList<>(); for (URL location : urls) { try {//from w w w . j ava2 s . c o m if (protocols.contains(location.getProtocol())) { classNames.addAll(jar(location)); } else if ("file".equals(location.getProtocol())) { try { // See if it's actually a jar URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/"); JarURLConnection juc = (JarURLConnection) jarUrl.openConnection(); juc.getJarFile(); classNames.addAll(jar(jarUrl)); } catch (IOException e) { classNames.addAll(file(location)); } } } catch (Exception e) { LOG.error("Unable to read URL [{}]", location.toExternalForm(), e); } } for (String className : classNames) { try { if (classNameFilter.test(className)) readClassDef(className); } catch (Throwable e) { LOG.error("Unable to read class [{}]", className, e); } } }
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./*from w ww. ja v a 2 s .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.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. ja v a 2 s . 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(); } } }