List of usage examples for java.util.jar JarInputStream getManifest
public Manifest getManifest()
Manifest
for this JAR file, or null
if none. From source file:com.sketchy.server.UpgradeUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {// w w w. jav a 2 s. com boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); String version = ""; for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { JarInputStream jarInputStream = null; try { // check to make sure it's a Sketchy File with a Manifest File jarInputStream = new JarInputStream(fileItem.getInputStream(), true); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new Exception("Invalid Upgrade File!"); } Attributes titleAttributes = manifest.getMainAttributes(); if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase( titleAttributes.getValue("Implementation-Title"), "Sketchy"))) { throw new Exception("Invalid Upgrade File!"); } version = titleAttributes.getValue("Implementation-Version"); } catch (Exception e) { throw new Exception("Invalid Upgrade File!"); } finally { IOUtils.closeQuietly(jarInputStream); } // save new .jar file as "ready" fileItem.write(new File("Sketchy.jar.ready")); jsonServletResult.put("version", version); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:com.liferay.ide.project.core.modules.ServiceWrapperCommand.java
private void _getServiceWrapperList(Map<String, String[]> wrapperMap, String name, JarInputStream jarInputStream) { if (name.endsWith("ServiceWrapper.class") && !name.contains("$")) { name = name.replaceAll("\\\\", ".").replaceAll("/", "."); name = name.substring(0, name.lastIndexOf(".")); Attributes mainAttributes = jarInputStream.getManifest().getMainAttributes(); String bundleName = mainAttributes.getValue("Bundle-SymbolicName"); String version = mainAttributes.getValue("Bundle-Version"); String group = ""; if (bundleName.equals("com.liferay.portal.kernel")) { group = "com.liferay.portal"; } else {//w w w . j av a 2 s.co m int ordinalIndexOf = StringUtils.ordinalIndexOf(bundleName, ".", 2); if (ordinalIndexOf != -1) { group = bundleName.substring(0, ordinalIndexOf); } } wrapperMap.put(name, new String[] { group, bundleName, version }); } }
From source file:be.iminds.aiolos.ui.DemoServlet.java
private void getRepositoryBundles(PrintWriter writer) { JSONArray components = new JSONArray(); Repository[] repos = new Repository[] {}; repos = repositoryTracker.getServices(repos); for (Repository repo : repos) { try {// w ww.j a va 2 s . com CapabilityRequirementImpl requirement = new CapabilityRequirementImpl("osgi.identity", null); requirement.addDirective("filter", String.format("(%s=%s)", "osgi.identity", "*")); Map<Requirement, Collection<Capability>> result = repo .findProviders(Collections.singleton(requirement)); for (Capability c : result.values().iterator().next()) { String type = (String) c.getAttributes().get("type"); if (type != null && type.equals("osgi.bundle")) { String componentId = (String) c.getAttributes().get("osgi.identity"); String version = c.getAttributes().get("version").toString(); String name = null; String description = null; try { RepositoryContent content = (RepositoryContent) c.getResource(); JarInputStream jar = new JarInputStream(content.getContent()); Manifest mf = jar.getManifest(); Attributes attr = mf.getMainAttributes(); name = attr.getValue("Bundle-Name"); description = attr.getValue("Bundle-Description"); } catch (Exception e) { e.printStackTrace(); } JSONObject component = new JSONObject(); component.put("componentId", componentId); component.put("version", version); component.put("name", name); component.put("description", description); components.add(component); } } } catch (Exception e) { } } writer.write(components.toJSONString()); }
From source file:com.kotcrab.vis.editor.module.editor.PluginLoaderModule.java
private void loadPluginsDescriptors(Array<FileHandle> pluginsFolders) throws IOException { for (FileHandle folder : pluginsFolders) { FileHandle[] files = folder.list((dir, name) -> name.endsWith("jar")); if (files.length > 1 || files.length == 0) { Log.error(TAG, "Failed (invalid directory structure): " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, new IllegalStateException( "Plugin directory must contain only one jar (required libs must be stored in 'lib' subdirectory"))); continue; }/*from ww w .j a v a 2 s . c om*/ FileHandle pluginJar = files[0]; try { JarInputStream jarStream = new JarInputStream(new FileInputStream(pluginJar.file())); Manifest mf = jarStream.getManifest(); jarStream.close(); PluginDescriptor desc = new PluginDescriptor(pluginJar, mf); allPlugins.add(desc); } catch (IOException e) { Log.error(TAG, "Failed (IO exception): " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, e)); Log.exception(e); } catch (EditorException e) { Log.error(TAG, "Failed: " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, e)); Log.exception(e); } } }
From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java
private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException { InstallationResult result = null;//from w w w. j av a 2 s . co m try { DiskFileItemFactory factory = new DiskFileItemFactory(); // try to hold even largish bundles in memory to potentially improve performance factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); if (items.size() != 1) { logAndWriteError( "Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp); return; } FileItem item = items.get(0); JarInputStream jar = null; InputStream rawInput = null; try { jar = new JarInputStream(item.getInputStream()); Manifest manifest = jar.getManifest(); if (manifest == null) { logAndWriteError("Uploaded jar file does not contain a manifest", resp); return; } final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName == null) { logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp); return; } final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION); // the JarInputStream is used only for validation, we need a fresh input stream for updating rawInput = item.getInputStream(); Bundle found = getBundle(symbolicName); try { installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar"); result = new InstallationResult(true, null); resp.setStatus(200); result.render(resp.getWriter()); return; } catch (BundleException e) { logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp); return; } } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(rawInput); } } catch (FileUploadException e) { logAndWriteError("Failed parsing uploaded bundle", e, resp); return; } }
From source file:com.amalto.core.jobox.watch.JoboxListener.java
public void contextChanged(String jobFile, String context) { File entity = new File(jobFile); String sourcePath = jobFile;/*from w w w . j av a 2s. c om*/ int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$ int separateMark = jobFile.lastIndexOf(File.separatorChar); if (dotMark != -1) { sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$ + jobFile.substring(separateMark, dotMark); } try { JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$ } catch (Exception e1) { LOGGER.error("Extraction exception occurred.", e1); return; } List<File> resultList = new ArrayList<File>(); JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$ if (!resultList.isEmpty()) { JarInputStream jarIn = null; JarOutputStream jarOut = null; try { JarFile jarFile = new JarFile(resultList.get(0)); Manifest mf = jarFile.getManifest(); jarIn = new JarInputStream(new FileInputStream(resultList.get(0))); Manifest newManifest = jarIn.getManifest(); if (newManifest == null) { newManifest = new Manifest(); } newManifest.getMainAttributes().putAll(mf.getMainAttributes()); newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$ jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$ continue; } jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } } catch (Exception e) { LOGGER.error("Extraction exception occurred.", e); } finally { IOUtils.closeQuietly(jarIn); IOUtils.closeQuietly(jarOut); } // re-zip file if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$ File sourceFile = new File(sourcePath); try { JoboxUtil.zip(sourceFile, jobFile); } catch (Exception e) { LOGGER.error("Zip exception occurred.", e); } } } }
From source file:com.geewhiz.pacify.TestArchive.java
@Test public void checkJar() throws ArchiveException, IOException { String testFolder = "testArchive/correct/jar"; File targetResourceFolder = new File("target/test-resources/", testFolder); LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder, createPropertyResolveManager(propertiesToUseWhileResolving)); Assert.assertEquals("We shouldnt get any defects.", 0, defects.size()); File expectedArchive = new File(targetResourceFolder, "expectedResult/archive.jar"); File resultArchive = new File(targetResourceFolder, "package/archive.jar"); JarInputStream expected = new JarInputStream(new FileInputStream(expectedArchive)); JarInputStream result = new JarInputStream(new FileInputStream(resultArchive)); Assert.assertNotNull("SRC jar should contain the manifest as first entry", expected.getManifest()); Assert.assertNotNull("RESULT jar should contain the manifest as first entry", result.getManifest()); expected.close();/* ww w.j av a 2s. com*/ result.close(); checkIfResultIsAsExpected(testFolder); }
From source file:org.apache.sling.osgi.obr.Repository.java
File spoolModified(InputStream ins) throws IOException { JarInputStream jis = new JarInputStream(ins); // immediately handle the manifest JarOutputStream jos;//ww w. j a v a2s . co m Manifest manifest = jis.getManifest(); if (manifest == null) { throw new IOException("Missing Manifest !"); } String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName == null || symbolicName.length() == 0) { throw new IOException("Missing Symbolic Name in Manifest !"); } String version = manifest.getMainAttributes().getValue("Bundle-Version"); Version v = Version.parseVersion(version); if (v.getQualifier().indexOf("SNAPSHOT") >= 0) { String tStamp; synchronized (DATE_FORMAT) { tStamp = DATE_FORMAT.format(new Date()); } version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "." + v.getQualifier().replaceAll("SNAPSHOT", tStamp); manifest.getMainAttributes().putValue("Bundle-Version", version); } File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar"); OutputStream out = null; try { out = new FileOutputStream(bundle); jos = new JarOutputStream(out, manifest); jos.setMethod(JarOutputStream.DEFLATED); jos.setLevel(Deflater.BEST_COMPRESSION); JarEntry entryIn = jis.getNextJarEntry(); while (entryIn != null) { JarEntry entryOut = new JarEntry(entryIn.getName()); entryOut.setTime(entryIn.getTime()); entryOut.setComment(entryIn.getComment()); jos.putNextEntry(entryOut); if (!entryIn.isDirectory()) { spool(jis, jos); } jos.closeEntry(); jis.closeEntry(); entryIn = jis.getNextJarEntry(); } // close the JAR file now to force writing jos.close(); } finally { IOUtils.closeQuietly(out); } return bundle; }
From source file:com.geewhiz.pacify.TestArchive.java
@Test public void checkJarWhereTheSourceIsntAJarPerDefinition() throws ArchiveException, IOException { LoggingUtils.setLogLevel(logger, Level.ERROR); String testFolder = "testArchive/correct/jarWhereSourceIsntAJarPerDefinition"; File testResourceFolder = new File("src/test/resources/", testFolder); File targetResourceFolder = new File("target/test-resources/", testFolder); LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder, createPropertyResolveManager(propertiesToUseWhileResolving)); Assert.assertEquals("We shouldnt get any defects.", 0, defects.size()); JarInputStream in = new JarInputStream( new FileInputStream(new File(testResourceFolder, "package/archive.jar"))); JarInputStream out = new JarInputStream( new FileInputStream(new File(targetResourceFolder, "package/archive.jar"))); Assert.assertNull("SRC jar should be a jar which is packed via zip, so the first entry isn't the manifest.", in.getManifest()); Assert.assertNotNull("RESULT jar should contain the manifest as first entry", out.getManifest()); in.close();//from w w w. jav a 2s. c o m out.close(); checkIfResultIsAsExpected(testFolder); }
From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java
/** * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the * entry represents another a JAR file. The files in the {@link JarEntry} will be * extracted using the contextDir as the base directory. * /* w ww . j a va 2 s .c o m*/ * @param earFile The JarEntry for the JAR to read from the archive. * @param earEntry The JarFile to get the {@link InputStream} for the file from. * @param contextDir The directory to extract the JAR to. * @throws IOException If the extracting of data from the JarEntry fails. */ protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir) throws MojoFailureException { if (this.getLogger().isInfoEnabled()) { this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '" + contextDir + "'"); } if (!contextDir.exists()) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Creating context directory entry '" + contextDir + "'"); } try { FileUtils.forceMkdir(contextDir); } catch (IOException e) { throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '" + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e); } } JarInputStream warInputStream = null; try { warInputStream = new JarInputStream(earFile.getInputStream(earEntry)); // Write out the MANIFEST.MF file to the target directory Manifest manifest = warInputStream.getManifest(); if (manifest != null) { FileOutputStream manifestFileOutputStream = null; try { final File manifestFile = new File(contextDir, MANIFEST_PATH); manifestFile.getParentFile().mkdirs(); manifestFileOutputStream = new FileOutputStream(manifestFile); manifest.write(manifestFileOutputStream); } catch (Exception e) { this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "'", e); throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "'", e); } finally { try { if (manifestFileOutputStream != null) { manifestFileOutputStream.close(); } } catch (Exception e) { this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry: " + earEntry.getName()); } } } JarEntry warEntry; while ((warEntry = warInputStream.getNextJarEntry()) != null) { final File warEntryFile = new File(contextDir, warEntry.getName()); if (warEntry.isDirectory()) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!" + warEntry.getName() + "' as '" + warEntryFile + "'"); } FileUtils.forceMkdir(warEntryFile); } else { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!" + warEntry.getName() + "' to '" + warEntryFile + "'"); } FileUtils.forceMkdir(warEntryFile.getParentFile()); final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile); try { IOUtils.copy(warInputStream, jarEntryFileOutputStream); } finally { IOUtils.closeQuietly(jarEntryFileOutputStream); } } } } catch (IOException e) { throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "' to '" + contextDir + "'", e); } finally { IOUtils.closeQuietly(warInputStream); } }