List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:demo.config.diff.support.ConfigurationMetadataRepositoryLoader.java
private Resource load(ConfigurationMetadataRepositoryJsonBuilder builder, String moduleId, String version, boolean mandatory) throws IOException { String coordinates = moduleId + ":" + version; try {/*from w ww . j av a 2 s .c o m*/ ArtifactResult artifactResult = dependencyResolver.resolveDependency(coordinates); File file = artifactResult.getArtifact().getFile(); JarFile jarFile = new JarFile(file); ZipEntry entry = jarFile.getEntry("META-INF/spring-configuration-metadata.json"); if (entry != null) { logger.info("Adding meta-data from '" + coordinates + "'"); try (InputStream stream = jarFile.getInputStream(entry)) { builder.withJsonResource(stream); } } else { logger.info("No meta-data found for '" + coordinates + "'"); } } catch (ArtifactResolutionException e) { if (mandatory) { throw new UnknownSpringBootVersion("Could not load '" + coordinates + "'", version); } logger.info("Ignoring '" + coordinates + " (not found)"); } return null; }
From source file:org.jahia.modules.serversettings.portlets.WebSpherePortletHelper.java
@Override boolean needsProcessing(JarFile jar) { ZipEntry webXml = jar.getEntry("WEB-INF/web.xml"); if (webXml == null) { return false; }/*from w w w . ja va 2 s . c om*/ boolean doProcess = false; InputStream is = null; try { is = jar.getInputStream(webXml); String webXmlContent = IOUtils.toString(is, "UTF-8"); doProcess = webXmlContent != null && !webXmlContent.contains("com.ibm.websphere.portletcontainer.PortletDeploymentEnabled"); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } return doProcess; }
From source file:cc.creativecomputing.io.CCIOUtil.java
/** * Simplified method to open a Java InputStream. * <p>//from w ww .java 2s . c o m * This method is useful if you want to easily open things from the data folder or from a URL, but want an * InputStream object so that you can use other Java methods to take more control of how the stream is read. * </p> * <p> * If the requested item doesn't exist, null is returned. This will also check to see if the user is asking for a * file whose name isn't properly capitalized. It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way. * </p> * * @param theFilename The filename passed in can be: * <ul> * <li>An URL, for instance openStream("http://creativecomputing.cc/");</li> * <li>A file in the application's data folder</li> * <li>Another file to be opened locally</li> * </ul> */ static public InputStream createStream(String theFilename) { InputStream stream = null; // check if the filename makes sense if (theFilename == null || theFilename.length() == 0) return null; // safe to check for this as a url first. this will prevent online try { URL urlObject = new URL(theFilename); URLConnection con = urlObject.openConnection(); // try to be a browser some sources do not like bots con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)"); return con.getInputStream(); } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. } catch (IOException e) { return null; } // load resource from jar using the path with getResourceAsStream if (theFilename.contains(".jar!")) { String[] myParts = theFilename.split("!"); String myJarPath = myParts[0]; if (myJarPath.startsWith("file:")) { myJarPath = myJarPath.substring(5); } String myFilePath = myParts[1]; if (myFilePath.startsWith("/")) { myFilePath = myFilePath.substring(1); } try { @SuppressWarnings("resource") JarFile myJarFile = new JarFile(myJarPath); return myJarFile.getInputStream(myJarFile.getEntry(myFilePath)); } catch (IOException e) { e.printStackTrace(); } } // handle case sensitivity check try { // first see if it's in a data folder File file = dataFile(theFilename); if (!file.exists()) { // next see if it's just in this folder file = new File(CCSystem.applicationPath, theFilename); } if (file.exists()) { try { String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(theFilename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + theFilename + ". Re-name it " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(theFilename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(appPath(theFilename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(theFilename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:Zip.java
/** * Reads a Jar file, displaying the attributes in its manifest and dumping * the contents of each file contained to the console. *///w ww .j ava 2 s.c o m public static void readJarFile(String fileName) { JarFile jarFile = null; try { // JarFile extends ZipFile and adds manifest information jarFile = new JarFile(fileName); if (jarFile.getManifest() != null) { System.out.println("Manifest Main Attributes:"); Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator(); while (iter.hasNext()) { Attributes.Name attribute = (Attributes.Name) iter.next(); System.out.println( attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute)); } System.out.println(); } // use the Enumeration to dump the contents of each file to the console System.out.println("Jar file entries:"); for (Enumeration e = jarFile.entries(); e.hasMoreElements();) { JarEntry jarEntry = (JarEntry) e.nextElement(); if (!jarEntry.isDirectory()) { System.out.println(jarEntry.getName() + " contains:"); BufferedReader jarReader = new BufferedReader( new InputStreamReader(jarFile.getInputStream(jarEntry))); while (jarReader.ready()) { System.out.println(jarReader.readLine()); } jarReader.close(); } } } catch (IOException ioe) { System.out.println("An IOException occurred: " + ioe.getMessage()); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { } } } }
From source file:dk.netarkivet.common.utils.batch.ByteJarLoader.java
/** * Constructor for the ByteLoader./*from w w w.j a v a2s . co m*/ * * @param files * An array of files, which are assumed to be jar-files, but * they need not have the extension .jar */ public ByteJarLoader(File... files) { ArgumentNotValid.checkNotNull(files, "File ... files"); ArgumentNotValid.checkTrue(files.length != 0, "Should not be empty array"); for (File file : files) { try { JarFile jarFile = new JarFile(file); for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); String name = entry.getName(); InputStream in = jarFile.getInputStream(entry); ByteArrayOutputStream out = new ByteArrayOutputStream((int) entry.getSize()); StreamUtils.copyInputStreamToOutputStream(in, out); log.trace("Entering data for class '" + name + "'"); binaryData.put(name, out.toByteArray()); } } catch (IOException e) { throw new IOFailure("Failed to load jar file '" + file.getAbsolutePath() + "': " + e); } } }
From source file:org.xwiki.webjars.internal.FilesystemResourceReferenceCopier.java
private void processCSSfile(String resourcePrefix, String targetPrefix, JarEntry entry, JarFile jar, FilesystemExportContext exportContext) throws Exception { // Limitation: we only support url() constructs located on a single line try (BufferedReader br = new BufferedReader(new InputStreamReader(jar.getInputStream(entry), "UTF-8"))) { String line;/*from w w w . j av a 2 s. c om*/ while ((line = br.readLine()) != null) { Matcher matcher = URL_PATTERN.matcher(line); while (matcher.find()) { String url = matcher.group(1); // Determine if URL is relative if (isRelativeURL(url)) { // Remove any query string part and any fragment part too url = StringUtils.substringBefore(url, "?"); url = StringUtils.substringBefore(url, "#"); // Normalize paths String resourceName = String.format(CONCAT_PATH_FORMAT, StringUtils.substringBeforeLast(entry.getName(), "/"), url); resourceName = new URI(resourceName).normalize().getPath(); resourceName = resourceName.substring(resourcePrefix.length() + 1); // Copy to filesystem copyResourceFromJAR(resourcePrefix, resourceName, targetPrefix, exportContext); } } } } }
From source file:com.taobao.android.builder.tools.asm.MethodReplacer.java
@Override protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) { try {/*from ww w . j av a 2 s. c o m*/ InputStream jarFileInputStream = jarFile.getInputStream(ze); ClassReader classReader = new ClassReader(jarFileInputStream); ClassWriter classWriter = new ClassWriter(0); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(jar.getAbsolutePath()).append(".").append(pathName); classReader.accept(new MethodReplaceClazzVisitor(Opcodes.ASM4, classWriter, methodStore, stringBuilder), ClassReader.EXPAND_FRAMES); ByteArrayInputStream inputStream = new ByteArrayInputStream(classWriter.toByteArray()); copyStreamToJar(inputStream, jos, pathName, ze.getTime()); IOUtils.closeQuietly(inputStream); } catch (Throwable e) { System.err.println("[MethodReplacer] rewrite error > " + pathName); justCopy(jarFile, jos, ze, pathName); } }
From source file:com.taobao.android.builder.tools.asm.ClazzBasicHandler.java
protected void justCopy(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) { try {/* w w w . j a v a 2 s .co m*/ InputStream inputStream = jarFile.getInputStream(ze); copyStreamToJar(inputStream, jos, pathName, ze.getTime()); } catch (Exception e) { logger.error("justCopy exception", e); } }
From source file:com.samczsun.helios.handler.addons.JarLauncher.java
@Override public void run(File file) { JarFile jarFile = null; InputStream inputStream = null; try {//from ww w. j a va 2 s . com System.out.println("Loading addon: " + file.getAbsolutePath()); jarFile = new JarFile(file); ZipEntry entry = jarFile.getEntry("addon.json"); if (entry != null) { inputStream = jarFile.getInputStream(entry); JsonObject jsonObject = JsonObject .readFrom(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); String main = jsonObject.get("main").asString(); URL[] url = new URL[] { file.toURI().toURL() }; ClassLoader classLoader = AccessController .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url, Helios.class.getClassLoader())); Class<?> clazz = Class.forName(main, true, classLoader); if (Addon.class.isAssignableFrom(clazz)) { Addon addon = Addon.class.cast(clazz.newInstance()); registerAddon(addon.getName(), addon); } else { throw new IllegalArgumentException("Addon main does not extend Addon"); } } else { throw new IllegalArgumentException("No addon.json found"); } } catch (Exception e) { ExceptionHandler.handle(e); } finally { IOUtils.closeQuietly(jarFile); IOUtils.closeQuietly(inputStream); } }
From source file:com.heliosdecompiler.helios.controller.addons.JarLauncher.java
@Override public void run(File file) { JarFile jarFile = null; InputStream inputStream = null; try {/* w w w . j a v a 2 s . c om*/ System.out.println("Loading addon: " + file.getAbsolutePath()); jarFile = new JarFile(file); ZipEntry entry = jarFile.getEntry("addon.json"); if (entry != null) { inputStream = jarFile.getInputStream(entry); JsonObject jsonObject = new Gson() .fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), JsonObject.class); String main = jsonObject.get("main").getAsString(); URL[] url = new URL[] { file.toURI().toURL() }; ClassLoader classLoader = AccessController .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url, Helios.class.getClassLoader())); Class<?> clazz = Class.forName(main, true, classLoader); if (Addon.class.isAssignableFrom(clazz)) { Addon addon = Addon.class.cast(clazz.newInstance()); // registerAddon(addon.getName(), addon); } else { throw new IllegalArgumentException("Addon main does not extend Addon"); } } else { throw new IllegalArgumentException("No addon.json found"); } } catch (Exception e) { ExceptionHandler.handle(e); } finally { IOUtils.closeQuietly(jarFile); IOUtils.closeQuietly(inputStream); } }