List of usage examples for java.util.jar JarFile getJarEntry
public JarEntry getJarEntry(String name)
From source file:com.panet.imeta.job.JobEntryLoader.java
/** * Search through all jarfiles in all steps and try to find a certain file * in it./*from w w w. j a va 2s . c o m*/ * * @param filename * @return an inputstream for the given file. */ public InputStream getInputStreamForFile(String filename) { JobPlugin[] jobplugins = getJobEntriesWithType(JobPlugin.TYPE_PLUGIN); for (JobPlugin jobPlugin : jobplugins) { try { String[] jarfiles = jobPlugin.getJarfiles(); if (jarfiles != null) { for (int j = 0; j < jarfiles.length; j++) { JarFile jarFile = new JarFile(jarfiles[j]); JarEntry jarEntry; if (filename.startsWith("/")) { jarEntry = jarFile.getJarEntry(filename.substring(1)); } else { jarEntry = jarFile.getJarEntry(filename); } if (jarEntry != null) { InputStream inputStream = jarFile.getInputStream(jarEntry); if (inputStream != null) { return inputStream; } } } } } catch (Exception e) { // Just look for the next one... } } return null; }
From source file:ffx.FFXClassLoader.java
/** * {@inheritDoc}// www. j av a 2 s . com * * Finds and defines the given class among the extension JARs given in * constructor, then among resources. */ @Override protected Class findClass(String name) throws ClassNotFoundException { /* if (name.startsWith("com.jogamp")) { System.out.println(" Class requested:" + name); } */ if (!extensionsLoaded) { loadExtensions(); } // Build class file from its name String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (extensionJars != null) { for (JarFile extensionJar : extensionJars) { JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } // If it's not an extension class, search if its an application // class that can be read from resources if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } ByteArrayOutputStream out = null; BufferedInputStream in = null; try { // Read class input content to a byte array out = new ByteArrayOutputStream(); in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8192]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } // Define class return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { throw new ClassNotFoundException("Class " + name, e); } } }
From source file:UnpackedJarFile.java
public static String readAll(URL url) throws IOException { Reader reader = null;/*from w ww.j ava2 s. c om*/ JarFile jarFile = null; try { if (url.getProtocol().equalsIgnoreCase("jar")) { // url.openStream() locks the jar file and does not release the lock even after the stream is closed. // This problem is avoided by using JarFile APIs. File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/"))); String path = url.getFile().substring(url.getFile().indexOf("!/") + 2); jarFile = new JarFile(file); JarEntry jarEntry = jarFile.getJarEntry(path); if (jarEntry != null) { reader = new InputStreamReader(jarFile.getInputStream(jarEntry)); } else { throw new FileNotFoundException("JarEntry " + path + " not found in " + file); } } else { reader = new InputStreamReader(url.openStream()); } char[] buffer = new char[4000]; StringBuffer out = new StringBuffer(); for (int count = reader.read(buffer); count >= 0; count = reader.read(buffer)) { out.append(buffer, 0, count); } return out.toString(); } finally { close(reader); close(jarFile); } }
From source file:UnpackedJarFile.java
public static File toTempFile(URL url) throws IOException { InputStream in = null;//from w ww. j av a 2 s .com OutputStream out = null; JarFile jarFile = null; try { if (url.getProtocol().equalsIgnoreCase("jar")) { // url.openStream() locks the jar file and does not release the lock even after the stream is closed. // This problem is avoided by using JarFile APIs. File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/"))); String path = url.getFile().substring(url.getFile().indexOf("!/") + 2); jarFile = new JarFile(file); JarEntry jarEntry = jarFile.getJarEntry(path); if (jarEntry != null) { in = jarFile.getInputStream(jarEntry); } else { throw new FileNotFoundException("JarEntry " + path + " not found in " + file); } } else { in = url.openStream(); } int index = url.getPath().lastIndexOf("."); String extension = null; if (index > 0) { extension = url.getPath().substring(index); } File tempFile = createTempFile(extension); out = new FileOutputStream(tempFile); writeAll(in, out); return tempFile; } finally { close(out); close(in); close(jarFile); } }
From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java
@Override public Void call() throws Exception { CodeSource codeSource = getClass().getProtectionDomain().getCodeSource(); boolean goodFML = false; boolean fmlIsJar = false; if (codeSource.getLocation().getProtocol().equals("jar")) { fmlIsJar = true;//w w w. j a va 2 s .c o m Certificate[] certificates = codeSource.getCertificates(); if (certificates != null) { for (Certificate cert : certificates) { String fingerprint = CertificateHelper.getFingerprint(cert); if (fingerprint.equals(FMLFINGERPRINT)) { FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint); goodFML = true; } else if (fingerprint.equals(FORGEFINGERPRINT)) { FMLRelaunchLog.info( "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint); goodFML = true; } else { FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint); } } } } else { goodFML = true; } // Server is not signed, so assume it's good - a deobf env is dev time so it's good too boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv; int certCount = 0; try { Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl); codeSource = cbr.getProtectionDomain().getCodeSource(); } catch (Exception e) { // Probably a development environment, or the server (the server is not signed) goodMC = true; } JarFile mcJarFile = null; if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) { try { String mcPath = codeSource.getLocation().getPath().substring(5); mcPath = mcPath.substring(0, mcPath.lastIndexOf('!')); mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name()); mcJarFile = new JarFile(mcPath, true); mcJarFile.getManifest(); JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class"); InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry); try { ByteStreams.toByteArray(mcJarFileInputStream); } finally { IOUtils.closeQuietly(mcJarFileInputStream); } Certificate[] certificates = cbrEntry.getCertificates(); certCount = certificates != null ? certificates.length : 0; if (certificates != null) { for (Certificate cert : certificates) { String fingerprint = CertificateHelper.getFingerprint(cert); if (fingerprint.equals(MCFINGERPRINT)) { FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint); goodMC = true; } } } } catch (Throwable e) { FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file"); } finally { Java6Utils.closeZipQuietly(mcJarFile); } } else { goodMC = true; } if (!goodMC) { FMLRelaunchLog.severe( "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!", codeSource.getLocation().getFile()); if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) { FMLRelaunchLog.severe( "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file"); FMLRelaunchLog.severe( "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile."); FMLCommonHandler.instance().exitJava(1, false); } else { FMLRelaunchLog.severe( "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!"); FMLRelaunchLog.severe( "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount); } } if (!goodFML) { FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing"); } return null; }
From source file:com.eviware.soapui.DefaultSoapUICore.java
protected void initPlugins() { File[] pluginFiles = new File("plugins").listFiles(); if (pluginFiles != null) { for (File pluginFile : pluginFiles) { if (!pluginFile.getName().toLowerCase().endsWith("-plugin.jar")) continue; try { log.info("Adding plugin from [" + pluginFile.getAbsolutePath() + "]"); // add jar to our extension classLoader getExtensionClassLoader().addFile(pluginFile); JarFile jarFile = new JarFile(pluginFile); // look for factories JarEntry entry = jarFile.getJarEntry("META-INF/factories.xml"); if (entry != null) getFactoryRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader); // look for listeners entry = jarFile.getJarEntry("META-INF/listeners.xml"); if (entry != null) getListenerRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader); // look for actions entry = jarFile.getJarEntry("META-INF/actions.xml"); if (entry != null) getActionRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader); // add jar to resource classloader so embedded images can be found with UISupport.loadImageIcon(..) UISupport.addResourceClassLoader(new URLClassLoader(new URL[] { pluginFile.toURI().toURL() })); } catch (Exception e) { SoapUI.logError(e);/* w w w . j a v a 2s . c o m*/ } } } }
From source file:com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.java
/** * Check whether the artifact includes a BuildConfig located in a given package. * /* ww w . jav a2 s. co m*/ * @param artifact an AAR artifact to look for BuildConfig in * @param packageName BuildConfig package name * @throws MojoExecutionException */ private boolean isBuildConfigPresent(Artifact artifact, String packageName) throws MojoExecutionException { try { JarFile jar = new JarFile(getUnpackedAarClassesJar(artifact)); JarEntry entry = jar.getJarEntry(packageName.replace('.', '/') + "/BuildConfig.class"); return (entry != null); } catch (IOException e) { getLog().error("Error generating BuildConfig ", e); throw new MojoExecutionException("Error generating BuildConfig", e); } }
From source file:UnpackedJarFile.java
public NestedJarFile(JarFile jarFile, String path) throws IOException { super(DeploymentUtil.DUMMY_JAR_FILE); // verify that the jar actually contains that path JarEntry targetEntry = jarFile.getJarEntry(path + "/"); if (targetEntry == null) { targetEntry = jarFile.getJarEntry(path); if (targetEntry == null) { throw new IOException("Jar entry does not exist: jarFile=" + jarFile.getName() + ", path=" + path); }//from w w w.ja va 2 s.c om } if (targetEntry.isDirectory()) { if (targetEntry instanceof UnpackedJarEntry) { //unpacked nested module inside unpacked ear File targetFile = ((UnpackedJarEntry) targetEntry).getFile(); baseJar = new UnpackedJarFile(targetFile); basePath = ""; } else { baseJar = jarFile; if (!path.endsWith("/")) { path += "/"; } basePath = path; } } else { if (targetEntry instanceof UnpackedJarEntry) { // for unpacked jars we don't need to copy the jar file // out to a temp directory, since it is already available // as a raw file File targetFile = ((UnpackedJarEntry) targetEntry).getFile(); baseJar = new JarFile(targetFile); basePath = ""; } else { tempFile = DeploymentUtil.toFile(jarFile, targetEntry.getName()); baseJar = new JarFile(tempFile); basePath = ""; } } }
From source file:com.impetus.kundera.classreading.ClasspathReader.java
/** * Scan class resource in the provided urls with the additional Class-Path * of each jar checking/*from w ww .j a v a 2 s.c o m*/ * * @param classRelativePath * relative path to a class resource * @param urls * urls to be checked * @return list of class path included in the base package */ private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) { List<URL> list = new ArrayList<URL>(); for (URL url : urls) { if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase()) && url.getPath().endsWith(".jar")) { try { JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8)); // Checking the dependencies of this jar file Manifest manifest = jarFile.getManifest(); if (manifest != null) { String classPath = manifest.getMainAttributes().getValue("Class-Path"); // Scan all entries in the classpath if they are // specified in the jar if (!StringUtils.isEmpty(classPath)) { List<URL> subList = new ArrayList<URL>(); for (String cpEntry : classPath.split(" ")) { try { subList.add(new URL(cpEntry)); } catch (MalformedURLException e) { URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry); if (subResources != null) { subList.add(subResources); } // logger.warn("Incorrect URL in the classpath of a jar file [" // + url.toString() // + "]: " + cpEntry); } } list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath, subList.toArray(new URL[subList.size()])))); } } JarEntry present = jarFile.getJarEntry(classRelativePath + ".class"); if (present != null) { list.add(url); } } catch (IOException e) { logger.warn("Error during loading from context , Caused by:" + e.getMessage()); } } else if (url.getPath().endsWith("/")) { File file = new File(url.getPath() + classRelativePath + ".class"); if (file.exists()) { try { list.add(file.toURL()); } catch (MalformedURLException e) { throw new ResourceReadingException(e); } } } } return list.toArray(new URL[list.size()]); }
From source file:org.apache.catalina.startup.HostConfig.java
/** * Deploy WAR files.//from w w w . j av a 2s .c om */ protected void deployWARs(File appBase, String[] files) { for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; if (deployed.contains(files[i])) continue; File dir = new File(appBase, files[i]); if (files[i].toLowerCase().endsWith(".war")) { deployed.add(files[i]); // Calculate the context path and make sure it is unique String contextPath = "/" + files[i]; int period = contextPath.lastIndexOf("."); if (period >= 0) contextPath = contextPath.substring(0, period); if (contextPath.equals("/ROOT")) contextPath = ""; if (host.findChild(contextPath) != null) continue; // Checking for a nested /META-INF/context.xml JarFile jar = null; JarEntry entry = null; InputStream istream = null; BufferedOutputStream ostream = null; File xml = new File(configBase, files[i].substring(0, files[i].lastIndexOf(".")) + ".xml"); if (!xml.exists()) { try { jar = new JarFile(dir); entry = jar.getJarEntry("META-INF/context.xml"); if (entry != null) { istream = jar.getInputStream(entry); ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; entry = null; jar.close(); jar = null; deployDescriptors(configBase(), configBase.list()); return; } } catch (Exception e) { // Ignore and continue if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ; } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ; } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (Throwable t) { ; } jar = null; } } } if (isUnpackWARs()) { // Expand and deploy this application as a directory log.debug(sm.getString("hostConfig.expand", files[i])); URL url = null; String path = null; try { url = new URL("jar:file:" + dir.getCanonicalPath() + "!/"); path = ExpandWar.expand(host, url); } catch (IOException e) { // JAR decompression failure log.warn(sm.getString("hostConfig.expand.error", files[i])); continue; } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); continue; } try { if (path != null) { url = new URL("file:" + path); ((Deployer) host).install(contextPath, url); } } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); } } else { // Deploy the application in this WAR file log.info(sm.getString("hostConfig.deployJar", files[i])); try { URL url = new URL("file", null, dir.getCanonicalPath()); url = new URL("jar:" + url.toString() + "!/"); ((Deployer) host).install(contextPath, url); } catch (Throwable t) { log.error(sm.getString("hostConfig.deployJar.error", files[i]), t); } } } } }