List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:net.cliseau.composer.javatarget.PointcutParseException.java
/** * Update the manifest of a given JAR file to include CliSeAu's dependencies in the classpath list. * * This method modifies the "Class-Path" entry of the given JAR file's * manifest to include the paths of all runtime dependencies that are caused * by the instrumentation with the CliSeAu unit. * * @param targetJARFile The JAR file whose manifest to update. * @exception IOException Thrown when reading or writing the JAR file fails. * @todo Check whether this update is possible also with the JarFile API alone. *///from www. j a v a2s . c o m private void updateTargetManifest(final File targetJARFile) throws IOException, InvalidConfigurationException { // Step 1: Obtain the existing class path list from the target JAR file JarFile targetJAR = new JarFile(targetJARFile); Manifest targetManifest = targetJAR.getManifest(); LinkedList<String> classPathEntries; if (targetManifest != null) { String targetClassPath = targetManifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (targetClassPath == null) { targetClassPath = ""; } classPathEntries = new LinkedList<String>( Arrays.asList(targetClassPath.split(manifestClassPathSeparator))); } else { classPathEntries = new LinkedList<String>(); } // close the object again (this shall ensure that the command in // Step 4 can safely work on the file again) targetJAR.close(); // Step 2: Add all newly introduced runtime dependencies of CliSeAu classPathEntries.addAll(getInlinedDependencies()); // Step 3: Create a new manifest file with *only* the updated class path directive File manifestUpdate = File.createTempFile("MANIFEST", ".MF"); PrintWriter muWriter = new PrintWriter(manifestUpdate); muWriter.print("Class-path:"); muWriter.print(StringUtils.join(classPathEntries, manifestClassPathSeparator)); muWriter.println(); muWriter.close(); // Step 4: Run "jar" to update the JAR file with the new manifest; this // does not replace the JAR file's manifest with the new one, but // *update* *only* those entries in the JAR file's manifest which are // present in the new manifest. That is, only the class path settings are // updated and everything else remains intact. CommandRunner.exec(new String[] { aspectjConfig.getJarExecutable(), "umf", // update manifest manifestUpdate.getPath(), targetJARFile.getPath() }); // Step 5: cleanup manifestUpdate.delete(); }
From source file:UnpackedJarFile.java
public static JarFile createJarFile(File jarFile) throws IOException { if (jarFile.isDirectory()) { return new UnpackedJarFile(jarFile); } else {/*from w w w.jav a 2s .c o m*/ return new JarFile(jarFile); } }
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.// w w w. j av a 2 s. 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:org.apache.pig.test.TestJobControlCompiler.java
/** * checks if the given file name is in the jar * @param jarFile the jar to check/*from w ww . ja v a2s . c o m*/ * @param name the name to find (full path in the jar) * @return true if the name was found * @throws IOException */ private boolean jarContainsFileNamed(File jarFile, String name) throws IOException { Enumeration<JarEntry> entries = new JarFile(jarFile).entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().equals(name)) { return true; } } return false; }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static HeliosData loadHelios() throws IOException { System.out.println("Finding Helios implementation"); HeliosData data = new HeliosData(); boolean needsToDownload = !IMPL_FILE.exists(); if (!needsToDownload) { try (JarFile jarFile = new JarFile(IMPL_FILE)) { ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF"); if (entry == null) { needsToDownload = true;// w w w. ja v a2 s . com } else { Manifest manifest = new Manifest(jarFile.getInputStream(entry)); String ver = manifest.getMainAttributes().getValue("Implementation-Version"); try { data.buildNumber = Integer.parseInt(ver); data.version = manifest.getMainAttributes().getValue("Version"); data.mainClass = manifest.getMainAttributes().getValue("Main-Class"); } catch (NumberFormatException e) { needsToDownload = true; } } } catch (IOException e) { needsToDownload = true; } } if (needsToDownload) { URL latestJar = new URL(LATEST_JAR); System.out.println("Downloading latest Helios implementation"); FileOutputStream out = new FileOutputStream(IMPL_FILE); HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection(); if (connection.getResponseCode() == 200) { int contentLength = connection.getContentLength(); if (contentLength > 0) { InputStream stream = connection.getInputStream(); byte[] buffer = new byte[1024]; int amnt; AtomicInteger total = new AtomicInteger(); AtomicBoolean stop = new AtomicBoolean(false); Thread progressBar = new Thread() { public void run() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JLabel label = new JLabel(); label.setText("Downloading latest Helios build"); panel.add(label); GridLayout layout = new GridLayout(); layout.setColumns(1); layout.setRows(3); panel.setLayout(layout); JProgressBar pbar = new JProgressBar(); pbar.setMinimum(0); pbar.setMaximum(100); panel.add(pbar); JTextArea textArea = new JTextArea(1, 3); textArea.setOpaque(false); textArea.setEditable(false); textArea.setText("Downloaded 00.00MB/00.00MB"); panel.add(textArea); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); while (!stop.get()) { SwingUtilities.invokeLater( () -> pbar.setValue((int) (100.0 * total.get() / contentLength))); textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/" + bytesToMeg(contentLength) + "MB"); try { Thread.sleep(100); } catch (InterruptedException ignored) { } } frame.dispose(); } }; progressBar.start(); while ((amnt = stream.read(buffer)) != -1) { out.write(buffer, 0, amnt); total.addAndGet(amnt); } stop.set(true); return loadHelios(); } else { throw new IOException("Content-Length set to " + connection.getContentLength()); } } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date throw new RuntimeException("Bootstrapper out of date!"); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } } return data; }
From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java
private ModuleInstallationResult installModule(File file, MessageContext context, List<String> providedBundles, Map<Bundle, MessageResolver> collectedResolutionErrors, boolean forceUpdate, boolean autoStart) throws IOException, BundleException { JarFile jarFile = new JarFile(file); try {// ww w. j a v a 2s . c om Manifest manifest = jarFile.getManifest(); String symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME); if (symbolicName == null) { symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_ROOT_FOLDER); } String version = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_IMPL_VERSION); String groupId = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_GROUP_ID); if (templateManagerService.differentModuleWithSameIdExists(symbolicName, groupId)) { context.addMessage(new MessageBuilder().source("moduleFile") .code("serverSettings.manageModules.install.moduleWithSameIdExists").arg(symbolicName) .error().build()); return null; } ModuleVersion moduleVersion = new ModuleVersion(version); Set<ModuleVersion> allVersions = templatePackageRegistry.getAvailableVersionsForModule(symbolicName); if (!forceUpdate) { if (!moduleVersion.isSnapshot()) { if (allVersions.contains(moduleVersion)) { context.addMessage(new MessageBuilder().source("moduleExists") .code("serverSettings.manageModules.install.moduleExists") .args(symbolicName, version).build()); return null; } } } String successMessage = (autoStart ? "serverSettings.manageModules.install.uploadedAndStarted" : "serverSettings.manageModules.install.uploaded"); String resolutionError = null; boolean shouldAutoStart = autoStart; if (autoStart && !Boolean.valueOf(SettingsBean.getInstance().getPropertiesFile() .getProperty("org.jahia.modules.autoStartOlderVersions"))) { // verify that a newer version is not active already JahiaTemplatesPackage currentActivePackage = templateManagerService.getTemplatePackageRegistry() .lookupById(symbolicName); ModuleVersion currentVersion = currentActivePackage != null ? currentActivePackage.getVersion() : null; if (currentActivePackage != null && moduleVersion.compareTo(currentVersion) < 0) { // we do not start the uploaded older version automatically shouldAutoStart = false; successMessage = "serverSettings.manageModules.install.uploadedNotStartedDueToNewerVersionActive"; } } try { moduleManager.install(new FileSystemResource(file), null, shouldAutoStart); } catch (ModuleManagementException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof BundleException && ((BundleException) cause).getType() == BundleException.RESOLVE_ERROR) { // we are dealing with unresolved dependencies here resolutionError = cause.getMessage(); } else { // re-throw the exception throw e; } } Bundle bundle = BundleUtils.getBundle(symbolicName, version); JahiaTemplatesPackage module = BundleUtils.getModule(bundle); if (module.getState().getState() == ModuleState.State.WAITING_TO_BE_IMPORTED) { // This only can happen in a cluster. successMessage = "serverSettings.manageModules.install.waitingToBeImported"; } if (resolutionError != null) { List<String> missingDeps = getMissingDependenciesFrom(module.getDepends(), providedBundles); if (!missingDeps.isEmpty()) { createMessageForMissingDependencies(context, missingDeps); } else { MessageResolver errorMessage = new MessageBuilder().source("moduleFile") .code("serverSettings.manageModules.resolutionError").arg(resolutionError).error() .build(); if (collectedResolutionErrors != null) { // we just collect the resolution errors for multiple module to double-check them after all modules are installed collectedResolutionErrors.put(bundle, errorMessage); return new ModuleInstallationResult(bundle, successMessage); } else { // we directly add error message context.addMessage(errorMessage); } } } else if (module.getState().getState() == ModuleState.State.ERROR_WITH_DEFINITIONS) { context.addMessage(new MessageBuilder().source("moduleFile") .code("serverSettings.manageModules.errorWithDefinitions") .arg(((Exception) module.getState().getDetails()).getCause().getMessage()).error().build()); } else { return new ModuleInstallationResult(bundle, successMessage); } } finally { IOUtils.closeQuietly(jarFile); } return null; }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Ignore("See https://github.com/ceylon/ceylon/issues/6027") @Test//www .j av a2 s. c om public void testMdlCarWithInvalidSHA1() throws IOException { compile("modules/single/module.ceylon"); File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6"); assertTrue(carFile.exists()); JarFile car = new JarFile(carFile); // just to be sure ZipEntry moduleClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class"); assertNotNull(moduleClass); car.close(); // now let's break the SHA1 File shaFile = getArchiveName("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6", destDir, "car.sha1"); Writer w = new FileWriter(shaFile); w.write("fubar"); w.flush(); w.close(); // now try to compile the subpackage with a broken SHA1 String carName = "/com/redhat/ceylon/compiler/java/test/cmr/modules/single/6.6.6/com.redhat.ceylon.compiler.java.test.cmr.modules.single-6.6.6.car"; carName = carName.replace('/', File.separatorChar); assertErrors("modules/single/subpackage/Subpackage", new CompilerError(-1, "Module car " + carName + " obtained from repository " + (new File(destDir).getAbsolutePath()) + " has an invalid SHA1 signature: you need to remove it and rebuild the archive, since it may be corrupted.")); }
From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java
protected JarFile createJarFile(File jarFile) { try {/*from w ww . j av a 2 s . c om*/ File jarFileWithoutSubPath = getJarFileWithoutSubPath(jarFile); return new JarFile(jarFileWithoutSubPath); } catch (IOException e) { throw new MigrateBirdException("Error opening jar file " + jarFile, e); } }
From source file:com.bbxiaoqu.api.util.Utils.java
/** * ???MD5//ww w.j av a 2s. c o m */ public static String getFileSignatureMd5(String targetFile) { try { JarFile jarFile = new JarFile(targetFile); // ?RSA JarEntry jarEntry = jarFile.getJarEntry("AndroidManifest.xml"); if (jarEntry != null) { InputStream is = jarFile.getInputStream(jarEntry); byte[] buffer = new byte[8192]; while (is.read(buffer) > 0) { // do nothing } is.close(); Certificate[] certs = jarEntry == null ? null : jarEntry.getCertificates(); if (certs != null && certs.length > 0) { String rsaPublicKey = String.valueOf(certs[0].getPublicKey()); return getMD5(rsaPublicKey); } } } catch (IOException e) { W("occur IOException when get file signature", e); } return ""; }
From source file:com.vectorcast.plugins.vectorcastexecution.VectorCASTSetup.java
/** * Perform the build step. Copy the scripts from the archive/directory to the workspace * @param build build//from w ww. j a v a 2 s . c o m * @param workspace workspace * @param launcher launcher * @param listener listener */ @Override public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) { FilePath destScriptDir = new FilePath(workspace, "vc_scripts"); JarFile jFile = null; try { String path = null; String override_path = System.getenv("VCAST_VC_SCRIPTS"); String extra_script_path = SCRIPT_DIR; Boolean directDir = false; if (override_path != null && !override_path.isEmpty()) { path = override_path; extra_script_path = ""; directDir = true; String msg = "VectorCAST - overriding vc_scripts. Copying from '" + path + "'"; Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.ALL, msg); } else { path = VectorCASTSetup.class.getProtectionDomain().getCodeSource().getLocation().getPath(); path = URLDecoder.decode(path, "utf-8"); } File testPath = new File(path); if (testPath.isFile()) { // Have jar file... jFile = new JarFile(testPath); Enumeration<JarEntry> entries = jFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith("scripts")) { String fileOrDir = entry.getName().substring(8); // length of scripts/ FilePath dest = new FilePath(destScriptDir, fileOrDir); if (entry.getName().endsWith("/")) { // Directory, create destination dest.mkdirs(); } else { // File, copy it InputStream is = VectorCASTSetup.class.getResourceAsStream("/" + entry.getName()); dest.copyFrom(is); } } } } else { // Have directory File scriptDir = new File(path + extra_script_path); processDir(scriptDir, "./", destScriptDir, directDir); } } catch (IOException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } finally { if (jFile != null) { try { jFile.close(); } catch (IOException ex) { // Ignore } } } }