Example usage for java.util.jar Manifest read

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

Introduction

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

Prototype

public void read(InputStream is) throws IOException 

Source Link

Document

Reads the Manifest from the specified InputStream.

Usage

From source file:com.ikon.util.WarUtils.java

/**
 * // w  ww.j  ava2s.c  o m
 */
public static synchronized void readAppVersion(ServletContext sc) {
    String appServerHome = sc.getRealPath("/");
    File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(manifestFile);
        Manifest mf = new Manifest();
        mf.read(fis);
        Attributes atts = mf.getMainAttributes();
        String impVersion = atts.getValue("Implementation-Version");
        String impBuild = atts.getValue("Implementation-Build");
        log.info("Implementation-Version: " + impVersion);
        log.info("Implementation-Build: " + impBuild);

        if (impVersion != null) {
            String[] version = impVersion.split("\\.");

            if (version.length > 0 && version[0] != null) {
                appVersion.setMajor(version[0]);
            }

            if (version.length > 1 && version[1] != null) {
                appVersion.setMinor(version[1]);
            }

            if (version.length > 2 && version[2] != null && !version[2].equals("")) {
                appVersion.setMaintenance(version[2]);
            }
        }

        if (impBuild != null) {
            appVersion.setBuild(impBuild);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.asual.summer.core.util.ResourceUtils.java

public static String getManifestAttribute(String key) {
    try {//from  www. j ava 2s .  c  o m
        if (!attributes.containsKey(key)) {
            String path = "META-INF/MANIFEST.MF";
            Manifest mf = new Manifest();
            URL resource = RequestUtils.getServletContext().getResource("/" + path);
            if (resource == null) {
                resource = getClasspathResources(path, false).get(0);
            }
            mf.read(new FileInputStream(resource.getFile()));
            attributes.put(key, mf.getMainAttributes().getValue(key));
        }
        return attributes.get(key);
    } catch (Exception e) {
        return "";
    }
}

From source file:de.u808.simpleinquest.web.tags.VersionInfoTag.java

@Override
public void doTag() throws JspException, IOException {
    PageContext pageContext = (PageContext) getJspContext();
    JspWriter out = pageContext.getOut();
    try {/*from   w ww .ja  va 2 s . c o m*/
        String appServerHome = pageContext.getServletContext().getRealPath("/");

        File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");

        Manifest mf = new Manifest();
        mf.read(new FileInputStream(manifestFile));

        Attributes atts = mf.getMainAttributes();

        out.println("<span id=\"version\"> (Revision " + atts.getValue("Implementation-Version") + " Build "
                + atts.getValue("Implementation-Build") + " Built-By " + atts.getValue("Built-By")
                + ")</span>");
    } catch (Exception e) {
        log.error("Tag error", e);
    }
}

From source file:ManifestWriter.java

/** Get the Manifest object that this object created.
  * @return the Manifest that this builder created
  *//*  w ww .j  a v a2  s  . c  om*/
public Manifest getManifest() {
    try {
        Manifest m = new Manifest();
        m.read(getInputStream());
        return m;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.musicrecital.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}//from w  w  w  .  jav  a2  s . c o  m
 */
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);

    // Determine version number for CSS and JS Assets
    String appVersion = null;
    try {
        InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        if (is == null) {
            log.warn("META-INF/MANIFEST.MF not found.");
        } else {
            Manifest mf = new Manifest();
            mf.read(is);
            Attributes atts = mf.getMainAttributes();
            appVersion = atts.getValue("Implementation-Version");
        }
    } catch (IOException e) {
        log.error("I/O Exception reading manifest: " + e.getMessage());
    }

    // If there was a build number defined in the war, then use it for
    // the cache buster. Otherwise, assume we are in development mode
    // and use a random cache buster so developers don't have to clear
    // their browser cache.
    if (appVersion == null || appVersion.contains("SNAPSHOT")) {
        appVersion = "" + new Random().nextInt(100000);
    }

    log.info("Application version set to: " + appVersion);
    context.setAttribute(Constants.ASSETS_VERSION, appVersion);
}

From source file:com.pongasoft.kiwidoc.builder.KiwidocBuilder.java

/**
 * Builds the kiwidoc for the given library
 *
 * @param library (optional, <code>null</code> ok) dependencies
 * @return the model builder//from w w w. j a  va2 s. c  o  m
 * @throws BuilderException when there is a problem indexing
 */
public LibraryModelBuilder buildKiwidoc(Library library) throws IOException, BuilderException {
    Set<BuiltFrom> builtFrom = EnumSet.noneOf(BuiltFrom.class);
    Manifest manifest = null;

    LibraryModelBuilder libFromByteCode = null;

    // if we have the library itself (jar file)
    if (library.classes != null) {
        builtFrom.add(BuiltFrom.BYTECODE);

        // manifest
        FileObject manifestResource = library.classes.resolveFile("META-INF/MANIFEST.MF");
        if (manifestResource.exists()) {
            manifest = new Manifest();
            InputStream is = manifestResource.getContent().getInputStream();
            try {
                manifest.read(new BufferedInputStream(is));
            } finally {
                is.close();
            }
        }

        // byte code
        libFromByteCode = new LibraryModelBuilder(library.libraryVersionResource);
        new ByteCodeParser().parseClasses(libFromByteCode, library.classes);
    }

    LibraryModelBuilder libFromSource = null;
    // if we have the source code
    if (library.sources != null) {
        try {
            libFromSource = new LibraryModelBuilder(library.libraryVersionResource);
            if (libFromByteCode != null)
                libFromSource.setJdkVersion(libFromByteCode.getJdkVersion());
            else
                libFromSource.setJdkVersion(library.jdkVersion);

            int sourceCount = new SourceCodeParser().parseSources(libFromSource, library.sources,
                    library.overviewFilename, library.publicOnly ? library.javadoc : null, library.classpath);

            if (sourceCount == 0) {
                libFromSource = null;
                log.warn("No sources found in " + library.sources);
            } else {
                builtFrom.add(BuiltFrom.SOURCE);
            }
        } catch (IOException e) {
            throw e;
        } catch (Throwable th) {
            throw new BuilderException(th);
        }
    }

    // compute which version to use (source code wins if available)
    LibraryModelBuilder lib = new LibraryModelBuilder(library.libraryVersionResource);

    if (libFromByteCode != null) {
        lib = libFromByteCode;
    }

    if (libFromSource != null) {
        lib = libFromSource;
    }

    log.info("Processed source|bytecode: " + (libFromSource == null ? "N/A" : libFromSource.getClassCount())
            + " | " + (libFromByteCode == null ? "N/A" : libFromByteCode.getClassCount()));

    // TODO MED YP: use byte code for resolving unresolved types during javadoc processing  

    // if we have the original javadoc (used for determining exported classes)
    if (library.javadoc != null) {
        builtFrom.add(BuiltFrom.JAVADOC);

        for (PackageModelBuilder packageModelBuilder : lib.getAllPackages()) {
            for (ClassModelBuilder classModelBuilder : packageModelBuilder.getAllClasses()) {
                String javadocFile = classModelBuilder.getFqcn();
                javadocFile = javadocFile.replace('.', '/');
                javadocFile = javadocFile.replace('$', '.'); // for inner classes
                javadocFile += ".html";

                try {
                    classModelBuilder.setExportedClass(
                            library.javadoc.resolveFile(javadocFile, NameScope.DESCENDENT).exists());
                } catch (FileSystemException e) {
                    log.warn("Error while setting exported class on " + javadocFile + " ["
                            + classModelBuilder.getFqcn() + "]", e);
                }
            }
        }
    }

    // dependencies
    lib.setDependencies(library.dependencies);

    // manifest
    lib.setManifest(manifest);

    // built from
    lib.addBuiltFrom(builtFrom);

    return lib;
}

From source file:org.craftercms.commons.monitoring.VersionMonitor.java

/**
 * Gets the current VersionMonitor base on a Class that will load it's manifest file.
 * @param clazz Class that will load the manifest MF file
 * @return A {@link VersionMonitor} pojo with the information.
 * @throws IOException If Unable to read the Manifest file.
 *///from  w w w.  j  a  v  a 2  s .  com
public static VersionMonitor getVersion(Class clazz) throws IOException {
    Manifest manifest = new Manifest();
    manifest.read(clazz.getResourceAsStream(MANIFEST_PATH));
    return getVersion(manifest);
}

From source file:org.jahia.services.modulemanager.util.ModuleUtils.java

/**
 * Performs the transformation of the capability attributes in the MANIFEST.MF file of the supplied stream.
 *
 * @param sourceStream the source stream for the bundle, which manifest has to be adjusted w.r.t. module dependencies; the stream is
 *            closed after returning from this method
 * @return the transformed stream for the bundle with adjusted manifest
 * @throws IOException in case of I/O errors
 *///w ww .  j  av  a  2s  .  c om
public static InputStream addModuleDependencies(InputStream sourceStream) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try (ZipInputStream zis = new ZipInputStream(sourceStream);
            ZipOutputStream zos = new ZipOutputStream(out);) {
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            zos.putNextEntry(new ZipEntry(zipEntry.getName()));
            if (JarFile.MANIFEST_NAME.equals(zipEntry.getName())) {
                // we read the manifest from the source stream
                Manifest mf = new Manifest();
                mf.read(zis);

                addCapabilities(mf.getMainAttributes());

                // write the manifest entry into the target output stream
                mf.write(zos);
            } else {
                IOUtils.copy(zis, zos);
            }
            zis.closeEntry();
            zipEntry = zis.getNextEntry();
        }
    }

    return new ByteArrayInputStream(out.toByteArray());
}

From source file:org.nuxeo.osgi.application.loader.FrameworkLoader.java

protected static boolean isBundle(File f) {
    Manifest mf;
    try {//from  w w  w  .j a va 2  s . c  o  m
        if (f.isFile()) { // jar file
            JarFile jf = new JarFile(f);
            try {
                mf = jf.getManifest();
            } finally {
                jf.close();
            }
            if (mf == null) {
                return false;
            }
        } else if (f.isDirectory()) { // directory
            f = new File(f, "META-INF/MANIFEST.MF");
            if (!f.isFile()) {
                return false;
            }
            mf = new Manifest();
            FileInputStream input = new FileInputStream(f);
            try {
                mf.read(input);
            } finally {
                input.close();
            }
        } else {
            return false;
        }
    } catch (IOException e) {
        return false;
    }
    return mf.getMainAttributes().containsKey(SYMBOLIC_NAME);
}

From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java

/**
 * //from w  ww . jav a 2  s  . c  om
 * create one default index bean which based one the component zip file directly.
 * 
 * bundleId, version, mvn_uri are required
 */
public ComponentIndexBean create(File componentZipFile) {
    if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory()
            || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) {
        return null;
    }

    String name = null;
    String bundleId = null;
    String bundleVersion = null;
    String mvnUri = null;

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(componentZipFile);

        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            String path = zipEntry.getName();
            if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar
                // if it's bundle, not from other folder, like lib, m2 repository.
                IPath p = new Path(path);
                // must be in plugins
                if (p.segmentCount() > 1
                        && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) {
                    if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) {
                        JarInputStream jarEntryStream = null;
                        try {
                            // must use another stream
                            jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry));
                            // find the bundleId and version
                            Manifest manifest = jarEntryStream.getManifest();
                            if (manifest != null) {
                                bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                            }
                            boolean checkManifest = StringUtils.isBlank(bundleId)
                                    || StringUtils.isBlank(bundleVersion);

                            // find the pom.properties
                            JarEntry jarEntry = null;
                            while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) {
                                final String entryPath = jarEntry.getName();
                                if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) {
                                    manifest = new Manifest();
                                    manifest.read(jarEntryStream);
                                    bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                    bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                                    checkManifest = false;
                                }
                                final Path fullPath = new Path(entryPath);
                                final String fileName = fullPath.lastSegment();

                                /*
                                 * for example,
                                 * META-INF/maven/org.talend.components/components-splunk/pom.properties
                                 */
                                if (fileName.equals("pom.properties") //$NON-NLS-1$
                                        && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$

                                    // FIXME, didn't find one way to read the inner jar
                                    // final InputStream propStream = jarFile.getInputStream(jarEntry);
                                    // if (propStream != null) {
                                    // Properties pomProp = new Properties();
                                    // pomProp.load(propStream);
                                    //
                                    // String version = pomProp.getProperty("version"); //$NON-NLS-1$
                                    // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$
                                    // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$
                                    // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version,
                                    // FileExtensions.ZIP_FILE_SUFFIX, null);
                                    //
                                    // propStream.close();
                                    // }

                                    // FIXME, try the path way
                                    // META-INF/maven/org.talend.components/components-splunk
                                    IPath tmpMavenPath = fullPath.removeLastSegments(1);
                                    String artifactId = tmpMavenPath.lastSegment(); // components-splunk
                                    // META-INF/maven/org.talend.components
                                    tmpMavenPath = tmpMavenPath.removeLastSegments(1);
                                    String groupId = tmpMavenPath.lastSegment(); // org.talend.components

                                    mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion,
                                            FileExtensions.ZIP_EXTENSION, null);

                                } else
                                /*
                                 * /OSGI-INF/installer$$splunk.xml
                                 */
                                if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX)
                                        && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                        && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) {
                                    name = fullPath.removeFileExtension().lastSegment();
                                    name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                            + UpdatesHelper.NEW_COMPONENT_PREFIX.length());
                                }
                            }
                        } catch (IOException e) {
                            //
                        } finally {
                            try {
                                if (jarEntryStream != null) {
                                    jarEntryStream.close();
                                }
                            } catch (IOException e) {
                                //
                            }
                        }

                    }
                }
            }
        }

    } catch (ZipException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } catch (IOException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                //
            }
        }
    }
    // set the required
    if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) {
        final ComponentIndexBean indexBean = new ComponentIndexBean();
        final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri);
        indexBean.setValue(ComponentIndexNames.types,
                PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0)));
        if (set) {
            return indexBean;
        }
    }
    return null;
}