Example usage for java.util.jar Attributes putValue

List of usage examples for java.util.jar Attributes putValue

Introduction

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

Prototype

public String putValue(String name, String value) 

Source Link

Document

Associates the specified value with the specified attribute name, specified as a String.

Usage

From source file:org.eclipse.ebr.maven.BundleMojo.java

private File generateFinalBundleManifest() throws MojoExecutionException {
    try {/*from   ww w .j  ava  2  s .  c  om*/
        File mfile = new File(outputDirectory, "META-INF/MANIFEST.MF");
        final InputStream is = new FileInputStream(mfile);
        Manifest mf;
        try {
            mf = new Manifest(is);
        } finally {
            is.close();
        }
        final Attributes attributes = mf.getMainAttributes();

        if (attributes.getValue(Name.MANIFEST_VERSION) == null) {
            attributes.put(Name.MANIFEST_VERSION, "1.0");
        }

        // shameless self-promotion
        attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in");

        final String expandedVersion = getExpandedVersion();
        attributes.putValue(BUNDLE_VERSION, expandedVersion);

        mfile = getFinalBundleManifestFile();
        mfile.getParentFile().mkdirs();
        final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile));
        try {
            mf.write(os);
        } finally {
            os.close();
        }

        return mfile;
    } catch (final Exception e) {
        throw new MojoExecutionException("Error generating bundle manifest: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.ebr.maven.BundleMojo.java

private File generateSourceBundleManifest() throws MojoExecutionException {
    try {/*from  ww w  .  ja v  a 2s  . c  om*/
        generateSourceBundleL10nFile();

        final Manifest mf = new Manifest();
        final Attributes attributes = mf.getMainAttributes();

        if (attributes.getValue(Name.MANIFEST_VERSION) == null) {
            attributes.put(Name.MANIFEST_VERSION, "1.0");
        }

        final String expandedVersion = getExpandedVersion();
        attributes.putValue(BUNDLE_VERSION, expandedVersion);
        attributes.putValue(BUNDLE_MANIFESTVERSION, "2");
        attributes.putValue(BUNDLE_SYMBOLICNAME, getSourceBundleSymbolicName());
        attributes.putValue(BUNDLE_NAME, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_NAME);
        attributes.putValue(BUNDLE_VENDOR, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_VENDOR);
        //attributes.putValue(BUNDLE_LOCALIZATION, BUNDLE_LOCALIZATION_DEFAULT_BASENAME);
        attributes.putValue("Eclipse-SourceBundle",
                project.getArtifactId() + ";version=\"" + expandedVersion + "\";roots:=\".\"");
        attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in");

        final File mfile = getSourceBundleManifestFile();
        mfile.getParentFile().mkdirs();
        final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile));
        try {
            mf.write(os);
        } finally {
            os.close();
        }

        return mfile;
    } catch (final Exception e) {
        throw new MojoExecutionException("Error generating source bundle manifest: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.equinox.servletbridge.FrameworkLauncher.java

/**
 * deployExtensionBundle will generate the Servletbridge extensionbundle if it is not already present in the platform's
 * plugin directory. By default it exports "org.eclipse.equinox.servletbridge" and a versioned export of the Servlet API.
 * Additional exports can be added by using the "extendedFrameworkExports" initial-param in the ServletConfig
 */// ww w . ja  v a 2 s  .co  m
private void deployExtensionBundle(File plugins) {
    File extensionBundle = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0.jar"); //$NON-NLS-1$
    File extensionBundleDir = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0"); //$NON-NLS-1$
    if (Boolean.valueOf(config.getInitParameter(CONFIG_OVERRIDE_AND_REPLACE_EXTENSION_BUNDLE)).booleanValue()) {
        extensionBundle.delete();
        deleteDirectory(extensionBundleDir);
    } else if (extensionBundle.exists() || extensionBundleDir.isDirectory())
        return;

    Manifest mf = new Manifest();
    Attributes attribs = mf.getMainAttributes();
    attribs.putValue(MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_MANIFEST_VERSION, "2"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_NAME, "Servletbridge Extension Bundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_SYMBOLIC_NAME, "org.eclipse.equinox.servletbridge.extensionbundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_VERSION, "1.0.0"); //$NON-NLS-1$
    attribs.putValue(FRAGMENT_HOST, "system.bundle; extension:=framework"); //$NON-NLS-1$

    String servletVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //$NON-NLS-1$
    String packageExports = "org.eclipse.equinox.servletbridge; version=1.0" + //$NON-NLS-1$
            ", javax.servlet; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.http; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.resources; version=" + servletVersion; //$NON-NLS-1$

    String extendedExports = config.getInitParameter(CONFIG_EXTENDED_FRAMEWORK_EXPORTS);
    if (extendedExports != null && extendedExports.trim().length() != 0)
        packageExports += ", " + extendedExports; //$NON-NLS-1$

    attribs.putValue(EXPORT_PACKAGE, packageExports);

    try {
        JarOutputStream jos = null;
        try {
            jos = new JarOutputStream(new FileOutputStream(extensionBundle), mf);
            jos.finish();
        } finally {
            if (jos != null)
                jos.close();
        }
    } catch (IOException e) {
        context.log("Error generating extension bundle", e); //$NON-NLS-1$
    }
}

From source file:org.hecl.jarhack.JarHack.java

/**
 * The <code>substHecl</code> method takes the filenames of two
 * .jar's - one as input, the second as output, in addition to the
 * name of the application.  Where it counts, the old name (Hecl,
 * usually) is overridden with the new name, and the new .jar file
 * is written to the specified outfile.  Via the iconname argument
 * it is also possible to specify a new icon file to use.
 *
 * @param infile a <code>FileInputStream</code> value
 * @param outfile a <code>String</code> value
 * @param newname a <code>String</code> value
 * @param iconname a <code>String</code> value
 * @exception IOException if an error occurs
 *//*from   w  w w. j ava2  s.  c o m*/
public static void substHecl(InputStream infile, String outfile, String newname, String iconname,
        String scriptfile) throws IOException {

    JarInputStream jif = new JarInputStream(infile);
    Manifest mf = jif.getManifest();
    Attributes attrs = mf.getMainAttributes();

    Set keys = attrs.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        Object key = it.next();
        Object value = attrs.get(key);
        String keyname = key.toString();

        /* These are the three cases that interest us in
         * particular, where we need to make changes. */
        if (keyname.equals("MIDlet-Name")) {
            attrs.putValue(keyname, newname);
        } else if (keyname.equals("MIDlet-1")) {
            String valuestr = value.toString();
            /* FIXME - the stringsplit method is used for older
             * versions of GCJ.  Once newer versions are common,
             * it can go away.  Or not - it works just fine. */
            String properties[] = stringsplit(valuestr, ", ");
            attrs.putValue(keyname, newname + ", " + properties[1] + ", " + properties[2]);
        } else if (keyname.equals("MicroEdition-Configuration")) {
            cldcversion = value.toString();
        } else if (keyname.equals("MicroEdition-Profile")) {
            midpversion = value.toString();
        } else if (keyname.equals("MIDlet-Jar-URL")) {
            attrs.put(key, newname + ".jar");
        }
    }

    JarOutputStream jof = new JarOutputStream(new FileOutputStream(outfile), mf);

    byte[] buf = new byte[4096];

    /* Go through the various entries. */
    JarEntry entry;
    int read;
    while ((entry = jif.getNextJarEntry()) != null) {

        /* Don't copy the manifest file. */
        if ("META-INF/MANIFEST.MF".equals(entry.getName()))
            continue;

        /* Insert our own icon */
        if (iconname != null && "Hecl.png".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("Hecl.png"));
            FileInputStream inf = new FileInputStream(iconname);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        }
        /* Insert our own copy of the script file. */
        else if ("script.hcl".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("script.hcl"));
            FileInputStream inf = new FileInputStream(scriptfile);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        } else {
            /* Otherwise, just copy the entry. */
            jof.putNextEntry(entry);
            while ((read = jif.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
        }

        jof.closeEntry();
    }

    jof.flush();
    jof.close();
    jif.close();
}

From source file:org.reficio.p2.bundler.impl.AquteBundler.java

private void decorateSourceManifest(Manifest manifest, String name, String refrencedBundleSymbolicName,
        String symbolicName, String version) {
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue(Analyzer.BUNDLE_SYMBOLICNAME, symbolicName);
    attributes.putValue(ECLIPSE_SOURCE_BUNDLE,
            refrencedBundleSymbolicName + ";version=\"" + version + "\";roots:=\".\"");
    attributes.putValue(Analyzer.BUNDLE_VERSION, version);
    attributes.putValue(Analyzer.BUNDLE_LOCALIZATION, "plugin");
    attributes.putValue(MANIFEST_VERSION, "1.0");
    attributes.putValue(Analyzer.BUNDLE_MANIFESTVERSION, "2");
    attributes.putValue(Analyzer.BUNDLE_NAME, name);
    attributes.putValue(IMPLEMENTATION_TITLE, name);
    attributes.putValue(SPECIFICATION_TITLE, name);
    attributes.putValue(AquteHelper.TOOL_KEY, AquteHelper.TOOL);
}

From source file:org.reficio.p2.utils.JarUtils.java

public static void adjustSnapshotOutputVersion(File inputFile, File outputFile, String version) {
    Jar jar = null;//from   www. jav  a  2  s .c  o m
    try {
        jar = new Jar(inputFile);
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        attributes.putValue(Analyzer.BUNDLE_VERSION, version);
        jar.write(outputFile);
    } catch (IOException e) {
        throw new RuntimeException("Cannot open jar " + outputFile);
    } catch (Exception e) {
        throw new RuntimeException("Cannot open jar " + outputFile);
    } finally {
        if (jar != null) {
            jar.close();
        }
    }
}

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

/**
 * Write the SHA256 to the manifest using the RHQ-Sha256 attribute tag.
 *
 * @param deploymentFolder app deployment folder
 * @param sha SHA256/*from   w w  w. java 2s.  c o  m*/
 * @throws IOException
 */
private void writeSHAToManifest(File deploymentFolder, String sha) throws IOException {
    File manifestFile = new File(deploymentFolder, MANIFEST_RELATIVE_PATH);
    Manifest manifest;
    if (manifestFile.exists()) {
        FileInputStream inputStream = new FileInputStream(manifestFile);
        try {
            manifest = new Manifest(inputStream);
        } finally {
            inputStream.close();
        }
    } else {
        manifest = new Manifest();
        manifestFile.getParentFile().mkdirs();
        manifestFile.createNewFile();
    }

    Attributes attribs = manifest.getMainAttributes();

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

    attribs.putValue(RHQ_SHA_256, sha);

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

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

public void deploy(CreateResourceReport createResourceReport, ResourceType resourceType) {
    createResourceReport.setStatus(null);
    File archiveFile = null;/*w  w  w  .  j  a v  a2  s . co  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:org.wso2.carbon.server.extensions.FragmentBundleCreator.java

public void perform() {
    File[] files = getBundleConfigs();
    if (files.length > 0) {
        for (File file : files) {
            String fragmentHostBundleName = getFragmentHostBundleName(file);
            String fragmentBundleName = getFragmentBundleName(file);

            try {
                Manifest mf = new Manifest();
                Attributes attribs = mf.getMainAttributes();
                attribs.putValue(LauncherConstants.MANIFEST_VERSION, "1.0");
                attribs.putValue(LauncherConstants.BUNDLE_MANIFEST_VERSION, "2");
                attribs.putValue(LauncherConstants.BUNDLE_NAME, fragmentBundleName);
                attribs.putValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME, fragmentBundleName);
                attribs.putValue(LauncherConstants.BUNDLE_VERSION, FRAGMENT_BUNDLE_VERSION);
                attribs.putValue(LauncherConstants.FRAGMENT_HOST, fragmentHostBundleName);
                attribs.putValue(LauncherConstants.BUNDLE_CLASSPATH, ".");

                File dropinsFolder = new File(Utils.getCarbonComponentRepo(), "dropins");
                String targetFilePath = dropinsFolder.getAbsolutePath() + File.separator + fragmentBundleName
                        + "_" + FRAGMENT_BUNDLE_VERSION + ".jar";

                String tempDirPath = Utils.JAR_TO_BUNDLE_DIR + File.separator + System.currentTimeMillis()
                        + Math.random();

                FileOutputStream mfos = null;
                try {
                    if (file.isDirectory()) {
                        FileUtils.copyDirectory(file, new File(tempDirPath));
                    } else { // is a single file..
                        Utils.copyFileToDir(file, new File(tempDirPath));
                    }//  w  w w  .j  av a2s.c  om
                    String metaInfPath = tempDirPath + File.separator + "META-INF";
                    if (!new File(metaInfPath).mkdirs()) {
                        throw new IOException("Failed to create the directory: " + metaInfPath);
                    }
                    mfos = new FileOutputStream(metaInfPath + File.separator + "MANIFEST.MF");
                    mf.write(mfos);

                    Utils.archiveDir(targetFilePath, tempDirPath);
                    Utils.deleteDir(new File(tempDirPath));
                } finally {
                    try {
                        if (mfos != null) {
                            mfos.close();
                        }
                    } catch (IOException e) {
                        log.error("Unable to close the OutputStream " + e.getMessage(), e);
                    }
                }
            } catch (IOException e) {
                log.error("Error occured while creating the log4j prop fragment bundle.", e);
            }
        }
    }
}

From source file:org.wso2.carbon.server.extensions.Log4jPropFileFragmentBundleCreator.java

public void perform() {

    //Get the log4j.properties file path.
    //Calculate the target fragment bundle file name with required manifest headers.
    //org.wso2.carbon.logging.propfile_1.0.0.jar

    try {//from  w  w w.  j  a va 2s . c  o  m

        Manifest mf = new Manifest();
        Attributes attribs = mf.getMainAttributes();
        attribs.putValue(LauncherConstants.MANIFEST_VERSION, "1.0");
        attribs.putValue(LauncherConstants.BUNDLE_MANIFEST_VERSION, "2");
        attribs.putValue(LauncherConstants.BUNDLE_NAME, FRAGMENT_BUNDLE_NAME);
        attribs.putValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME, FRAGMENT_BUNDLE_NAME);
        attribs.putValue(LauncherConstants.BUNDLE_VERSION, FRAGMENT_BUNDLE_VERSION);
        attribs.putValue(LauncherConstants.FRAGMENT_HOST, FRAGMENT_HOST_BUNDLE_NAME);
        attribs.putValue(LauncherConstants.BUNDLE_CLASSPATH, ".");

        File confFolder = new File(Utils.getCarbonComponentRepo(), "../conf");
        String loggingPropFilePath = confFolder.getAbsolutePath() + File.separator + LOG4J_PROP_FILE_NAME;

        File dropinsFolder = new File(Utils.getCarbonComponentRepo(), "dropins");
        String targetFilePath = dropinsFolder.getAbsolutePath() + File.separator + FRAGMENT_BUNDLE_NAME + "_"
                + FRAGMENT_BUNDLE_VERSION + ".jar";

        String tempDirPath = Utils.JAR_TO_BUNDLE_DIR + File.separator + System.currentTimeMillis()
                + Math.random();

        FileOutputStream mfos = null;
        try {

            Utils.copyFileToDir(new File(loggingPropFilePath), new File(tempDirPath));
            String metaInfPath = tempDirPath + File.separator + "META-INF";
            if (!new File(metaInfPath).mkdirs()) {
                throw new IOException("Failed to create the directory: " + metaInfPath);
            }
            mfos = new FileOutputStream(metaInfPath + File.separator + "MANIFEST.MF");
            mf.write(mfos);

            Utils.archiveDir(targetFilePath, tempDirPath);
            Utils.deleteDir(new File(tempDirPath));
        } finally {
            try {
                if (mfos != null) {
                    mfos.close();
                }
            } catch (IOException e) {
                log.error("Unable to close the OutputStream " + e.getMessage(), e);
            }
        }

    } catch (IOException e) {
        log.error("Error occured while creating the log4j prop fragment bundle.", e);
    }

    //Utils.createBundle(log4jPropFile, targetFragmentBundle, mf);
    //To change body of implemented methods use File | Settings | File Templates.
}