Example usage for java.util.jar Manifest getMainAttributes

List of usage examples for java.util.jar Manifest getMainAttributes

Introduction

In this page you can find the example usage for java.util.jar Manifest getMainAttributes.

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

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  ww  . j a  v  a  2 s  .c  o  m*/
    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.taobao.android.apatch.MergePatch.java

@SuppressWarnings("deprecation")
@Override// www  . ja  va 2s .c o  m
protected Manifest getMeta() {
    Manifest retManifest = new Manifest();
    Attributes main = retManifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("Patch-Name", name);

    try {
        fillManifest(main);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return retManifest;
}

From source file:org.overlord.commons.osgi.vfs.VfsBundle.java

/**
 * Throws a "not found" error while also logging information found in the manifest.  This
 * latter part will help diagnose which JAR was *supposed* to have been detected.
 * @param url/*from ww  w.  ja  va 2 s .  c om*/
 */
private void throwNotFoundError(URL url) {
    InputStream manifestStream = null;
    StringBuilder builder = new StringBuilder();
    try {
        String manifestPath = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
        URL manifestURL = new URL(url.toExternalForm() + manifestPath);
        manifestStream = manifestURL.openStream();
        Manifest manifest = new Manifest(manifestStream);
        Attributes attributes = manifest.getMainAttributes();
        for (Entry<Object, Object> entry : attributes.entrySet()) {
            String key = String.valueOf(entry.getKey());
            String value = String.valueOf(entry.getValue());
            builder.append(key).append(": ").append(value).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    } catch (Exception e) {
    } finally {
        IOUtils.closeQuietly(manifestStream);
    }
    // Include the full manifest in the exception - this is helpful to diagnose which
    // JAR gave us fits.  Hopefully this will not happen!
    throw new RuntimeException("Failed to create a Vfs.Dir for URL: " + url //$NON-NLS-1$
            + "\n--Manifest--\n====================" + builder.toString()); //$NON-NLS-1$
}

From source file:net.sf.freecol.FreeCol.java

/**
 * Extract the package version from the class.
 *
 * @param juc The <code>JarURLConnection</code> to extract from.
 * @return A value of the package version attribute.
 *//*from   w ww . ja v a  2  s. c  o m*/
private static String readVersion(JarURLConnection juc) throws IOException {
    Manifest mf = juc.getManifest();
    return (mf == null) ? null : mf.getMainAttributes().getValue("Package-Version");
}

From source file:com.datatorrent.stram.client.ConfigPackage.java

/**
 * Creates an Config Package object./*from w  w w .  j ava 2  s  .co m*/
 *
 * @param file
 * @throws java.io.IOException
 * @throws net.lingala.zip4j.exception.ZipException
 */
public ConfigPackage(File file) throws IOException, ZipException {
    super(file);
    Manifest manifest = getManifest();
    if (manifest == null) {
        throw new IOException("Not a valid config package. MANIFEST.MF is not present.");
    }
    Attributes attr = manifest.getMainAttributes();
    configPackageName = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_NAME);
    appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
    appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
    appPackageMinVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MIN_VERSION);
    appPackageMaxVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MAX_VERSION);
    configPackageDescription = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_DESCRIPTION);
    String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
    String filesString = attr.getValue(ATTRIBUTE_FILES);
    if (configPackageName == null) {
        throw new IOException("Not a valid config package.  DT-Conf-Package-Name is missing from MANIFEST.MF");
    }
    if (!StringUtils.isBlank(classPathString)) {
        classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
    }
    if (!StringUtils.isBlank(filesString)) {
        files.addAll(Arrays.asList(StringUtils.split(filesString, " ")));
    }

    ZipFile zipFile = new ZipFile(file);
    if (zipFile.isEncrypted()) {
        throw new ZipException("Encrypted conf package not supported yet");
    }
    File newDirectory = Files.createTempDirectory("dt-configPackage-").toFile();
    newDirectory.mkdirs();
    directory = newDirectory.getAbsolutePath();
    zipFile.extractAll(directory);
    processPropertiesXml();
}

From source file:com.hellblazer.process.JavaProcessTest.java

protected void copyTestJarFile() throws Exception {
    String classFileName = HelloWorld.class.getCanonicalName().replace('.', '/') + ".class";
    URL classFile = getClass().getResource("/" + classFileName);
    assertNotNull(classFile);//  w  w  w .  ja va 2 s  .  c o m

    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Main-Class", HelloWorld.class.getCanonicalName());

    FileOutputStream fos = new FileOutputStream(new File(testDir, TEST_JAR));
    JarOutputStream jar = new JarOutputStream(fos, manifest);
    JarEntry entry = new JarEntry(classFileName);
    jar.putNextEntry(entry);
    InputStream in = classFile.openStream();
    byte[] buffer = new byte[1024];
    for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
        jar.write(buffer, 0, read);
    }
    in.close();
    jar.closeEntry();
    jar.close();
}

From source file:org.jvnet.hudson.update_center.LocalDirectoryRepository.java

/**
 * Return all plugins contained in the directory.
 * /*w w  w .ja  v a  2 s .  c o  m*/
 * @return a collection of histories of plugins contained in the directory.
 * @see org.jvnet.hudson.update_center.MavenRepository#listHudsonPlugins()
 */
@Override
public Collection<PluginHistory> listHudsonPlugins() throws PlexusContainerException, ComponentLookupException,
        IOException, UnsupportedExistingLuceneIndexException, AbstractArtifactResolutionException {
    // Search all plugins contained in the directory.
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(dir);
    ds.setIncludes(new String[] { "**/*.hpi", "**/*.jpi" });
    ds.scan();

    // build plugin history.
    Map<String, PluginHistory> plugins = new TreeMap<String, PluginHistory>(String.CASE_INSENSITIVE_ORDER);

    for (String filename : ds.getIncludedFiles()) {
        File hpiFile = new File(dir, filename);
        JarFile jar = new JarFile(hpiFile);
        Manifest manifest = jar.getManifest();
        long lastModified = jar.getEntry("META-INF/MANIFEST.MF").getTime();
        jar.close();

        String groupId = manifest.getMainAttributes().getValue("Group-Id");
        if (groupId == null) {
            // Old plugins inheriting from org.jvnet.hudson.plugins do not have
            // Group-Id field set in manifest. Absence of group id causes NPE in ArtifactInfo.
            groupId = "org.jvnet.hudson.plugins";
        }

        final String extension = FilenameUtils.getExtension(filename);

        // Extension-Name and Implementation-Title is not set for plugin using gradle (ex: ivy:1.26)
        // Short-Name seems always present and have the same value as the other two.
        String artifactId = manifest.getMainAttributes().getValue("Short-Name");
        ArtifactInfo a = new ArtifactInfo(null, // fname
                extension, groupId, artifactId, manifest.getMainAttributes().getValue("Plugin-Version"), // version
                // maybe Implementation-Version is more proper.
                null, // classifier
                "hpi", // packaging
                manifest.getMainAttributes().getValue("Long-Name"), // name
                manifest.getMainAttributes().getValue("Specification-Title"), // description
                lastModified, // lastModified
                hpiFile.length(), // size
                null, // md5
                null, // sha1
                ArtifactAvailablility.NOT_PRESENT, // sourcesExists
                ArtifactAvailablility.NOT_PRESENT, //javadocExists,
                ArtifactAvailablility.NOT_PRESENT, //signatureExists,
                null // repository
        );

        if (!includeSnapshots && a.version.contains("SNAPSHOT"))
            continue; // ignore snapshots
        PluginHistory p = plugins.get(a.artifactId);
        if (p == null)
            plugins.put(a.artifactId, p = new PluginHistory(a.artifactId));

        URL url;
        if (downloadDir == null) {
            // No downloadDir specified.
            // Just link to packages where they are located.
            String path = filename;
            if (File.separatorChar != '/') {
                // fix path separate character to /
                path = filename.replace(File.separatorChar, '/');
            }
            url = new URL(baseUrl, path);
        } else {
            // downloadDir is specified.
            // Packages are deployed into downloadDir, based on its plugin name and version.
            final String path = new LocalHPI(this, p, a, hpiFile, null).getRelativePath();
            url = new URL(new URL(baseUrl, "download/"), path);
        }
        p.addArtifact(new LocalHPI(this, p, a, hpiFile, url));
        p.groupId.add(a.groupId);
    }

    return plugins.values();
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);// w ww. j  av a 2s  .  c  om
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), Paths.get("output.jar"),
            ImmutableSet.of(Paths.get("input.jar")), /* main class */ null, Paths.get("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context));

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

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 {//www . ja v a  2  s.c o m

        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:org.pentaho.osgi.platform.webjars.WebjarsURLConnectionTest.java

private void verifyManifest(ZipFile zipInputStream) throws IOException {
    ZipEntry entry = zipInputStream.getEntry("META-INF/MANIFEST.MF");
    assertNotNull(entry);/*from   w w w.j  a  va 2 s.co  m*/
    Manifest manifest = new Manifest(zipInputStream.getInputStream(entry));
    assertTrue("Bundle-SymbolicName is not pentaho-webjars-",
            manifest.getMainAttributes().getValue("Bundle-SymbolicName").startsWith("pentaho-webjars-"));
}