Example usage for java.util.jar Manifest Manifest

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

Introduction

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

Prototype

public Manifest(Manifest man) 

Source Link

Document

Constructs a new Manifest that is a copy of the specified Manifest.

Usage

From source file:org.openhab.tools.analysis.checkstyle.ServiceComponentManifestCheck.java

private void verifyManifest(FileText fileText) {
    File file = fileText.getFile();

    manifestPath = file.getPath();//from   w  ww . j a  va 2  s . c o m
    try {
        Manifest manifest = new Manifest(new FileInputStream(file));
        Attributes attributes = manifest.getMainAttributes();

        serviceComponentHeaderValue = attributes.getValue(SERVICE_COMPONENT_HEADER_NAME);

        if (serviceComponentHeaderValue != null) {
            serviceComponentHeaderLineNumber = findLineNumberSafe(fileText, SERVICE_COMPONENT_HEADER_NAME, 0,
                    "Service component header line number not found.");
            List<String> serviceComponentsList = Arrays.asList(serviceComponentHeaderValue.trim().split(","));
            for (String serviceComponent : serviceComponentsList) {
                // We assume that the defined service component refers to existing file
                File serviceComponentFile = new File(serviceComponent);
                String serviceComponentParentDirectoryName = serviceComponentFile.getParentFile().getName();

                if (!serviceComponentParentDirectoryName.equals(OSGI_INF_DIRECTORY_NAME)) {
                    // if the parent directory of the service is not
                    // OSGI-INF
                    logMessage(serviceComponentHeaderLineNumber,
                            String.format("Incorrect directory for services - %s. "
                                    + "The best practice is services metadata files to be placed directly in OSGI-INF directory.",
                                    serviceComponentParentDirectoryName));
                }

                String serviceComponentName = serviceComponentFile.getName();

                // We will process either .xml or OSGi-INF/* service components
                if (serviceComponentName.endsWith(XML_EXTENSION) || serviceComponentName.endsWith(WILDCARD)) {
                    manifestServiceComponents.add(serviceComponentName);
                } else {
                    logMessage(serviceComponentHeaderLineNumber,
                            String.format("The service %s is with invalid extension."
                                    + "Only XML metadata files for services description are expected in the OSGI-INF directory.",
                                    serviceComponentName));
                }
            }
        }
    } catch (IOException e) {
        logger.error("Problem occurred while parsing the file " + file.getPath(), e);
    }
}

From source file:org.rhq.plugins.jbossas.util.FileContentDelegate.java

/**
 * Write the SHA256 to the manifest using the RHQ-Sha256 attribute tag.
 *
 * @param deploymentFolder app deployment folder
 * @param sha SHA256// w  ww  . j  a v a2s. com
 * @throws IOException
 */
private void writeSHAToManifest(File deploymentFolder, String sha) throws IOException {
    File manifestFile = new File(deploymentFolder, MANIFEST_RELATIVE_PATH);
    Manifest manifest;
    if (manifestFile.exists()) {
        FileInputStream inputStream = new FileInputStream(manifestFile);
        try {
            manifest = new Manifest(inputStream);
        } finally {
            inputStream.close();
        }
    } else {
        manifest = new Manifest();
        manifestFile.getParentFile().mkdirs();
        manifestFile.createNewFile();
    }

    Attributes attribs = manifest.getMainAttributes();

    //The main section of the manifest file does not get saved if both of
    //these two attributes are missing. Please see Attributes implementation.
    if (!attribs.containsKey(Attributes.Name.MANIFEST_VERSION.toString())
            && !attribs.containsKey(Attributes.Name.SIGNATURE_VERSION.toString())) {
        attribs.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
    }

    attribs.putValue(RHQ_SHA_256, sha);

    FileOutputStream outputStream = new FileOutputStream(manifestFile);
    try {
        manifest.write(outputStream);
    } finally {
        outputStream.close();
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.dialogs.About.java

@SuppressWarnings("unchecked")
private void startup() {
    try {/*from   www  .j  a va2 s.  co m*/
        try {
            theFormControl = new FormControl(this, theSettingsPath);
        } catch (Exception ex) {
            LOG.error("Error loading form parameters", ex);
        }
        ClassLoader cLoader = Thread.currentThread().getContextClassLoader();
        Toolkit kit = Toolkit.getDefaultToolkit();
        Package p = this.getClass().getPackage();
        lblVersion.setText(p.getImplementationVersion());
        if (new File(theLogoFileName).exists()) {
            theLogo = kit.getImage(theLogoFileName);
        } else {
            java.net.URL imageURL = cLoader.getResource(theLogoFileName);
            if (imageURL != null) {
                theLogo = kit.getImage(imageURL);
            }
        }
        if (theLogo != null) {
            lblBuildNo.setForeground(Color.white);
            lblBuildNoLabel.setForeground(Color.white);
            //lblHeader.setForeground(Color.white);
            lblVersion.setForeground(Color.white);
            lblVersionLabel.setForeground(Color.white);
            paintImage();
        }
        //String manifestFileName = "/META-INF/MANIFEST.MF";
        Class cls = this.getClass();

        String className = cls.getSimpleName();
        String classFileName = className + ".class";
        String pathToThisClass = cls.getResource(classFileName).toString();
        int mark = pathToThisClass.indexOf("!");
        String pathToManifest = pathToThisClass.substring(0, mark + 1);
        if (!pathToManifest.equals("")) {
            pathToManifest += "/META-INF/MANIFEST.MF";
            LOG.debug("Path to manifest: " + pathToManifest);
            Manifest mf = new Manifest(new URL(pathToManifest).openStream());
            if (mf != null) {
                Attributes attr = mf.getMainAttributes();
                String attrVersion = "Implementation-Version";
                String attrBuild = "Implementation-Build";
                String version = attr.getValue(attrVersion);
                String build = attr.getValue(attrBuild);
                this.lblVersion.setText(version);
                this.lblBuildNo.setText(build);
            }
        }
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        LOG.debug("free memory: " + freeMemory / 1024);
        LOG.debug("allocated memory: " + allocatedMemory / 1024);
        LOG.debug("max memory: " + maxMemory / 1024);
        LOG.debug("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024);
    } catch (IOException ex) {
        ex.printStackTrace();
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {/*www .  j  a v  a 2s .co m*/
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:io.selendroid.builder.SelendroidServerBuilder.java

public static String getJarVersionNumber() {
    Class clazz = SelendroidStandaloneDriver.class;
    String className = clazz.getSimpleName() + ".class";
    String classPath = clazz.getResource(className).toString();
    if (!classPath.startsWith("jar")) {
        // Class not from JAR
        return "dev";
    }//  ww w .  ja  v a2  s.c  om
    String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
    Manifest manifest = null;
    try {
        manifest = new Manifest(new URL(manifestPath).openStream());
    } catch (Exception e) {
        return "";
    }
    Attributes attr = manifest.getMainAttributes();
    String value = attr.getValue("version");
    return value;
}

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;/*from w ww .j a va 2s  .co m*/
            } 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.eclipse.smarthome.test.SyntheticBundleInstaller.java

private static Manifest getManifest(Bundle bundle, String bundlePath) throws IOException {
    String filePath = bundlePath + "/" + "META-INF/MANIFEST.MF";
    URL resource = bundle.getResource(filePath);
    if (resource == null) {
        return null;
    }/*from  w w w.j a va2  s .c o  m*/
    return new Manifest(resource.openStream());
}

From source file:org.orbisgis.core.plugin.BundleTools.java

private static void parseDirectoryManifest(File rootPath, File path, List<PackageDeclaration> packages)
        throws SecurityException {
    File[] files = path.listFiles();
    for (File file : files) {
        // TODO Java7 check for non-symlink,
        // without this check it might generate an infinite loop
        // @link http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isSymbolicLink(java.nio.file.Path)
        if (!file.isDirectory()) {
            if (file.getName().equals(MANIFEST_FILENAME)) {
                try {
                    Manifest manifest = new Manifest(new FileInputStream(file));
                    parseManifest(manifest, packages);
                } catch (Exception ex) {
                    LOGGER.warn("Unable to read manifest in " + file.getAbsolutePath(), ex);
                }/*  w w  w. ja  va  2 s  .c o m*/
            }
            if (FilenameUtils.getExtension(file.getName()).equals("jar") && file.exists()) {
                try {
                    parseJarManifest(file, packages);
                } catch (IOException ex) {
                    LOGGER.warn("Unable to fetch packages in " + file.getAbsolutePath(), ex);
                }
            }
        } else {
            parseDirectoryManifest(rootPath, file, packages);
        }
    }
}

From source file:me.azenet.UHPlugin.UHPluginCommand.java

/**
 * This command prints some informations about the plugin and the translation.
 * /*from w  ww.j a  va 2s .c o  m*/
 * Usage: /uh about
 * 
 * @param sender
 * @param command
 * @param label
 * @param args
 */
@SuppressWarnings("unused")
private void doAbout(CommandSender sender, Command command, String label, String[] args) {
    if (sender instanceof Player)
        sender.sendMessage("");
    sender.sendMessage(
            i.t("cmd.titleHelp", p.getDescription().getDescription(), p.getDescription().getVersion()));

    // Authors

    String authors = "";
    List<String> listAuthors = p.getDescription().getAuthors();
    for (String author : listAuthors) {
        if (author == listAuthors.get(0)) {
            // Nothing
        } else if (author == listAuthors.get(listAuthors.size() - 1)) {
            authors += " " + i.t("about.and") + " ";
        } else {
            authors += ", ";
        }
        authors += author;
    }
    sender.sendMessage(i.t("about.authors", authors));

    // Build number

    String build = null;
    try {
        Class<? extends UHPlugin> clazz = p.getClass();
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        if (classPath.startsWith("jar")) { // Class from JAR
            String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
                    + "/META-INF/MANIFEST.MF";
            Manifest manifest = new Manifest(new URL(manifestPath).openStream());
            Attributes attr = manifest.getMainAttributes();

            build = attr.getValue("Git-Commit");
        }
    } catch (IOException e) {
        // Build not available.
    }

    if (build != null) {
        sender.sendMessage(i.t("about.build.number", build));
    } else {
        sender.sendMessage(i.t("about.build.notAvailable"));
    }

    // Translation

    sender.sendMessage(i.t("about.i18n.title"));
    sender.sendMessage(
            i.t("about.i18n.selected", i.getSelectedLanguage(), i.getTranslator(i.getSelectedLanguage())));
    sender.sendMessage(
            i.t("about.i18n.fallback", i.getDefaultLanguage(), i.getTranslator(i.getDefaultLanguage())));
    sender.sendMessage(i.t("about.license.title"));
    sender.sendMessage(i.t("about.license.license"));
}

From source file:cascading.flow.hadoop.util.HadoopUtil.java

private static PlatformInfo getPlatformInfoInternal() {
    URL url = JobConf.class.getResource(JobConf.class.getSimpleName() + ".class");

    if (url == null || !url.toString().startsWith("jar"))
        return new PlatformInfo("Hadoop", null, null);

    String path = url.toString();
    String manifestPath = path.substring(0, path.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";

    Manifest manifest;/*from  ww w .ja v  a 2  s  . c om*/

    try {
        manifest = new Manifest(new URL(manifestPath).openStream());
    } catch (IOException exception) {
        LOG.warn("unable to get manifest from {}", manifestPath, exception);

        return new PlatformInfo("Hadoop", null, null);
    }

    Attributes attributes = manifest.getAttributes("org/apache/hadoop");

    if (attributes == null) {
        LOG.debug("unable to get Hadoop manifest attributes");
        return new PlatformInfo("Hadoop", null, null);
    }

    String vendor = attributes.getValue("Implementation-Vendor");
    String version = attributes.getValue("Implementation-Version");

    return new PlatformInfo("Hadoop", vendor, version);
}