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:eu.chocolatejar.eclipse.plugin.cleaner.ArtifactParser.java

private Manifest readManifestfromJarOrDirectory(File file) {
    try {//w  w  w.ja va 2 s  .c  om
        Manifest bundleManifest = null;

        try (final FileInputStream is = new FileInputStream(file)) {
            final boolean isJar = "jar".equalsIgnoreCase(FilenameUtils.getExtension(file.getName()));
            if (isJar) {
                try (final JarInputStream jis = new JarInputStream(is)) {
                    bundleManifest = jis.getManifest();
                }
            } else {
                bundleManifest = new Manifest(is);
            }
        }
        return bundleManifest;
    } catch (IOException e) {
        logger.debug("Unable to read manifest from jar or directory.", e);
        return null;
    }
}

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);//  w  w  w  . j av a2  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-"));
}

From source file:ZipImploder.java

/**
 * Main command line entry point.//from w w  w .j  a va 2 s .co  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String zipName = null;
    String jarName = null;
    String manName = null;
    String sourceDir = null;
    String leadDir = null;
    boolean jarActive = false, manActive = false, zipActive = false, sourceDirActive = false,
            leadDirActive = false;
    boolean verbose = false;
    boolean noDirs = false;
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("jar")) {
                jarActive = true;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("manifest")) {
                jarActive = false;
                manActive = true;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                manActive = false;
                jarActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = true;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("lead")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = true;
            } else if (arg.equalsIgnoreCase("noDirs")) {
                noDirs = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                if (jarName != null) {
                    reportError("Duplicate value - " + arg);
                }
                jarName = arg;
            } else if (manActive) {
                if (manName != null) {
                    reportError("Duplicate value - " + arg);
                }
                manName = arg;
            } else if (zipActive) {
                if (zipName != null) {
                    reportError("Duplicate value - " + arg);
                }
                zipName = arg;
            } else if (sourceDirActive) {
                if (sourceDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                sourceDir = arg;
            } else if (leadDirActive) {
                if (leadDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                leadDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (sourceDir == null || (zipName == null && jarName == null)) {
        reportError("Missing parameters");
    }
    if (manName != null && zipName != null) {
        reportError("Manifests not supported on ZIP files");
    }
    if (leadDir == null) {
        leadDir = new File(sourceDir).getAbsolutePath().replace('\\', '/') + '/';
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipImploder.class.getName()
                + (jarName != null ? " -jar " + jarName + (manName != null ? " -manifest " + manName : "") : "")
                + (zipName != null ? " -zip " + zipName : "") + " -dir " + sourceDir + " -lead " + leadDir
                + (noDirs ? " -noDirs" : "") + (verbose ? " -verbose" : ""));
    }
    try {
        ZipImploder zi = new ZipImploder(verbose);
        if (leadDir != null) {
            zi.setBaseDir(leadDir);
        }
        if (manName != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(manName));
            try {
                zi.setManifest(new Manifest(bis));
            } finally {
                bis.close();
            }
        }
        zi.setIncludeDirs(!noDirs);
        zi.process(zipName, jarName, sourceDir);
        if (verbose) {
            System.out.println("\nDone Directories=" + zi.getDirCount() + " Files=" + zi.getFileCount());
        }
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        // ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}

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

public void loadMapPack(File mapPackFile, MapSourcesManager mapSourcesManager)
        throws CertificateException, IOException, MapSourceCreateException {
    // testMapPack(mapPackFile);
    URLClassLoader urlCl;//from   www .jav  a  2 s  .com
    URL url = mapPackFile.toURI().toURL();
    urlCl = new MapPackClassLoader(url, ClassLoader.getSystemClassLoader());
    InputStream manifestIn = urlCl.getResourceAsStream("META-INF/MANIFEST.MF");
    String rev = null;
    if (manifestIn != null) {
        Manifest mf = new Manifest(manifestIn);
        rev = mf.getMainAttributes().getValue("MapPackRevision");
        manifestIn.close();
        if (rev != null) {
            if ("exported".equals(rev)) {
                rev = ProgramInfo.getRevisionStr();
            } else {
                rev = Integer.toString(Utilities.parseSVNRevision(rev));
            }
        }
        mf = null;
    }
    MapSourceLoaderInfo loaderInfo = new MapSourceLoaderInfo(LoaderType.MAPPACK, mapPackFile, rev);
    final Iterator<MapSource> iterator = ServiceLoader.load(MapSource.class, urlCl).iterator();

    while (iterator.hasNext()) {
        try {
            MapSource ms = iterator.next();
            ms.setLoaderInfo(loaderInfo);
            mapSourcesManager.addMapSource(ms);
            log.trace("Loaded map source: " + ms.toString() + " (name: " + ms.getName() + ")");
        } catch (Error e) {
            urlCl = null;
            throw new MapSourceCreateException("Failed to load a map sources from map pack: "
                    + mapPackFile.getName() + " " + e.getMessage(), e);
        }
    }
}

From source file:org.rhq.plugins.jbossas5.deploy.ManagedComponentDeployer.java

public void deploy(CreateResourceReport createResourceReport, ResourceType resourceType) {
    createResourceReport.setStatus(null);
    File archiveFile = null;/*from w  ww.ja v  a 2  s .c  o m*/

    try {
        ResourcePackageDetails details = createResourceReport.getPackageDetails();
        PackageDetailsKey key = details.getKey();

        archiveFile = downloader.prepareArchive(key, resourceType);

        String archiveName = key.getName();

        if (!DeploymentUtils.hasCorrectExtension(archiveName, resourceType)) {
            createResourceReport.setStatus(CreateResourceStatus.FAILURE);
            createResourceReport
                    .setErrorMessage("Incorrect extension specified on filename [" + archiveName + "]");
            return;
        }

        abortIfApplicationAlreadyDeployed(resourceType, archiveFile);

        Configuration deployTimeConfig = details.getDeploymentTimeConfiguration();
        @SuppressWarnings({ "ConstantConditions" })
        boolean deployExploded = deployTimeConfig.getSimple("deployExploded").getBooleanValue();

        DeploymentManager deploymentManager = this.profileServiceConnection.getDeploymentManager();
        boolean deployFarmed = deployTimeConfig.getSimple("deployFarmed").getBooleanValue();
        if (deployFarmed) {
            Collection<ProfileKey> profileKeys = deploymentManager.getProfiles();
            boolean farmSupported = false;
            for (ProfileKey profileKey : profileKeys) {
                if (profileKey.getName().equals(FARM_PROFILE_KEY.getName())) {
                    farmSupported = true;
                    break;
                }
            }
            if (!farmSupported) {
                throw new IllegalStateException("This application server instance is not a node in a cluster, "
                        + "so it does not support farmed deployments. Supported deployment profiles are "
                        + profileKeys + ".");
            }
            if (deployExploded) {
                throw new IllegalArgumentException(
                        "Deploying farmed applications in exploded form is not supported by the Profile Service.");
            }
            deploymentManager.loadProfile(FARM_PROFILE_KEY);
        }

        String[] deploymentNames;
        try {
            deploymentNames = DeploymentUtils.deployArchive(deploymentManager, archiveFile, deployExploded);
        } finally {
            // Make sure to switch back to the 'applications' profile if we switched to the 'farm' profile above.
            if (deployFarmed) {
                deploymentManager.loadProfile(APPLICATIONS_PROFILE_KEY);
            }
        }

        if (deploymentNames == null || deploymentNames.length != 1) {
            throw new RuntimeException("deploy operation returned invalid result: " + deploymentNames);
        }

        // e.g.: vfszip:/C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war
        String deploymentName = deploymentNames[0];

        // If deployed exploded, we need to store the SHA of source package in META-INF/MANIFEST.MF for correct
        // versioning.
        if (deployExploded) {
            MessageDigestGenerator sha256Generator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
            String shaString = sha256Generator.calcDigestString(archiveFile);
            URI deploymentURI = URI.create(deploymentName);
            // e.g.: /C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war
            String deploymentPath = deploymentURI.getPath();
            File deploymentFile = new File(deploymentPath);
            if (deploymentFile.isDirectory()) {
                File manifestFile = new File(deploymentFile, "META-INF/MANIFEST.MF");
                Manifest manifest;
                if (manifestFile.exists()) {
                    FileInputStream inputStream = new FileInputStream(manifestFile);
                    try {
                        manifest = new Manifest(inputStream);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    File metaInf = new File(deploymentFile, "META-INF");
                    if (!metaInf.exists())
                        if (!metaInf.mkdir())
                            throw new Exception("Could not create directory " + deploymentFile + "META-INF.");

                    manifestFile = new File(metaInf, "MANIFEST.MF");
                    manifest = new Manifest();
                }
                Attributes attribs = manifest.getMainAttributes();
                attribs.putValue("RHQ-Sha256", shaString);
                FileOutputStream outputStream = new FileOutputStream(manifestFile);
                try {
                    manifest.write(outputStream);
                } finally {
                    outputStream.close();
                }
            } else {
                LOG.error("Exploded deployment '" + deploymentFile
                        + "' does not exist or is not a directory - unable to add RHQ versioning metadata to META-INF/MANIFEST.MF.");
            }
        }

        // Reload the management view to pickup the ManagedDeployment for the app we just deployed.
        ManagementView managementView = this.profileServiceConnection.getManagementView();
        managementView.load();

        ManagedDeployment managedDeployment = null;
        try {
            managedDeployment = managementView.getDeployment(deploymentName);
        } catch (NoSuchDeploymentException e) {
            LOG.error("Failed to find managed deployment '" + deploymentName + "' after deploying '"
                    + archiveName + "', so cannot start the application.");
            createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT);
            createResourceReport.setErrorMessage("Unable to start application '" + deploymentName
                    + "' after deploying it, since lookup of the associated ManagedDeployment failed.");
        }
        if (managedDeployment != null) {
            DeploymentState state = managedDeployment.getDeploymentState();
            if (state != DeploymentState.STARTED) {
                // The app failed to start - do not consider this a FAILURE, since it was at least deployed
                // successfully. However, set the status to INVALID_ARTIFACT and set an error message, so
                // the user is informed of the condition.
                createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT);
                createResourceReport.setErrorMessage(
                        "Failed to start application '" + deploymentName + "' after deploying it.");
            }
        }

        createResourceReport.setResourceName(archiveName);
        createResourceReport.setResourceKey(archiveName);
        if (createResourceReport.getStatus() == null) {
            // Deployment was 100% successful, including starting the app.
            createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
        }
    } catch (Throwable t) {
        LOG.error("Error deploying application for request [" + createResourceReport + "].", t);
        createResourceReport.setStatus(CreateResourceStatus.FAILURE);
        createResourceReport.setException(t);
    } finally {
        if (archiveFile != null) {
            downloader.destroyArchive(archiveFile);
        }
    }
}

From source file:hudson.ClassicPluginStrategy.java

@Override
public PluginWrapper createPluginWrapper(File archive) throws IOException {
    final Manifest manifest;

    URL baseResourceURL = null;//w  w  w  .  ja  va 2  s  .  c  o  m
    File expandDir = null;
    // if .hpi, this is the directory where war is expanded

    boolean isLinked = isLinked(archive);
    if (isLinked) {
        manifest = loadLinkedManifest(archive);
    } else {
        if (archive.isDirectory()) {// already expanded
            expandDir = archive;
        } else {
            expandDir = new File(archive.getParentFile(), getBaseName(archive.getName()));
            explode(archive, expandDir);
        }

        File manifestFile = new File(expandDir, PluginWrapper.MANIFEST_FILENAME);
        if (!manifestFile.exists()) {
            throw new IOException("Plugin installation failed. No manifest at " + manifestFile);
        }
        FileInputStream fin = new FileInputStream(manifestFile);
        try {
            manifest = new Manifest(fin);
        } finally {
            fin.close();
        }
    }

    final Attributes atts = manifest.getMainAttributes();

    // TODO: define a mechanism to hide classes
    // String export = manifest.getMainAttributes().getValue("Export");

    List<File> paths = new ArrayList<File>();
    if (isLinked) {
        parseClassPath(manifest, archive, paths, "Libraries", ",");
        parseClassPath(manifest, archive, paths, "Class-Path", " +"); // backward compatibility

        baseResourceURL = resolve(archive, atts.getValue("Resource-Path")).toURI().toURL();
    } else {
        File classes = new File(expandDir, "WEB-INF/classes");
        if (classes.exists())
            paths.add(classes);
        File lib = new File(expandDir, "WEB-INF/lib");
        File[] libs = lib.listFiles(JAR_FILTER);
        if (libs != null)
            paths.addAll(Arrays.asList(libs));

        try {
            Class pathJDK7 = Class.forName("java.nio.file.Path");
            Object toPath = File.class.getMethod("toPath").invoke(expandDir);
            URI uri = (URI) pathJDK7.getMethod("toUri").invoke(toPath);

            baseResourceURL = uri.toURL();
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        } catch (ClassNotFoundException e) {
            baseResourceURL = expandDir.toURI().toURL();
        } catch (InvocationTargetException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        }
    }
    File disableFile = new File(archive.getPath() + ".disabled");
    if (disableFile.exists()) {
        LOGGER.info("Plugin " + archive.getName() + " is disabled");
    }

    // compute dependencies
    List<PluginWrapper.Dependency> dependencies = new ArrayList<PluginWrapper.Dependency>();
    List<PluginWrapper.Dependency> optionalDependencies = new ArrayList<PluginWrapper.Dependency>();
    String v = atts.getValue("Plugin-Dependencies");
    if (v != null) {
        for (String s : v.split(",")) {
            PluginWrapper.Dependency d = new PluginWrapper.Dependency(s);
            if (d.optional) {
                optionalDependencies.add(d);
            } else {
                dependencies.add(d);
            }
        }
    }
    for (DetachedPlugin detached : DETACHED_LIST)
        detached.fix(atts, optionalDependencies);

    // Register global classpath mask. This is useful for hiding JavaEE APIs that you might see from the container,
    // such as database plugin for JPA support. The Mask-Classes attribute is insufficient because those classes
    // also need to be masked by all the other plugins that depend on the database plugin.
    String masked = atts.getValue("Global-Mask-Classes");
    if (masked != null) {
        for (String pkg : masked.trim().split("[ \t\r\n]+"))
            coreClassLoader.add(pkg);
    }

    ClassLoader dependencyLoader = new DependencyClassLoader(coreClassLoader, archive,
            Util.join(dependencies, optionalDependencies));
    dependencyLoader = getBaseClassLoader(atts, dependencyLoader);

    return new PluginWrapper(pluginManager, archive, manifest, baseResourceURL,
            createClassLoader(paths, dependencyLoader, atts), disableFile, dependencies, optionalDependencies);
}

From source file:org.pepstock.jem.gwt.server.listeners.StartUp.java

/**
 * Set the jem Version//from  w  w w .  ja v  a  2 s .  c  om
 * 
 * @param contextPath
 */
private void setJemVersion(ServletContext context) {
    // reads manifest file for searching version of JEM
    InputStream fis = null;
    try {
        fis = context.getResourceAsStream(MANIFEST_FILE);
        if (fis == null) {
            throw new FileNotFoundException(MANIFEST_FILE);
        }
        Manifest manifest = new Manifest(fis);
        // gets JEM vrsion
        Attributes at = manifest.getAttributes(ConfigKeys.JEM_MANIFEST_SECTION);
        String jemVersion = at.getValue(ConfigKeys.JEM_MANIFEST_VERSION);
        // saves JEM version
        if (jemVersion != null) {
            SharedObjects.getInstance().setJemVersion(jemVersion);
        }
    } catch (FileNotFoundException e) {
        // to ignore stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } catch (IOException e) {
        // to ignore stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }

}

From source file:com.github.lindenb.jvarkit.util.command.CommandFactory.java

private void loadManifest() {
    try {//from  w w w  . j a v a 2s  . co m

        Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");//not '/META-INF'
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            InputStream in = url.openStream();
            if (in == null) {
                continue;
            }

            Manifest m = new Manifest(in);
            in.close();
            in = null;
            java.util.jar.Attributes attrs = m.getMainAttributes();
            if (attrs == null) {
                continue;
            }
            String s = attrs.getValue("Git-Hash");
            if (s != null && !s.isEmpty() && !s.contains("$")) //ant failed
            {
                this.version = s;
            }

            s = attrs.getValue("Compile-Date");
            if (s != null && !s.isEmpty()) //ant failed
            {
                this.compileDate = s;
            }
        }
    } catch (Exception err) {

    }

}

From source file:com.conversantmedia.mapreduce.tool.RunJob.java

private static String readVersionFromManifest(String version) {
    // Try again to see if this class's MANIFEST was unjar'd by the hadoop command
    // - read it from the unjar'd file instead.
    InputStream in = null;/*  w  w  w  . ja  v  a  2  s. c o  m*/
    try {
        URL manifestUrl = findManifestForDriver();
        if (manifestUrl != null) {
            in = manifestUrl.openStream();
            Manifest manifest = new Manifest(in);
            version = manifest.getMainAttributes().getValue("Implementation-Version");
        }
    } catch (Exception e) {
        // No point in exiting the app because we fail to read version from manifest.
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(in);
    }
    return version;
}

From source file:org.apache.catalina.util.ExtensionValidator.java

/**
 * Runtime validation of a Web Applicaiton.
 *
 * This method uses JNDI to look up the resources located under a 
 * <code>DirContext</code>. It locates Web Application MANIFEST.MF 
 * file in the /META-INF/ directory of the application and all 
 * MANIFEST.MF files in each JAR file located in the WEB-INF/lib 
 * directory and creates an <code>ArrayList</code> of 
 * <code>ManifestResorce<code> objects. These objects are then passed 
 * to the validateManifestResources method for validation.
 *
 * @param dirContext The JNDI root of the Web Application
 * @param context The context from which the Logger and path to the
 *                application//from w w w .jav a2 s  .  c om
 *
 * @return true if all required extensions satisfied
 */
public static synchronized boolean validateApplication(DirContext dirContext, StandardContext context)
        throws IOException {

    String appName = context.getPath();
    ArrayList appManifestResources = new ArrayList();
    ManifestResource appManifestResource = null;
    // If the application context is null it does not exist and 
    // therefore is not valid
    if (dirContext == null)
        return false;
    // Find the Manifest for the Web Applicaiton
    InputStream inputStream = null;
    try {
        NamingEnumeration wne = dirContext.listBindings("/META-INF/");
        Binding binding = (Binding) wne.nextElement();
        if (binding.getName().toUpperCase().equals("MANIFEST.MF")) {
            Resource resource = (Resource) dirContext.lookup("/META-INF/" + binding.getName());
            inputStream = resource.streamContent();
            Manifest manifest = new Manifest(inputStream);
            inputStream.close();
            inputStream = null;
            ManifestResource mre = new ManifestResource(
                    sm.getString("extensionValidator.web-application-manifest"), manifest,
                    ManifestResource.WAR);
            appManifestResources.add(mre);
        }
    } catch (NamingException nex) {
        // Application does not contain a MANIFEST.MF file
    } catch (NoSuchElementException nse) {
        // Application does not contain a MANIFEST.MF file
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }

    // Locate the Manifests for all bundled JARs
    NamingEnumeration ne = null;
    try {
        if (dirContext != null) {
            ne = dirContext.listBindings("WEB-INF/lib/");
        }
        while ((ne != null) && ne.hasMoreElements()) {
            Binding binding = (Binding) ne.nextElement();
            if (!binding.getName().toLowerCase().endsWith(".jar")) {
                continue;
            }
            Resource resource = (Resource) dirContext.lookup("/WEB-INF/lib/" + binding.getName());
            Manifest jmanifest = getManifest(resource.streamContent());
            if (jmanifest != null) {
                ManifestResource mre = new ManifestResource(binding.getName(), jmanifest,
                        ManifestResource.APPLICATION);
                appManifestResources.add(mre);
            }
        }
    } catch (NamingException nex) {
        // Jump out of the check for this application because it 
        // has no resources
    }

    return validateManifestResources(appName, appManifestResources);
}