Example usage for java.util.jar JarFile getManifest

List of usage examples for java.util.jar JarFile getManifest

Introduction

In this page you can find the example usage for java.util.jar JarFile getManifest.

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

From source file:com.wavemaker.tools.ant.NewCopyRuntimeJarsTask.java

protected List<String> getReferencedClassPathJars(File jarFile, boolean failOnError) {

    try {//w  w  w.  j  a  va  2 s . c  o  m
        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:cn.homecredit.web.listener.MyOsgiHost.java

protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {/*from   ww  w.j  a va2 s.  c  om*/
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());
            }
        }
    }
    return "1.0.0";
}

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

@Override
public void run(Bootstrap bootstrap) {
    try {//from w  ww.  ja  v a2  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:org.apache.servicemix.war.deployer.WarDeploymentListener.java

public boolean canHandle(File artifact) {
    try {//  w w  w.  j  a v  a2  s .c  o m
        JarFile jar = new JarFile(artifact);
        JarEntry entry = jar.getJarEntry("WEB-INF/web.xml");
        // Only handle WAR artifacts
        if (entry == null) {
            return false;
        }
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
                && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.felix.webconsole.internal.core.InstallAction.java

private String getSymbolicName(File bundleFile) {
    JarFile jar = null;
    try {//from   w w w .java  2s  .  c  om
        jar = new JarFile(bundleFile);
        Manifest m = jar.getManifest();
        if (m != null) {
            return m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        }
    } catch (IOException ioe) {
        getLog().log(LogService.LOG_WARNING, "Cannot extract symbolic name of bundle file " + bundleFile, ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // fall back to "not found"
    return null;
}

From source file:simpleserver.minecraft.MinecraftWrapper.java

private String getCommand() {
    int minimumMemory = MINIMUM_MEMORY;
    String arguments = "";

    if (options.contains("javaArguments")) {
        arguments = options.get("javaArguments");
    }/*from  w w  w.  ja v a  2 s .c o m*/

    if (options.getInt("memory") < minimumMemory) {
        minimumMemory = options.getInt("memory");
    }

    if (!options.getBoolean("overwriteArguments")) {
        String memoryArgs;
        if (options.getBoolean("useXincgc")) {
            memoryArgs = String.format(XINCGC_FORMAT, options.get("memory"));
        } else {
            memoryArgs = String.format(MEMORY_FORMAT, minimumMemory, options.get("memory"));
        }
        arguments = String.format("%s %s %s", arguments, memoryArgs, DEFAULT_ARGUMENTS);
    }
    if (options.getBoolean("enablePlugins")) {
        String mainclass = null;
        try {
            JarFile jarFile = new JarFile(getServerJar());
            mainclass = jarFile.getManifest().getMainAttributes().getValue("Main-Class");
            jarFile.close();
        } catch (IOException e) {
            System.out.println("[SimpleServer] " + e);
            System.out.println("[SimpleServer] FATAL ERROR: Could not read minecraft_server.jar!");
            System.exit(-1);
        }
        String[] plugins = new File("plugins").list(new WildcardFileFilter("*.zip"));
        if (plugins == null) {
            plugins = new String[0];
        }
        Arrays.sort(plugins);
        ArrayList<String> plugstrs = new ArrayList<String>(plugins.length + 1);
        for (String fname : plugins) {
            plugstrs.add("plugins/" + fname);
        }
        plugstrs.add(getServerJar());
        String clspath = StringUtils.join(plugstrs, ":");
        return String.format(COMMAND_FORMAT_PLUGINS, arguments, clspath, mainclass, modArguments());
    } else {
        return String.format(COMMAND_FORMAT, arguments, getServerJar(), modArguments());
    }
}

From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java

/**
 * Deploy a module bundle on MMP server/*from ww w.j av  a  2s .c  o m*/
 * @param moduleFile The module file (JAR file)
 */
@SuppressWarnings("unchecked")
public Module deployModule(File moduleFile) throws MMPException {
    try {
        JarFile jarFile = new JarFile(new File(moduleFile.toURI()));
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            throw new MMPException("invalid module archive, MANIFEST file not found");
        }
        // Get Bundle category
        Attributes attributes = manifest.getMainAttributes();
        String category = attributes.getValue(BUNDLE_CATEGORY_HEADER);
        // Test if the module is a widget
        if (category != null && category.equals(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET)) {
            Widget widget = new Widget();
            String symbName = attributes.getValue(BUNDLE_SYMBOLICNAME_HEADER);
            String branch = symbName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)[1];
            widget.setLocation(moduleFile.toURI());
            widget.setBranchId(branch);
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(widget);
            this.lastUpdate = 0;
            this.refresh();
            return widget;
        } else {
            Module module = new Module();
            module.setLocation(moduleFile.toURI());
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(module);
            this.lastUpdate = 0;
            this.refresh();
            return module;
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy module", ioe);
    }
}

From source file:org.apache.flink.client.web.JobsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter(ACTION_PARAM_NAME);

    if (action.equals(ACTION_LIST_VALUE)) {
        GregorianCalendar cal = new GregorianCalendar();

        File[] files = destinationDir.listFiles();
        Arrays.<File>sort(files, FILE_SORTER);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(CONTENT_TYPE_PLAIN);

        PrintWriter writer = resp.getWriter();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].getName().endsWith(".jar")) {
                continue;
            }// w  ww  . jav  a 2 s.co m

            JarFile jar = new JarFile(files[i]);
            Manifest manifest = jar.getManifest();
            String assemblerClass = null;
            String descriptions = "";

            if (manifest != null) {
                assemblerClass = manifest.getMainAttributes()
                        .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_ASSEMBLER_CLASS);
                if (assemblerClass == null) {
                    assemblerClass = manifest.getMainAttributes()
                            .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_MAIN_CLASS);
                }
            }
            if (assemblerClass == null) {
                assemblerClass = "";
            } else {
                String[] classes = assemblerClass.split(",");
                for (String c : classes) {
                    try {
                        String d = new PackagedProgram(files[i], c, new String[0]).getDescription();
                        if (d == null) {
                            d = "No description provided.";
                        }
                        descriptions += "#_#" + d;
                    } catch (ProgramInvocationException e) {
                        descriptions += "#_#No description provided.";
                        continue;
                    }
                }

                assemblerClass = '\t' + assemblerClass;
            }

            cal.setTimeInMillis(files[i].lastModified());
            writer.println(files[i].getName() + '\t' + (cal.get(GregorianCalendar.MONTH) + 1) + '/'
                    + cal.get(GregorianCalendar.DAY_OF_MONTH) + '/' + cal.get(GregorianCalendar.YEAR) + ' '
                    + cal.get(GregorianCalendar.HOUR_OF_DAY) + ':' + cal.get(GregorianCalendar.MINUTE) + ':'
                    + cal.get(GregorianCalendar.SECOND) + assemblerClass + descriptions);
        }
    } else if (action.equals(ACTION_DELETE_VALUE)) {
        String filename = req.getParameter(FILENAME_PARAM_NAME);

        if (filename == null || filename.length() == 0) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            File f = new File(destinationDir, filename);
            if (!f.exists() || f.isDirectory()) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
            f.delete();
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.amalto.core.jobox.component.JobAware.java

private boolean recognizeTISJob(File entity) {
    boolean isTISEntry = false;
    List<File> checkList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, entity, "classpath.jar", checkList); //$NON-NLS-1$
    if (checkList.size() > 0) {
        try {/*from  www .j a  v a 2 s.  c  o  m*/
            JarFile jarFile = new JarFile(checkList.get(0).getAbsolutePath());
            Manifest jarFileManifest = jarFile.getManifest();
            String vendorInfo = jarFileManifest.getMainAttributes().getValue("Implementation-Vendor"); //$NON-NLS-1$
            if (vendorInfo.trim().toUpperCase().startsWith("TALEND")) //$NON-NLS-1$
                isTISEntry = true;
        } catch (IOException e) {
            throw new JoboxException(e);
        }
    }
    return isTISEntry;
}

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

public Manifest getManifest() throws IOException {
    if (manifest == null) {
        File f = resolve();/*w  ww .jav  a 2s .  c  o  m*/
        try {
            JarFile jar = new JarFile(f);
            ZipEntry e = jar.getEntry("META-INF/MANIFEST.MF");
            timestamp = e.getTime();
            manifest = jar.getManifest();
            jar.close();
        } catch (IOException x) {
            throw (IOException) new IOException("Failed to open " + f).initCause(x);
        }
    }
    return manifest;
}