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:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download./*ww  w.  j  a  va2 s.c o  m*/
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:UnpackedJarFile.java

public Manifest getManifest() throws IOException {
    if (isClosed) {
        throw new IllegalStateException("NestedJarFile is closed");
    }//ww  w  .  j  a v a 2s  .c  om

    if (!manifestLoaded) {
        JarEntry manifestEntry = getBaseEntry("META-INF/MANIFEST.MF");

        if (manifestEntry != null && !manifestEntry.isDirectory()) {
            InputStream in = null;
            try {
                in = baseJar.getInputStream(manifestEntry);
                manifest = new Manifest(in);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }
        manifestLoaded = true;
    }
    return manifest;
}

From source file:org.jvnet.hudson.test.HudsonTestCase.java

/**
 * If this test harness is launched for a Hudson plugin, locate the <tt>target/test-classes/the.hpl</tt>
 * and add a recipe to install that to the new Hudson.
 *
 * <p>//from   ww w . ja v  a 2s . co m
 * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current
 * packaging is <tt>hpi</tt>.
 */
protected void recipeLoadCurrentPlugin() throws Exception {
    Enumeration<URL> e = getClass().getClassLoader().getResources("the.hpl");
    if (!e.hasMoreElements())
        return; // nope

    final URL hpl = e.nextElement();

    if (e.hasMoreElements()) {
        // this happens if one plugin produces a test jar and another plugin depends on it.
        // I can't think of a good way to make this work, so for now, just detect that and report an error.
        URL hpl2 = e.nextElement();
        throw new Error("We have both " + hpl + " and " + hpl2);
    }

    recipes.add(new Runner() {
        @Override
        public void decorateHome(HudsonTestCase testCase, File home) throws Exception {
            // make the plugin itself available
            Manifest m = new Manifest(hpl.openStream());
            String shortName = m.getMainAttributes().getValue("Short-Name");
            if (shortName == null)
                throw new Error(hpl + " doesn't have the Short-Name attribute");
            FileUtils.copyURLToFile(hpl, new File(home, "plugins/" + shortName + ".hpl"));

            // make dependency plugins available
            // TODO: probably better to read POM, but where to read from?
            // TODO: this doesn't handle transitive dependencies

            // Tom: plugins are now searched on the classpath first. They should be available on
            // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository
            // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. 

            String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies");
            if (dependencies != null) {
                MavenEmbedder embedder = new MavenEmbedder(null);
                embedder.setClassLoader(getClass().getClassLoader());
                embedder.start();
                for (String dep : dependencies.split(",")) {
                    String[] tokens = dep.split(":");
                    String artifactId = tokens[0];
                    String version = tokens[1];
                    File dependencyJar = null;
                    // need to search multiple group IDs
                    // TODO: extend manifest to include groupID:artifactID:version
                    Exception resolutionError = null;
                    for (String groupId : new String[] { "org.jvnet.hudson.plugins",
                            "org.jvnet.hudson.main" }) {

                        // first try to find it on the classpath.
                        // this takes advantage of Maven POM located in POM
                        URL dependencyPomResource = getClass()
                                .getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml");
                        if (dependencyPomResource != null) {
                            // found it
                            dependencyJar = Which.jarFile(dependencyPomResource);
                            break;
                        } else {
                            Artifact a;
                            a = embedder.createArtifact(groupId, artifactId, version,
                                    "compile"/*doesn't matter*/, "hpi");
                            try {
                                embedder.resolve(a,
                                        Arrays.asList(embedder.createRepository(
                                                "http://maven.glassfish.org/content/groups/public/", "repo")),
                                        embedder.getLocalRepository());
                                dependencyJar = a.getFile();
                            } catch (AbstractArtifactResolutionException x) {
                                // could be a wrong groupId
                                resolutionError = x;
                            }
                        }
                    }
                    if (dependencyJar == null)
                        throw new Exception("Failed to resolve plugin: " + dep, resolutionError);

                    File dst = new File(home, "plugins/" + artifactId + ".hpi");
                    if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) {
                        FileUtils.copyFile(dependencyJar, dst);
                    }
                }
                embedder.stop();
            }
        }
    });
}

From source file:com.liferay.portal.plugin.PluginPackageUtil.java

private PluginPackage _readPluginPackageServletManifest(ServletContext servletContext) throws IOException {
    Attributes attributes = null;

    String servletContextName = servletContext.getServletContextName();

    InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");

    if (inputStream != null) {
        Manifest manifest = new Manifest(inputStream);

        attributes = manifest.getMainAttributes();
    } else {/*www.  ja  va 2s .c o  m*/
        attributes = new Attributes();
    }

    String artifactGroupId = attributes.getValue("Implementation-Vendor-Id");

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = attributes.getValue("Implementation-Vendor");
    }

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = GetterUtil.getString(attributes.getValue("Bundle-Vendor"), servletContextName);
    }

    String artifactId = attributes.getValue("Implementation-Title");

    if (Validator.isNull(artifactId)) {
        artifactId = GetterUtil.getString(attributes.getValue("Bundle-Name"), servletContextName);
    }

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

    if (Validator.isNull(version)) {
        version = GetterUtil.getString(attributes.getValue("Bundle-Version"), Version.UNKNOWN);
    }

    if (version.equals(Version.UNKNOWN) && _log.isWarnEnabled()) {
        _log.warn("Plugin package on context " + servletContextName
                + " cannot be tracked because this WAR does not contain a "
                + "liferay-plugin-package.xml file");
    }

    PluginPackage pluginPackage = new PluginPackageImpl(artifactGroupId + StringPool.SLASH + artifactId
            + StringPool.SLASH + version + StringPool.SLASH + "war");

    pluginPackage.setName(artifactId);

    String shortDescription = attributes.getValue("Bundle-Description");

    if (Validator.isNotNull(shortDescription)) {
        pluginPackage.setShortDescription(shortDescription);
    }

    String pageURL = attributes.getValue("Bundle-DocURL");

    if (Validator.isNotNull(pageURL)) {
        pluginPackage.setPageURL(pageURL);
    }

    return pluginPackage;
}

From source file:strat.mining.stratum.proxy.configuration.ConfigurationManager.java

/**
 * Return the version of the program// www  . j a  v  a  2  s .  c om
 * 
 * @return
 */
public static String getVersion() {
    if (version == null) {
        version = "Dev";

        Class<Launcher> clazz = Launcher.class;
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        if (classPath.startsWith("jar")) {
            // Class not from JAR
            String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
                    + "/META-INF/MANIFEST.MF";

            try {
                Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                Attributes attr = manifest.getMainAttributes();
                version = attr.getValue("Implementation-Version");
            } catch (IOException e) {
                // Do nothing, just return Unknown as version
                version = "Unknown";
            }
        }
    }

    return version;
}

From source file:org.apache.openejb.config.DeploymentLoader.java

protected ClientModule createClientModule(final URL clientUrl, final String absolutePath,
        final ClassLoader appClassLoader, final String moduleName, final boolean log) throws OpenEJBException {
    final ResourceFinder clientFinder = new ResourceFinder(clientUrl);

    URL manifestUrl = null;/*w ww .  j av a2  s .co  m*/
    try {
        manifestUrl = clientFinder.find("META-INF/MANIFEST.MF");
    } catch (final IOException e) {
        //
    }

    String mainClass = null;
    if (manifestUrl != null) {
        try {
            final InputStream is = IO.read(manifestUrl);
            final Manifest manifest = new Manifest(is);
            mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
        } catch (final IOException e) {
            throw new OpenEJBException("Unable to determine Main-Class defined in META-INF/MANIFEST.MF file",
                    e);
        }
    }

    //        if (mainClass == null) throw new IllegalStateException("No Main-Class defined in META-INF/MANIFEST.MF file");

    final Map<String, URL> descriptors = getDescriptors(clientFinder, log);

    ApplicationClient applicationClient = null;
    final URL clientXmlUrl = descriptors.get("application-client.xml");
    if (clientXmlUrl != null) {
        applicationClient = ReadDescriptors.readApplicationClient(clientXmlUrl);
    }

    final ClientModule clientModule = new ClientModule(applicationClient, appClassLoader, absolutePath,
            mainClass, moduleName);

    clientModule.getAltDDs().putAll(descriptors);
    if (absolutePath != null) {
        clientModule.getWatchedResources().add(absolutePath);
    }
    if (clientXmlUrl != null && "file".equals(clientXmlUrl.getProtocol())) {
        clientModule.getWatchedResources().add(URLs.toFilePath(clientXmlUrl));
    }
    return clientModule;
}

From source file:org.parosproxy.paros.Constant.java

private static Manifest getManifest() {
    String className = Constant.class.getSimpleName() + ".class";
    String classPath = Constant.class.getResource(className).toString();
    if (!classPath.startsWith("jar")) {
        // Class not from JAR
        return null;
    }//from   ww  w .  ja  va2s  . co  m
    String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
    try {
        return new Manifest(new URL(manifestPath).openStream());
    } catch (Exception e) {
        // Ignore
        return null;
    }
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Locates the Main class through {@code META-INF/MANIFEST.MF} and
 * returns it./*  ww w.  j a v  a2s.  c om*/
 *
 * @return
 *      always non-null.
 */
public Class loadMainClass() throws IOException, ClassNotFoundException {
    // determine the Main class name
    Enumeration<URL> res = getResources("META-INF/MANIFEST.MF");
    while (res.hasMoreElements()) {
        URL url = res.nextElement();
        InputStream is = new BufferedInputStream(url.openStream());
        try {
            Manifest mf = new Manifest(is);
            String value = mf.getMainAttributes().getValue("Dalma-Main-Class");
            if (value != null) {
                logger.info("Found Dalma-Main-Class=" + value + " in " + url);
                return loadClass(value);
            }
        } finally {
            is.close();
        }
    }

    // default location
    return loadClass("Main");
}

From source file:io.smartspaces.launcher.bootstrap.SmartSpacesFrameworkBootstrap.java

/**
 * Get the Smart Spaces version from the JAR manifest.
 *
 * @return The smart spaces version/*  w w  w.  j  a va2  s  .c  o m*/
 */
private String getSmartSpacesVersion() {
    // This little lovely line gives us the name of the jar that gave the
    // class
    // we are looking at.
    String classContainer = getClass().getProtectionDomain().getCodeSource().getLocation().toString();

    InputStream in = null;
    try {
        URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
        in = manifestUrl.openStream();
        Manifest manifest = new Manifest(in);
        Attributes attributes = manifest.getMainAttributes();

        return attributes.getValue(MANIFEST_PROPERTY_SMARTSPACES_VERSION);
    } catch (IOException ex) {
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // Don't care
            }
        }
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private List<URL> getManifestClassPathJars(String puName, InputStream manifestStream) {
    List<URL> exportedManifestUrls = new ArrayList<URL>();
    try {//w ww .j  a v a2 s.  co m

        Manifest manifest = new Manifest(manifestStream);

        String manifestClasspathLibs = manifest.getMainAttributes().getValue("Class-Path");
        if (manifestClasspathLibs != null) {
            String[] manifestLibFiles = StringUtils.tokenizeToStringArray(manifestClasspathLibs, " ");
            for (String fileName : manifestLibFiles) {

                try {
                    fileName = PlaceholderReplacer.replacePlaceholders(System.getenv(), fileName);
                } catch (PlaceholderResolutionException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not resolve manifest classpath entry: " + fileName
                                + " of processing unit " + puName, e);
                    }
                    continue;
                }

                URL url = null;
                try {
                    url = new URL(fileName);
                    if (!"file".equals(url.getProtocol())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Only file protocol is supported in urls, found : '" + fileName
                                    + "' in manifest classpath of processing unit " + puName);
                        }
                        continue;
                    }
                } catch (MalformedURLException e) {
                    // moving on, checking if file path has been provided
                }

                File file;
                if (url != null) {
                    try {
                        file = new File(url.toURI());
                    } catch (URISyntaxException e) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Invalid url: " + url + " provided in pu " + puName
                                    + " manifest classpath, ignoring entry", e);
                        }
                        continue;
                    }
                } else {
                    file = new File(fileName);
                }

                if (!file.isAbsolute()) {
                    file = new File(SystemInfo.singleton().getXapHome(), fileName);
                }

                if (!file.isFile()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Did not find manifest classpath entry: " + file.getAbsolutePath()
                                + " for processing unit: " + puName + ", ignoring entry.");
                    }
                    continue;
                }

                if (logger.isDebugEnabled()) {
                    logger.debug("Adding " + file.getAbsolutePath()
                            + " read from MANIFEST.MF to processing unit: " + puName + " classpath");
                }

                URL urlToAdd = file.toURI().toURL();
                exportedManifestUrls.add(urlToAdd);
            }
        }
    } catch (IOException e) {
        if (logger.isWarnEnabled()) {
            logger.warn(failedReadingManifest(puName), e);
        }
    } finally {
        try {
            manifestStream.close();
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed closing manifest input stream.", e);
            }
        }
    }
    return exportedManifestUrls;
}