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.sketchy.server.action.GetCurrentVersion.java

@Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    String version = "";
    try {//w ww  .  j  a v  a2s.c  o  m
        File sketchyFile = new File("Sketchy.jar");
        if (!sketchyFile.exists()) {
            throw new Exception("Can't find Sketchy.jar file!");
        }
        JarInputStream jarInputStream = null;
        try {
            // check to make sure it's a Sketchy File with a Manifest File
            jarInputStream = new JarInputStream(new FileInputStream(sketchyFile), true);
            Manifest manifest = jarInputStream.getManifest();
            if (manifest == null) {
                throw new Exception("Manifest file not found.");
            }
            Attributes titleAttributes = manifest.getMainAttributes();
            version = titleAttributes.getValue("Implementation-Version");
        } catch (Exception e) {
            throw new Exception("Invalid Upgrade File!");
        } finally {
            IOUtils.closeQuietly(jarInputStream);
        }

        jsonServletResult.put("currentVersion", version);
    } catch (Throwable t) {
        jsonServletResult = new JSONServletResult(Status.ERROR,
                "Error getting Current Version! " + t.getMessage());
    }
    return jsonServletResult;
}

From source file:org.xwiki.extension.test.ExtensionPackager.java

public void generateExtension(String classPackageFolder, URL descriptorUrl) throws IOException {
    String descriptorUrlStr = descriptorUrl.toString();
    String descriptorFolderURL = descriptorUrlStr.substring(0,
            descriptorUrlStr.length() - PACKAGEFILE_DESCRIPTOR.length());

    Properties descriptorProperties = new Properties();

    InputStream descriptorStream = descriptorUrl.openStream();
    try {//from  www  .  j a  v a2s  .  c o m
        descriptorProperties.load(descriptorStream);
    } finally {
        descriptorStream.close();
    }
    String type = descriptorProperties.getProperty("type");
    if (type == null) {
        type = "zip";
    }
    String id = descriptorProperties.getProperty("id");
    if (id == null) {
        id = descriptorFolderURL.substring(0, descriptorFolderURL.length() - 1);
        id = id.substring(id.lastIndexOf('/') + 1);
    }
    String version = descriptorProperties.getProperty("version");
    if (version == null) {
        version = "1.0";
    }
    File packageFile;
    String directory = descriptorProperties.getProperty("directory");
    String fileName = descriptorProperties.getProperty("fileName");
    String repositoryName = descriptorProperties.getProperty("repository");
    if (directory == null) {
        if (fileName == null) {
            packageFile = new File(this.repositories.get(repositoryName),
                    URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8"));
        } else {
            packageFile = new File(this.repositories.get(repositoryName), fileName);
        }
    } else {
        if (fileName == null) {
            fileName = URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8");
        }

        packageFile = new File(this.workingDirectory, directory);
        packageFile = new File(packageFile, fileName);
    }

    // generate

    // Make sure the folder exists
    packageFile.getParentFile().mkdirs();

    FileOutputStream fos = new FileOutputStream(packageFile);
    try {
        ZipOutputStream zos;
        if (type.equals("jar")) {
            Manifest manifest = new Manifest();
            manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            zos = new JarOutputStream(fos, manifest);
        } else {
            zos = new ZipOutputStream(fos);
        }

        try {
            // Order files
            TreeMap<String, Vfs.File> files = new TreeMap<>();
            for (Vfs.File resourceFile : Vfs.fromURL(new URL(descriptorFolderURL)).getFiles()) {
                files.put(resourceFile.getRelativePath(), resourceFile);
            }

            // Add files to zip
            for (Vfs.File resourceFile : files.values()) {
                if (!resourceFile.getRelativePath().equals(PACKAGEFILE_DESCRIPTOR)) {
                    addZipEntry(classPackageFolder, resourceFile, zos, type);
                }
            }
        } finally {
            zos.close();
        }

        // Register the extension
        this.extensionsFiles.put(new ExtensionId(id, version), packageFile);
    } finally {
        fos.close();
    }
}

From source file:uk.codingbadgers.bootstrap.tasks.TaskInstallerUpdateCheck.java

@Override
public void run(Bootstrap bootstrap) {
    try {//from   w  ww .  j  ava  2 s  .  c  o m
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(INSTALLER_UPDATE_URL);
        request.setHeader(new BasicHeader("Accept", GITHUB_MIME_TYPE));

        HttpResponse response = client.execute(request);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();

            String localVersion = null;

            if (bootstrap.getInstallerFile().exists()) {
                JarFile jar = new JarFile(bootstrap.getInstallerFile());
                Manifest manifest = jar.getManifest();
                localVersion = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
                jar.close();
            }

            JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray();
            JsonObject release = json.get(0).getAsJsonObject();

            JsonObject installerAsset = null;
            JsonObject librariesAsset = null;
            int i = 0;

            for (JsonElement element : release.get("assets").getAsJsonArray()) {
                JsonObject object = element.getAsJsonObject();
                if (INSTALLER_LABEL.equals(object.get("name").getAsString())) {
                    installerAsset = object;
                } else if (INSTALLER_LIBS_LABEL.equals(object.get("name").getAsString())) {
                    librariesAsset = object;
                }
            }

            if (VersionComparator.getInstance().compare(localVersion, release.get("name").getAsString()) < 0) {
                bootstrap.addDownload(DownloadType.INSTALLER, new EtagDownload(
                        installerAsset.get("url").getAsString(), bootstrap.getInstallerFile()));
                localVersion = release.get("name").getAsString();
            }

            File libs = new File(bootstrap.getInstallerFile() + ".libs");
            boolean update = true;

            if (libs.exists()) {
                FileReader reader = null;

                try {
                    reader = new FileReader(libs);
                    JsonElement parsed = PARSER.parse(reader);

                    if (parsed.isJsonObject()) {
                        JsonObject libsJson = parsed.getAsJsonObject();

                        if (libsJson.has("installer")) {
                            JsonObject installerJson = libsJson.get("installer").getAsJsonObject();
                            if (installerJson.get("version").getAsString().equals(localVersion)) {
                                update = false;
                            }
                        }
                    }
                } catch (JsonParseException ex) {
                    throw new BootstrapException(ex);
                } finally {
                    reader.close();
                }
            }

            if (update) {
                new EtagDownload(librariesAsset.get("url").getAsString(),
                        new File(bootstrap.getInstallerFile() + ".libs")).download();

                FileReader reader = null;
                FileWriter writer = null;

                try {
                    reader = new FileReader(libs);
                    JsonObject libsJson = PARSER.parse(reader).getAsJsonObject();

                    JsonObject versionJson = new JsonObject();
                    versionJson.add("version", new JsonPrimitive(localVersion));

                    libsJson.add("installer", versionJson);
                    writer = new FileWriter(libs);
                    new Gson().toJson(libsJson, writer);
                } catch (JsonParseException ex) {
                    throw new BootstrapException(ex);
                } finally {
                    reader.close();
                    writer.close();
                }
            }

            EntityUtils.consume(entity);
        } else if (statusLine.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            System.err.println("Hit rate limit, skipping update check");
        } else {
            throw new BootstrapException("Error sending request to github. Error " + statusLine.getStatusCode()
                    + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        throw new BootstrapException(e);
    }
}

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Create a jar file at the given path, containing a manifest with a classpath that references all specified
 * entries.//from w ww  .  j a v a2 s.c  o m
 * <p>
 * Some platforms may have an upper limit on command line length.  For example, the maximum command line length on
 * Windows is 8191 characters, but the length of the classpath may exceed this.  To work around this limitation, use
 * this method to create a small intermediate jar with a manifest that contains the full classpath.  It returns the
 * absolute path to the new jar, which the caller may set as the classpath for a new process.
 * <p>
 * Environment variable evaluation is not supported within a jar manifest, so this method expands environment
 * variables before inserting classpath entries to the manifest.  The method parses environment variables according
 * to platform-specific syntax (%VAR% on Windows, or $VAR otherwise).  On Windows, environment variables are
 * case-insensitive.  For example, %VAR% and %var% evaluate to the same value.
 * <p>
 * Specifying the classpath in a jar manifest does not support wildcards, so this method expands wildcards
 * internally.  Any classpath entry that ends with * is translated to all files at that path with extension .jar or
 * .JAR.
 *
 * @param inputClassPath String input classpath to bundle into the jar manifest
 * @param pwd            Path to working directory to save jar
 * @param targetDir      path to where the jar execution will have its working dir
 * @param callerEnv      Map<String, String> caller's environment variables to use for expansion
 *
 * @return String[] with absolute path to new jar in position 0 and unexpanded wild card entry path in position 1
 *
 * @throws IOException if there is an I/O error while writing the jar file
 */
public static String[] createJarWithClassPath(String inputClassPath, Path pwd, Path targetDir,
        Map<String, String> callerEnv) throws IOException {
    // Replace environment variables, case-insensitive on Windows
    @SuppressWarnings("unchecked")
    Map<String, String> env = Shell.WINDOWS ? new CaseInsensitiveMap(callerEnv) : callerEnv;
    String[] classPathEntries = inputClassPath.split(File.pathSeparator);
    for (int i = 0; i < classPathEntries.length; ++i) {
        classPathEntries[i] = StringUtils.replaceTokens(classPathEntries[i], StringUtils.ENV_VAR_PATTERN, env);
    }
    File workingDir = new File(pwd.toString());
    if (!workingDir.mkdirs()) {
        // If mkdirs returns false because the working directory already exists,
        // then this is acceptable.  If it returns false due to some other I/O
        // error, then this method will fail later with an IOException while saving
        // the jar.
        LOG.debug("mkdirs false for " + workingDir + ", execution will continue");
    }

    StringBuilder unexpandedWildcardClasspath = new StringBuilder();
    // Append all entries
    List<String> classPathEntryList = new ArrayList<String>(classPathEntries.length);
    for (String classPathEntry : classPathEntries) {
        if (classPathEntry.length() == 0) {
            continue;
        }
        if (classPathEntry.endsWith("*")) {
            boolean foundWildCardJar = false;
            // Append all jars that match the wildcard
            Path globPath = new Path(classPathEntry).suffix("{.jar,.JAR}");
            FileStatus[] wildcardJars = FileContext.getLocalFSFileContext().util().globStatus(globPath);
            if (wildcardJars != null) {
                for (FileStatus wildcardJar : wildcardJars) {
                    foundWildCardJar = true;
                    classPathEntryList.add(wildcardJar.getPath().toUri().toURL().toExternalForm());
                }
            }
            if (!foundWildCardJar) {
                unexpandedWildcardClasspath.append(File.pathSeparator);
                unexpandedWildcardClasspath.append(classPathEntry);
            }
        } else {
            // Append just this entry
            File fileCpEntry = null;
            if (!new Path(classPathEntry).isAbsolute()) {
                fileCpEntry = new File(targetDir.toString(), classPathEntry);
            } else {
                fileCpEntry = new File(classPathEntry);
            }
            String classPathEntryUrl = fileCpEntry.toURI().toURL().toExternalForm();

            // File.toURI only appends trailing '/' if it can determine that it is a
            // directory that already exists.  (See JavaDocs.)  If this entry had a
            // trailing '/' specified by the caller, then guarantee that the
            // classpath entry in the manifest has a trailing '/', and thus refers to
            // a directory instead of a file.  This can happen if the caller is
            // creating a classpath jar referencing a directory that hasn't been
            // created yet, but will definitely be created before running.
            if (classPathEntry.endsWith(Path.SEPARATOR) && !classPathEntryUrl.endsWith(Path.SEPARATOR)) {
                classPathEntryUrl = classPathEntryUrl + Path.SEPARATOR;
            }
            classPathEntryList.add(classPathEntryUrl);
        }
    }
    String jarClassPath = StringUtils.join(" ", classPathEntryList);

    // Create the manifest
    Manifest jarManifest = new Manifest();
    jarManifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
    jarManifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), jarClassPath);

    // Write the manifest to output JAR file
    File classPathJar = File.createTempFile("classpath-", ".jar", workingDir);
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    JarOutputStream jos = null;
    try {
        fos = new FileOutputStream(classPathJar);
        bos = new BufferedOutputStream(fos);
        jos = new JarOutputStream(bos, jarManifest);
    } finally {
        IOUtils.cleanup(LOG, jos, bos, fos);
    }
    String[] jarCp = { classPathJar.getCanonicalPath(), unexpandedWildcardClasspath.toString() };
    return jarCp;
}

From source file:averroes.JarFile.java

/**
 * Get the output stream of this JAR archive.
 * // w w w  . j  a  v a  2 s  . c  o m
 * @return
 * @throws IOException
 */
public JarOutputStream getJarOutputStream() throws IOException {
    if (jarOutputStream == null) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        jarOutputStream = new JarOutputStream(new FileOutputStream(fileName), manifest);
    }
    return jarOutputStream;
}

From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java

private Manifest createSignatureFile(Manifest manifest) throws IOException {
    byte[] mfRawBytes;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        manifest.write(baos);/*from  w  ww .j  av a  2s .com*/
        mfRawBytes = baos.toByteArray();
    }

    Manifest sf = new Manifest();
    Attributes sfMain = sf.getMainAttributes();
    Map<String, Attributes> sfEntries = sf.getEntries();

    sfMain.put(Attributes.Name.SIGNATURE_VERSION, "1.0");
    sfMain.putValue("Created-By", "Apache Felix DeploymentPackageBuilder");
    sfMain.putValue(m_digestAlg + "-Digest-Manifest", calculateDigest(mfRawBytes));
    sfMain.putValue(m_digestAlg + "-Digest-Manifest-Main-Attribute",
            calculateDigest(getRawBytesMainAttributes(manifest)));

    for (Entry<String, Attributes> entry : manifest.getEntries().entrySet()) {
        String name = entry.getKey();
        byte[] entryData = getRawBytesAttributes(entry.getValue());

        sfEntries.put(name, getDigestAttributes(entryData));
    }
    return sf;
}

From source file:com.asual.summer.onejar.OneJarMojo.java

public void execute() throws MojoExecutionException {

    JarOutputStream out = null;//from w  w  w .j  a v a2 s .c  o  m
    JarInputStream in = null;

    try {

        File jarFile = new File(buildDirectory, jarName);
        File warFile = new File(buildDirectory, warName);

        Manifest manifest = new Manifest(new ByteArrayInputStream("Manifest-Version: 1.0\n".getBytes("UTF-8")));
        manifest.getMainAttributes().putValue("Main-Class", JAR_MAIN_CLASS);
        manifest.getMainAttributes().putValue("One-Jar-Main-Class", ONE_JAR_MAIN_CLASS);

        out = new JarOutputStream(new FileOutputStream(jarFile, false), manifest);
        in = new JarInputStream(getClass().getClassLoader().getResourceAsStream(ONE_JAR_DIST));

        putEntry(out, new FileInputStream(warFile), new ZipEntry(JAR_CLASSPATH + warFile.getName()));

        for (Artifact artifact : pluginArtifacts) {
            if (artifact.getArtifactId().equalsIgnoreCase("summer-onejar")) {
                artifact.updateVersion(artifact.getVersion(), localRepository);
                putEntry(out, new FileInputStream(artifact.getFile()),
                        new ZipEntry(JAR_CLASSPATH + artifact.getFile().getName()));
                MavenProject project = mavenProjectBuilder.buildFromRepository(artifact,
                        remoteArtifactRepositories, localRepository);
                List<Dependency> dependencies = project.getDependencies();
                for (Dependency dependency : dependencies) {
                    if (!"provided".equals(dependency.getScope())) {
                        Artifact dependencyArtifact = artifactFactory.createArtifact(dependency.getGroupId(),
                                dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(),
                                dependency.getType());
                        dependencyArtifact.updateVersion(dependencyArtifact.getVersion(), localRepository);
                        putEntry(out, new FileInputStream(dependencyArtifact.getFile()),
                                new ZipEntry(JAR_CLASSPATH + dependencyArtifact.getFile().getName()));
                    }
                }
            }
        }

        while (true) {
            ZipEntry entry = in.getNextEntry();
            if (entry != null) {
                putEntry(out, in, entry);
            } else {
                break;
            }
        }

        projectHelper.attachArtifact(project, "jar", jarFile);

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private static List<String> createClasspathJar(File dir, String jarName, List<String> manifestClasspath)
        throws IOException {
    List<String> classpathArgs = new ArrayList<String>();
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(manifestClasspath, ' '));
    File classpathJar = new File(dir, jarName);
    classpathJar.deleteOnExit();/*from www . j av  a2s  .  c  om*/
    try (JarOutputStream stream = new JarOutputStream(new FileOutputStream(classpathJar), manifest)) {
    }
    classpathArgs.add("-classpath");
    classpathArgs.add(classpathJar.getCanonicalPath());
    return classpathArgs;
}

From source file:org.reficio.p2.bundler.impl.AquteBundler.java

private void decorateSourceManifest(Manifest manifest, String name, String refrencedBundleSymbolicName,
        String symbolicName, String version) {
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue(Analyzer.BUNDLE_SYMBOLICNAME, symbolicName);
    attributes.putValue(ECLIPSE_SOURCE_BUNDLE,
            refrencedBundleSymbolicName + ";version=\"" + version + "\";roots:=\".\"");
    attributes.putValue(Analyzer.BUNDLE_VERSION, version);
    attributes.putValue(Analyzer.BUNDLE_LOCALIZATION, "plugin");
    attributes.putValue(MANIFEST_VERSION, "1.0");
    attributes.putValue(Analyzer.BUNDLE_MANIFESTVERSION, "2");
    attributes.putValue(Analyzer.BUNDLE_NAME, name);
    attributes.putValue(IMPLEMENTATION_TITLE, name);
    attributes.putValue(SPECIFICATION_TITLE, name);
    attributes.putValue(AquteHelper.TOOL_KEY, AquteHelper.TOOL);
}

From source file:com.twosigma.beaker.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }/*from   w ww  .  j  a va  2 s  .co m*/
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                File child = new File(
                                        file.getParent() + System.getProperty("file.separator") + fn);
                                if (child.getAbsolutePath().equals(jar.getName())) {
                                    continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                }
                                if (child.exists()) {
                                    if (!findClasses(root, child, includeJars)) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}