Example usage for java.util.jar JarFile getManifest

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

Introduction

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

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

From source file:org.eu.gasp.core.internal.DefaultPluginRegistry.java

private void registerPlugin(File file) throws Exception {
    if (isFileRegistered(file)) {
        return;//w w  w  .ja va 2 s.c o m
    }

    final JarFile jarFile = new JarFile(file);
    final Manifest manifest = jarFile.getManifest();

    String pluginId = null;
    String pluginClassName = null;
    Version version = null;
    final List<DefaultPluginDependency> pluginDependencies = new ArrayList<DefaultPluginDependency>();
    final List<String> services = new ArrayList<String>();

    final Attributes attrs = manifest.getMainAttributes();
    for (final Map.Entry entry : attrs.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = StringUtils.trimToNull(entry.getValue().toString());

        if (value == null) {
            continue;
        }

        if (JAR_PLUGIN.equals(key)) {
            pluginId = value;
        } else if (JAR_PLUGIN_CLASS.equals(key)) {
            pluginClassName = value;
        } else if (JAR_PLUGIN_VERSION.equals(key)) {
            version = new Version(value);
        } else if (JAR_PLUGIN_PROVIDES.equals(key)) {
            for (final String service : value.split(",")) {
                services.add(service);
            }
        } else if (JAR_PLUGIN_REQUIRES.equals(key)) {
            for (final String versionnedRequiredPluginId : value.split(",")) {
                pluginDependencies.add(new DefaultPluginDependency(versionnedRequiredPluginId, null));
            }
        }
    }

    if (StringUtils.isBlank(pluginId)) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN + " attribute in manifest");
    }
    if (version == null) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN_VERSION + " attribute in manifest");
    }

    final PluginDescriptor pluginDescriptor = new DefaultPluginDescriptor(pluginId, version, pluginClassName,
            pluginDependencies, services);
    if (!plugins.containsKey(pluginDescriptor)) {
        log.info("Registering plugin: " + pluginDescriptor);
        plugins.put(pluginDescriptor, new PluginData(file));
    }
}

From source file:org.openanzo.client.cli.AnzoConsole.java

AnzoConsole() {
    try {/*from ww w.  j  a  v  a  2 s  . co  m*/
        dcw = CommandLineInterface.DEFAULT_CONSOLE;
        if (dcw.cr != null) {
            dcw.cr.setBellEnabled(true);
            dcw.cr.setPrompt("Anzo>");
            dcw.cr.setHistoryEnabled(true);
        }
        dcw.writeOutput(
                "Anzo Command Line Client. \nCopyright (c) 2009 Cambridge Semantics Inc and others. All rights reserved.");
        String version = null;
        if (CommandLineInterface.class.getProtectionDomain() != null
                && CommandLineInterface.class.getProtectionDomain().getCodeSource() != null
                && CommandLineInterface.class.getProtectionDomain().getCodeSource().getLocation() != null) {
            ProtectionDomain domain = CommandLineInterface.class.getProtectionDomain();
            CodeSource source = domain.getCodeSource();
            URL location = source.getLocation();
            if (location != null) {
                File file = new File(location.toURI());
                if (file.exists() && file.getName().toLowerCase().endsWith(".jar")) {
                    JarFile jar = new JarFile(file);
                    version = jar.getManifest().getMainAttributes().getValue("Bundle-Version");
                    if (version == null) {
                        version = jar.getManifest().getMainAttributes().getValue("Implementation-Build");
                    }
                }
            }
        }
        if (version == null) {
            version = CommandLineInterface.class.getPackage().getImplementationVersion();
        }
        dcw.writeOutput("Version: " + ((version == null) ? "Unknown" : version));
        dcw.writeOutput("Type help for usage");

        HashMap<String, Completer> completers = new HashMap<String, Completer>();
        completers.put("exit", new NullCompleter());
        completers.put("quit", new NullCompleter());
        completers.put("connect", new NullCompleter());
        completers.put("disconnect", new NullCompleter());
        completers.put("trace", new StringsCompleter("on", "off"));
        Options global = CommandLineInterface.getGlobalOptions();
        for (SubCommand sc : CommandLineInterface.subcommands) {
            String command = sc.getName();
            ArrayList<String> subcommands = new ArrayList<String>();
            for (Object o : sc.getOptions().getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            for (Object o : global.getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            completers.put(command, new StringsCompleter(subcommands));
        }
        if (dcw.cr != null) {
            dcw.cr.addCompleter(new CLICompleter(completers));
        }
        boolean showStackTrace = false;
        while (true) {
            String command = dcw.readLine("Anzo>");
            if (command != null) {
                if (EXIT.toLowerCase().equals(command.trim().toLowerCase())
                        || QUIT.toLowerCase().equals(command.trim().toLowerCase())) {
                    if (context != null && context.client != null && context.client.isConnected()) {
                        context.client.disconnect();
                        context.client.close();
                        dcw.writeOutput("Disonnected from:" + context.host);
                    }
                    System.exit(0);
                }
                String arguments[] = stringToArgs(command);
                try {
                    if (arguments.length > 0) {
                        String subcommand = arguments[0];
                        if ("connect".equals(subcommand.toLowerCase())) {
                            Options options = new Options();
                            CommandLineInterface.appendGlobalOptions(options);
                            CommandLineParser parser = new PosixParser();
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            CommandLine cl = parser.parse(options, subcommandArgs);
                            if (context == null) {
                                context = CommandLineInterface.createContext(dcw, cl, options, arguments);
                            }
                            if (!context.client.isConnected()) {
                                context.client.connect();
                                dcw.writeOutput("Connected to:" + context.host);
                            }
                        } else if ("disconnect".equals(subcommand.toLowerCase())) {
                            if (context != null && context.client != null && context.client.isConnected()) {
                                context.client.disconnect();
                                context.client.close();
                                dcw.writeOutput("Disonnected from:" + context.host);
                            } else {
                                dcw.writeOutput("Not connected to:" + context.host);
                            }
                            context = null;
                        } else if ("trace".equals(subcommand.toLowerCase())) {
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            if (subcommandArgs.length == 0) {
                                dcw.writeOutput("Show Stack Trace:" + showStackTrace);
                            } else {
                                String flag = subcommandArgs[0];
                                if (flag.equals("on"))
                                    showStackTrace = true;
                                else if (flag.equals("off"))
                                    showStackTrace = false;
                                else
                                    showStackTrace = Boolean.parseBoolean(flag);
                            }
                            if (context != null) {
                                context.showTrace = showStackTrace;
                            }
                        } else if ("version".equals(subcommand.toLowerCase())) {
                            String header = CommandLineInterface.generateVersionHeader();
                            dcw.writeOutput(header);

                        } else {
                            CommandLineInterface.processCommand(context, false, arguments);
                        }
                    }
                } catch (AnzoException e) {
                    if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) {
                        dcw.writeError("Connection failed.");
                        if (showStackTrace)
                            dcw.printException(e, showStackTrace);
                    } else {
                        dcw.printException(e, showStackTrace);
                    }
                } catch (AnzoRuntimeException e) {
                    dcw.printException(e, showStackTrace);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:org.red5.server.plugin.PluginLauncher.java

public void afterPropertiesSet() throws Exception {

    ApplicationContext common = (ApplicationContext) applicationContext.getBean("red5.common");
    Server server = (Server) common.getBean("red5.server");

    //server should be up and running at this point so load any plug-ins now         

    //get the plugins dir
    File pluginsDir = new File(System.getProperty("red5.root"), "plugins");

    File[] plugins = pluginsDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            //lower the case
            String tmp = name.toLowerCase();
            //accept jars and zips
            return tmp.endsWith(".jar") || tmp.endsWith(".zip");
        }/*from  ww  w  . j  av  a  2s . c  o  m*/
    });

    if (plugins != null) {

        IRed5Plugin red5Plugin = null;

        log.debug("{} plugins to launch", plugins.length);
        for (File plugin : plugins) {
            JarFile jar = null;
            Manifest manifest = null;
            try {
                jar = new JarFile(plugin, false);
                manifest = jar.getManifest();
            } catch (Exception e1) {
                log.warn("Error loading plugin manifest: {}", plugin);
            } finally {
                jar.close();
            }
            if (manifest == null) {
                continue;
            }
            Attributes attributes = manifest.getMainAttributes();
            if (attributes == null) {
                continue;
            }
            String pluginMainClass = attributes.getValue("Red5-Plugin-Main-Class");
            if (pluginMainClass == null || pluginMainClass.length() <= 0) {
                continue;
            }
            // attempt to load the class; since it's in the plugins directory this should work
            ClassLoader loader = common.getClassLoader();
            Class<?> pluginClass;
            String pluginMainMethod = null;
            try {
                pluginClass = Class.forName(pluginMainClass, true, loader);
            } catch (ClassNotFoundException e) {
                continue;
            }
            try {
                //handle plug-ins without "main" methods
                pluginMainMethod = attributes.getValue("Red5-Plugin-Main-Method");
                if (pluginMainMethod == null || pluginMainMethod.length() <= 0) {
                    //just get an instance of the class
                    red5Plugin = (IRed5Plugin) pluginClass.newInstance();
                } else {
                    Method method = pluginClass.getMethod(pluginMainMethod, (Class<?>[]) null);
                    Object o = method.invoke(null, (Object[]) null);
                    if (o != null && o instanceof IRed5Plugin) {
                        red5Plugin = (IRed5Plugin) o;
                    }
                }
                //register and start
                if (red5Plugin != null) {
                    //set top-level context
                    red5Plugin.setApplicationContext(applicationContext);
                    //set server reference
                    red5Plugin.setServer(server);
                    //register the plug-in to make it available for lookups
                    PluginRegistry.register(red5Plugin);
                    //start the plugin
                    red5Plugin.doStart();
                }
                log.info("Loaded plugin: {}", pluginMainClass);
            } catch (Throwable t) {
                log.warn("Error loading plugin: {}; Method: {}", pluginMainClass, pluginMainMethod);
                log.error("", t);
            }
        }
    } else {
        log.info("Plugins directory cannot be accessed or doesnt exist");
    }

}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/*from w  ww.  jav  a  2  s . c o  m*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#jenkins.war";
        configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir);
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/*from   w  ww. j  ava2 s .  co m*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

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

private void setClassPath4TISJob(File entity, JobInfo jobInfo) {
    String newClassPath = ""; //$NON-NLS-1$
    String separator = System.getProperty("path.separator"); //$NON-NLS-1$
    List<File> checkList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, entity, "classpath.jar", checkList); //$NON-NLS-1$
    if (checkList.size() > 0) {
        try {/*ww  w .  j a v  a 2 s.c  om*/
            String basePath = checkList.get(0).getParent();
            JarFile jarFile = new JarFile(checkList.get(0).getAbsolutePath());
            Manifest jarFileManifest = jarFile.getManifest();
            String cxt = jarFileManifest.getMainAttributes().getValue("activeContext"); //$NON-NLS-1$
            jobInfo.setContextStr(cxt);
            String classPaths = jarFileManifest.getMainAttributes().getValue("Class-Path"); //$NON-NLS-1$
            String[] classPathsArray = classPaths.split("\\s+", 0); //$NON-NLS-1$
            List<String> classPathsArrayList = new ArrayList<String>(Arrays.asList(classPathsArray));
            List<String> classPathsExtArray = new ArrayList<String>();
            if (!classPathsArrayList.contains(".")) { //$NON-NLS-1$
                classPathsExtArray.add("."); //$NON-NLS-1$
            }
            if (classPathsArrayList.size() > 0) {
                classPathsExtArray.addAll(classPathsArrayList);
            }
            for (String classPath : classPathsExtArray) {
                File libFile = new File(basePath + File.separator + classPath);
                if (libFile.exists()) {
                    if (newClassPath.length() == 0) {
                        newClassPath += libFile.getAbsolutePath();
                    } else if (newClassPath.length() > 0) {
                        newClassPath += separator + libFile.getAbsolutePath();
                    }
                }
            }
        } catch (IOException e) {
            throw new JoboxException(e);
        }
    }
    jobInfo.setClasspath(newClassPath);
}

From source file:org.apache.servicemix.jbi.deployer.handler.JBIDeploymentListener.java

/**
 * Check if the file is a recognized JBI artifact that needs to be
 * processed./*ww  w.j av  a  2s. c o m*/
 *
 * @param artifact the file to check
 * @return <code>true</code> is the file is a JBI artifact that
 *         should be transformed into an OSGi bundle.
 */
public boolean canHandle(File artifact) {
    try {
        // Accept jars and zips
        if (!artifact.getName().endsWith(".zip") && !artifact.getName().endsWith(".jar")) {
            return false;
        }
        JarFile jar = new JarFile(artifact);
        JarEntry entry = jar.getJarEntry(DescriptorFactory.DESCRIPTOR_FILE);
        // Only handle JBI artifacts
        if (entry == null) {
            return false;
        }
        // Only handle non OSGi bundles
        Manifest m = jar.getManifest();
        if (m != null && m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
                && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.jahia.data.templates.ModulesPackage.java

private ModulesPackage(JarFile jarFile) throws IOException {
    modules = new LinkedHashMap<String, PackagedModule>();
    Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
    version = new Version(manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_VERSION));
    name = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME);
    description = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_DESCRIPTION);
    // read jars/*w  w  w  .j  a v  a2  s  .co m*/
    Enumeration<JarEntry> jars = jarFile.entries();

    while (jars.hasMoreElements()) {
        JarEntry jar = jars.nextElement();
        JarFile moduleJarFile = null;
        OutputStream output = null;
        if (StringUtils.endsWith(jar.getName(), ".jar")) {
            try {
                InputStream input = jarFile.getInputStream(jar);
                File moduleFile = File.createTempFile(jar.getName(), "");
                output = new FileOutputStream(moduleFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = input.read(bytes)) != -1) {
                    output.write(bytes, 0, read);
                }
                moduleJarFile = new JarFile(moduleFile);
                Attributes moduleManifestAttributes = moduleJarFile.getManifest().getMainAttributes();
                String bundleName = moduleManifestAttributes.getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
                String jahiaGroupId = moduleManifestAttributes.getValue(Constants.ATTR_NAME_GROUP_ID);
                if (bundleName == null || jahiaGroupId == null) {
                    throw new IOException(
                            "Jar file " + jar.getName() + " in package does not seems to be a DX bundle.");
                }
                modules.put(bundleName, new PackagedModule(bundleName, moduleManifestAttributes, moduleFile));
            } finally {
                IOUtils.closeQuietly(output);
                if (moduleJarFile != null) {
                    moduleJarFile.close();
                }
            }
        }
    }

    // we finally sort modules based on dependencies
    try {
        sortByDependencies(modules);
    } catch (CycleDetectedException e) {
        throw new JahiaRuntimeException("A cyclic dependency detected in the modules of the supplied package",
                e);
    }
}

From source file:org.commonjava.web.test.fixture.JarKnockouts.java

public void rewriteJar(final File source, final File targetDir) throws IOException {
    targetDir.mkdirs();//from   w ww . j  av  a  2s .  c o  m
    final File target = new File(targetDir, source.getName());

    JarFile in = null;
    JarOutputStream out = null;
    try {
        in = new JarFile(source);

        final BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
        out = new JarOutputStream(fos, in.getManifest());

        final Enumeration<JarEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!knockout(entry.getName())) {
                final InputStream stream = in.getInputStream(entry);
                out.putNextEntry(entry);
                copy(stream, out);
                out.closeEntry();
            }
        }
    } finally {
        closeQuietly(out);
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java

/**
 * Change the version in jar//w w  w. j  a  v a  2 s  . c om
 * 
 * @param newVersion
 * @param file
 * @return
 * @throws MojoExecutionException
 */
protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException {
    String fileName = file.getName();
    int pos = fileName.indexOf(oldVersion);
    fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length());

    JarInputStream jis = null;
    JarOutputStream jos;
    OutputStream out = null;
    JarFile sourceJar = null;
    try {
        // now create a temporary file and update the version
        sourceJar = new JarFile(file);
        final Manifest manifest = sourceJar.getManifest();
        manifest.getMainAttributes().putValue("Bundle-Version", newVersion);

        jis = new JarInputStream(new FileInputStream(file));
        final File destJar = new File(file.getParentFile(), fileName);
        out = new FileOutputStream(destJar);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                IOUtils.copy(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();
        return destJar;
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to update version in jar file.", ioe);
    } finally {
        if (sourceJar != null) {
            try {
                sourceJar.close();
            } catch (IOException ex) {
                // close
            }
        }
        IOUtils.closeQuietly(jis);
        IOUtils.closeQuietly(out);
    }

}