List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.wavemaker.tools.ant.NewCopyRuntimeJarsTask.java
protected List<String> getReferencedClassPathJars(File jarFile, boolean failOnError) { try {//w w w. j a v a 2s . c om JarFile runtimeJar = new JarFile(jarFile); Manifest manifest = runtimeJar.getManifest(); String jarClassPath = manifest.getMainAttributes().getValue(CLASSPATH_ATTR_NAME); if (failOnError && jarClassPath == null) { throw new IllegalStateException(CLASSPATH_ATTR_NAME + " attribute is missing from " + jarFile); } else if (jarClassPath == null) { return new ArrayList<String>(); } String[] tokens = jarClassPath.split("\\s"); List<String> jarNames = new ArrayList<String>(tokens.length + 1); jarNames.add(jarFile.getName()); for (String jarName : jarClassPath.split("\\s")) { jarNames.add(jarName); } return jarNames; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java
/** * Get a JCE policy's details.//w w w . ja v a2s . co m * * @param jcePolicy * JCE policy * @return Policy details * @throws CryptoException * If there was a problem getting the policy details */ public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException { try { StringWriter sw = new StringWriter(); File file = getJarFile(jcePolicy); // if there is no policy file at all, return empty string if (!file.exists()) { return ""; } JarFile jar = new JarFile(file); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String entryName = jarEntry.getName(); if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) { sw.write(entryName + ":\n\n"); InputStreamReader isr = null; try { isr = new InputStreamReader(jar.getInputStream(jarEntry)); CopyUtil.copy(isr, sw); } finally { IOUtils.closeQuietly(isr); } sw.write('\n'); } } return sw.toString(); } catch (IOException ex) { throw new CryptoException( MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex); } }
From source file:com.photon.maven.plugins.android.standalonemojos.UnpackMojo.java
private File unpackClasses() throws MojoExecutionException { File outputDirectory = new File(project.getBuild().getDirectory(), "android-classes"); if (lazyLibraryUnpack && outputDirectory.exists()) getLog().info("skip library unpacking due to lazyLibraryUnpack policy"); else {/* w w w . jav a 2 s. c o m*/ for (Artifact artifact : getRelevantCompileArtifacts()) { if (artifact.getFile().isDirectory()) { try { FileUtils.copyDirectory(artifact.getFile(), outputDirectory); } catch (IOException e) { throw new MojoExecutionException( "IOException while copying " + artifact.getFile().getAbsolutePath() + " into " + outputDirectory.getAbsolutePath(), e); } } else { try { JarHelper.unjar(new JarFile(artifact.getFile()), outputDirectory, new JarHelper.UnjarListener() { @Override public boolean include(JarEntry jarEntry) { return !jarEntry.getName().startsWith("META-INF") && jarEntry.getName().endsWith(".class"); } }); } catch (IOException e) { throw new MojoExecutionException( "IOException while unjarring " + artifact.getFile().getAbsolutePath() + " into " + outputDirectory.getAbsolutePath(), e); } } } } try { File sourceDirectory = new File(project.getBuild().getDirectory(), "classes"); if (!sourceDirectory.exists()) { sourceDirectory.mkdirs(); } FileUtils.copyDirectory(sourceDirectory, outputDirectory); } catch (IOException e) { throw new MojoExecutionException("IOException while copying " + sourceDirectory.getAbsolutePath() + " into " + outputDirectory.getAbsolutePath(), e); } return outputDirectory; }
From source file:com.speed.ob.api.ClassStore.java
public void dump(File in, File out, Config config) throws IOException { if (in.isDirectory()) { for (ClassNode node : nodes()) { String[] parts = node.name.split("\\."); String dirName = node.name.substring(0, node.name.lastIndexOf(".")); dirName = dirName.replace(".", "/"); File dir = new File(out, dirName); if (!dir.exists()) { if (!dir.mkdirs()) throw new IOException("Could not make output dir: " + dir.getAbsolutePath()); }//from ww w . j a v a 2 s .c om ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); FileOutputStream fOut = new FileOutputStream( new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1))); fOut.write(data); fOut.flush(); fOut.close(); } } else if (in.getName().endsWith(".jar")) { File output = new File(out, in.getName()); JarFile jf = new JarFile(in); HashMap<JarEntry, Object> existingData = new HashMap<>(); if (output.exists()) { try { JarInputStream jarIn = new JarInputStream(new FileInputStream(output)); JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if (!entry.isDirectory()) { byte[] data = IOUtils.toByteArray(jarIn); existingData.put(entry, data); jarIn.closeEntry(); } } jarIn.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Could not read existing output file, overwriting", e); } } FileOutputStream fout = new FileOutputStream(output); Manifest manifest = null; if (jf.getManifest() != null) { manifest = jf.getManifest(); if (!config.getBoolean("ClassNameTransform.keep_packages") && config.getBoolean("ClassNameTransform.exclude_mains")) { manifest = new Manifest(manifest); if (manifest.getMainAttributes().getValue("Main-Class") != null) { String manifestName = manifest.getMainAttributes().getValue("Main-Class"); if (manifestName.contains(".")) { manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1); manifest.getMainAttributes().putValue("Main-Class", manifestName); } } } } jf.close(); JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout) : new JarOutputStream(fout, manifest); Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files"); if (!existingData.isEmpty()) { for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) { Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName()); jarOut.putNextEntry(entry.getKey()); jarOut.write((byte[]) entry.getValue()); jarOut.closeEntry(); } } for (ClassNode node : nodes()) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); int index = node.name.lastIndexOf("/"); String fileName; if (index > 0) { fileName = node.name.substring(0, index + 1).replace(".", "/"); fileName += node.name.substring(index + 1).concat(".class"); } else { fileName = node.name.concat(".class"); } JarEntry entry = new JarEntry(fileName); jarOut.putNextEntry(entry); jarOut.write(data); jarOut.closeEntry(); } jarOut.close(); } else { if (nodes().size() == 1) { File outputFile = new File(out, in.getName()); ClassNode node = nodes().iterator().next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); byte[] data = writer.toByteArray(); FileOutputStream stream = new FileOutputStream(outputFile); stream.write(data); stream.close(); } } }
From source file:de.xirp.plugin.PluginLoader.java
/** * Looks for plugins in the plugins directory. Plugins which needs * are not full filled are not accepted. * //from ww w. jav a2 s .c om * @param manager * instance of the plugin manager which is used for * notifying the application about the loading * progress. */ protected static void searchPlugins(PluginManager manager) { logClass.info(I18n.getString("PluginLoader.log.searchPlugins")); //$NON-NLS-1$ // Get all Files in the Plugin Directory with // Filetype jar File pluginDir = new File(Constants.PLUGIN_DIR); File[] fileList = pluginDir.listFiles(new FilenameFilter() { public boolean accept(@SuppressWarnings("unused") File dir, String filename) { return filename.endsWith(".jar"); //$NON-NLS-1$ } }); if (fileList != null) { double perFile = 1.0 / fileList.length; double cnt = 0; try { // Iterate over all jars and try to find // the plugin.properties file // The file is loaded and Information // extracted to PluginInfo // Plugin is added to List of Plugins for (File f : fileList) { String path = f.getAbsolutePath(); if (!plugins.containsKey(path)) { manager.throwLoaderProgressEvent( I18n.getString("PluginLoader.progress.searchingInFile", f.getName()), cnt); //$NON-NLS-1$ JarFile jar = new JarFile(path); JarEntry entry = jar.getJarEntry("plugin.properties"); //$NON-NLS-1$ if (entry != null) { InputStream input = jar.getInputStream(entry); Properties props = new Properties(); props.load(input); String mainClass = props.getProperty("plugin.mainclass"); //$NON-NLS-1$ PluginInfo info = new PluginInfo(path, mainClass, props); String packageName = ClassUtils.getPackageName(mainClass) + "." //$NON-NLS-1$ + AbstractPlugin.DEFAULT_BUNDLE_NAME; String bundleBaseName = packageName.replaceAll("\\.", "/"); //$NON-NLS-1$ //$NON-NLS-2$ for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry ent = entries.nextElement(); String name = ent.getName(); if (name.indexOf(bundleBaseName) != -1) { String locale = name .substring(name.indexOf(AbstractPlugin.DEFAULT_BUNDLE_NAME)); locale = locale.replaceAll(AbstractPlugin.DEFAULT_BUNDLE_NAME + "_", //$NON-NLS-1$ ""); //$NON-NLS-1$ locale = locale.substring(0, locale.indexOf(".properties")); //$NON-NLS-1$ Locale loc = new Locale(locale); info.addAvailableLocale(loc); } } PluginManager.extractAll(info); if (isPlugin(info)) { plugins.put(mainClass, info); } } } cnt += perFile; } } catch (IOException e) { logClass.error( I18n.getString("PluginLoader.log.errorSearchingforPlugins") + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ } } checkAllNeeds(); logClass.info(I18n.getString("PluginLoader.log.searchPluginsCompleted") + Constants.LINE_SEPARATOR); //$NON-NLS-1$ }
From source file:com.reactive.hzdfs.dll.JarModuleLoader.java
private static boolean isJarFile(File f) { try (JarFile j = new JarFile(f)) { return true; } catch (IOException e) { }/*from w w w . j av a 2s . co m*/ return false; }
From source file:org.commonjava.maven.galley.filearc.internal.ZipPublish.java
private Boolean rewriteArchive(final File dest, final String path) { final boolean isJar = isJarOperation(); final File src = new File(dest.getParentFile(), dest.getName() + ".old"); dest.renameTo(src);/*w ww . j a v a 2s . co m*/ InputStream zin = null; ZipFile zfIn = null; FileOutputStream fos = null; ZipOutputStream zos = null; ZipFile zfOut = null; try { fos = new FileOutputStream(dest); zos = isJar ? new JarOutputStream(fos) : new ZipOutputStream(fos); zfOut = isJar ? new JarFile(dest) : new ZipFile(dest); zfIn = isJar ? new JarFile(src) : new ZipFile(src); for (final Enumeration<? extends ZipEntry> en = zfIn.entries(); en.hasMoreElements();) { final ZipEntry inEntry = en.nextElement(); final String inPath = inEntry.getName(); try { if (inPath.equals(path)) { zin = stream; } else { zin = zfIn.getInputStream(inEntry); } final ZipEntry entry = zfOut.getEntry(inPath); zos.putNextEntry(entry); copy(stream, zos); } finally { closeQuietly(zin); } } return true; } catch (final IOException e) { error = new TransferException("Failed to write path: %s to EXISTING archive: %s. Reason: %s", e, path, dest, e.getMessage()); } finally { closeQuietly(zos); closeQuietly(fos); if (zfOut != null) { //noinspection EmptyCatchBlock try { zfOut.close(); } catch (final IOException e) { } } if (zfIn != null) { //noinspection EmptyCatchBlock try { zfIn.close(); } catch (final IOException e) { } } closeQuietly(stream); } return false; }
From source file:org.lightcouch.CouchDbUtil.java
/** * List directory contents for a resource folder. Not recursive. This is * basically a brute-force implementation. Works for regular files and also * JARs./*from www. ja v a 2s .co m*/ * * @author Greg Briggs * @param clazz * Any java class that lives in the same place as the resources * you want. * @param path * Should end with "/", but not start with one. * @return Just the name of each member item, not the full paths. */ public static List<String> listResources(String path) { String fileURL = null; try { URL entry = Platform.getBundle("org.lightcouch").getEntry(path); File file = null; if (entry != null) { fileURL = FileLocator.toFileURL(entry).getPath(); // remove leading slash from absolute path when on windows if (OSValidator.isWindows()) fileURL = fileURL.substring(1, fileURL.length()); file = new File(fileURL); } URL dirURL = file.toPath().toUri().toURL(); if (dirURL != null && dirURL.getProtocol().equals("file")) { return Arrays.asList(new File(dirURL.toURI()).list()); } if (dirURL != null && dirURL.getProtocol().equals("jar")) { String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { String entry1 = name.substring(path.length()); int checkSubdir = entry1.indexOf("/"); if (checkSubdir >= 0) { entry1 = entry1.substring(0, checkSubdir); } if (entry1.length() > 0) { result.add(entry1); } } } return new ArrayList<String>(result); } return null; } catch (Exception e) { throw new CouchDbException("fileURL: " + fileURL, e); } }
From source file:au.com.addstar.objects.Plugin.java
public Plugin setLatestVer() { try {// www .java2s . c om if (latestFile == null) return this; try (JarFile jar = new JarFile(latestFile);) { String descriptorFileName = "plugin.yml"; if (type != null) { switch (type) { case BUKKIT: descriptorFileName = "plugin.yml"; break; case BUNGEE: descriptorFileName = "bungee.yml"; break; default: descriptorFileName = "plugin.yml"; } } JarEntry je = jar.getJarEntry(descriptorFileName); if (je == null) je = jar.getJarEntry("plugin.yml"); JarEntry sv = jar.getJarEntry("spigot.ver"); if (sv != null) { try (InputStream svstream = jar.getInputStream(sv); InputStreamReader reader = new InputStreamReader(svstream); BufferedReader bs = new BufferedReader(reader);) { spigotVersion = bs.readLine(); bs.close(); reader.close(); svstream.close(); } } else { if (spigotVersion != null) addSpigotVer(spigotVersion); } try (InputStream stream = jar.getInputStream(je);) { PluginDescriptionFile pdf = new PluginDescriptionFile(stream); pdfVersion = pdf.getVersion(); } catch (NullPointerException e) { System.out.println("Plugin: " + this.getName() + " File: " + jar.getName() + " does not appear to be a valid plugin (" + latestFile.getAbsolutePath() + ")"); pdfVersion = null; } } if (spigotVersion != null && !spigotVersion.equals(pdfVersion)) { version = spigotVersion; } else { version = pdfVersion; } lastUpdated = new Date(latestFile.lastModified()); } catch (ZipException e) { } catch (IOException | InvalidDescriptionException e) { System.out.println(e.getLocalizedMessage()); } return this; }
From source file:com.smash.revolance.ui.model.application.ApplicationFactory.java
private void loadApplication(String appDir, String appId, String impl, String version) throws IOException { if (!appDir.isEmpty() && new File(appDir).isDirectory()) { Collection<File> files = FileUtils.listFiles(new File(appDir), new String[] { "jar" }, false); for (File file : files) { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); Attributes attributes = manifest.getMainAttributes(); String implAttr = attributes.getValue("revolance-ui-explorer-applicationImpl"); String versionAttr = attributes.getValue("revolance-ui-explorer-applicationVersion"); if (implAttr.contentEquals(impl) && (versionAttr.contentEquals(version) || version == null)) { applicationLoaders.put(getKey(appId, impl, version), new JarClassLoader(file.toURI().toURL())); }/*from w w w.j a v a 2 s. co m*/ } } }