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() 

Source Link

Document

Constructs a new, empty Manifest.

Usage

From source file:rapture.kernel.JarApiImplTest.java

private byte[] createTestJar() {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JarOutputStream target = new JarOutputStream(baos, manifest)) {
        File testJar = new File(TEST_JAR_PATH);
        if (!testJar.exists() || !testJar.canRead()) {
            return null;
        }//ww w  .  j a  v  a2s.  co m
        add(testJar, target);
    } catch (IOException e) {
        log.error(e);
    }
    return baos.toByteArray();
}

From source file:org.xwiki.extension.test.ExtensionPackager.java

public void generateExtension(String classPackageFolder, URL descriptorUrl) throws IOException {
    String descriptorUrlStr = descriptorUrl.toString();
    String descriptorFolderURL = descriptorUrlStr.substring(0,
            descriptorUrlStr.length() - PACKAGEFILE_DESCRIPTOR.length());

    Properties descriptorProperties = new Properties();

    InputStream descriptorStream = descriptorUrl.openStream();
    try {/*  w w  w.  ja  v a2  s .c  o  m*/
        descriptorProperties.load(descriptorStream);
    } finally {
        descriptorStream.close();
    }
    String type = descriptorProperties.getProperty("type");
    if (type == null) {
        type = "zip";
    }
    String id = descriptorProperties.getProperty("id");
    if (id == null) {
        id = descriptorFolderURL.substring(0, descriptorFolderURL.length() - 1);
        id = id.substring(id.lastIndexOf('/') + 1);
    }
    String version = descriptorProperties.getProperty("version");
    if (version == null) {
        version = "1.0";
    }
    File packageFile;
    String directory = descriptorProperties.getProperty("directory");
    String fileName = descriptorProperties.getProperty("fileName");
    String repositoryName = descriptorProperties.getProperty("repository");
    if (directory == null) {
        if (fileName == null) {
            packageFile = new File(this.repositories.get(repositoryName),
                    URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8"));
        } else {
            packageFile = new File(this.repositories.get(repositoryName), fileName);
        }
    } else {
        if (fileName == null) {
            fileName = URLEncoder.encode(id + '-' + version + '.' + type, "UTF-8");
        }

        packageFile = new File(this.workingDirectory, directory);
        packageFile = new File(packageFile, fileName);
    }

    // generate

    // Make sure the folder exists
    packageFile.getParentFile().mkdirs();

    FileOutputStream fos = new FileOutputStream(packageFile);
    try {
        ZipOutputStream zos;
        if (type.equals("jar")) {
            Manifest manifest = new Manifest();
            manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            zos = new JarOutputStream(fos, manifest);
        } else {
            zos = new ZipOutputStream(fos);
        }

        try {
            // Order files
            TreeMap<String, Vfs.File> files = new TreeMap<>();
            for (Vfs.File resourceFile : Vfs.fromURL(new URL(descriptorFolderURL)).getFiles()) {
                files.put(resourceFile.getRelativePath(), resourceFile);
            }

            // Add files to zip
            for (Vfs.File resourceFile : files.values()) {
                if (!resourceFile.getRelativePath().equals(PACKAGEFILE_DESCRIPTOR)) {
                    addZipEntry(classPackageFolder, resourceFile, zos, type);
                }
            }
        } finally {
            zos.close();
        }

        // Register the extension
        this.extensionsFiles.put(new ExtensionId(id, version), packageFile);
    } finally {
        fos.close();
    }
}

From source file:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;//from www. ja v  a2  s  .  c  o m
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:tilda.db.ConnectionPool.java

private static void LoadTildaResources(Connection C, boolean Migrate) throws Exception {
    Reader R = null;//from   w  ww .  j  a va 2  s  .c om
    InputStream In = null;
    Enumeration<URL> resEnum = ConnectionPool.class.getClassLoader().getResources(JarFile.MANIFEST_NAME);
    List<Schema> TildaList = new ArrayList<Schema>();
    while (resEnum.hasMoreElements()) {
        URL url = (URL) resEnum.nextElement();
        In = url.openStream();
        if (In != null) {
            Manifest Man = new Manifest();
            Man.read(In);
            In.close();
            String Tildas = Man.getMainAttributes().getValue("Tilda");
            if (TextUtil.isNullOrEmpty(Tildas) == false) {
                LOG.debug("Found Tilda(s) " + Tildas + " in " + url.toString());
                String[] parts = Tildas.split(";");
                if (parts != null)
                    for (String p : parts) {
                        if (TextUtil.isNullOrEmpty(p) == true)
                            continue;
                        p = p.trim();
                        In = FileUtil.getResourceAsStream(p);
                        if (In == null)
                            throw new Exception(
                                    "Tilda schema definition '" + p + "' could not be found in the classpath.");
                        LOG.info("Inspecting " + p);
                        R = new BufferedReader(new InputStreamReader(In));
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        Schema S = gson.fromJson(R, Schema.class);
                        S.setOrigin(p);
                        TildaList.add(S);
                        In.close();
                    }
            }
        }
    }
    ReorderTildaListWithDependencies(TildaList);
    // LOG.debug("All Tildas in order of dependencies:");
    // for (Schema S : TildaList)
    // LOG.debug(" "+S._ResourceNameShort);
    if (Migrate == false)
        Migrator.logMigrationWarning();
    int warnings = 0;
    for (Schema S : TildaList) {
        int w = Migrator.migrate(C, S, Migrate);
        if (w != 0 && Migrate == false) {
            warnings += w;
            LOG.warn("There were " + w
                    + " warning(s) issued because schema discrepencies were found but not fixed.");
            Migrator.logMigrationWarning();
            continue;
        }
        LOG.debug("Initializing Schema objects");
        Method M = Class.forName(tilda.generation.java8.Helper.getSupportClassFullName(S))
                .getMethod("initSchema", Connection.class);
        M.invoke(null, C);
        _SchemaPackage.put(S._Name, S._Package);
        C.commit();
    }
    LOG.debug("");
    LOG.debug("Creating/updating Tilda helper stored procedures.");
    if (Migrate == false)
        Migrator.logMigrationWarning();
    else if (C.addHelperFunctions() == false)
        throw new Exception("Cannot upgrade schema by adding the Tilda helper functions.");

    if (warnings != 0 && Migrate == false) {
        LOG.warn("");
        LOG.warn("");
        LOG.warn("There were a total of " + warnings
                + " warning(s) issued because schema discrepencies were found but not fixed.");
        Migrator.logMigrationWarning();
    }

    C.commit();
}

From source file:org.apache.hadoop.hbase.util.ClassLoaderTestHelper.java

/**
 * Add a list of jar files to another jar file under a specific folder.
 * It is used to generated coprocessor jar files which can be loaded by
 * the coprocessor class loader.  It is for testing usage only so we
 * don't be so careful about stream closing in case any exception.
 *
 * @param targetJar the target jar file// www .  ja v  a 2  s .  com
 * @param libPrefix the folder where to put inner jar files
 * @param srcJars the source inner jar files to be added
 * @throws Exception if anything doesn't work as expected
 */
public static void addJarFilesToJar(File targetJar, String libPrefix, File... srcJars) throws Exception {
    FileOutputStream stream = new FileOutputStream(targetJar);
    JarOutputStream out = new JarOutputStream(stream, new Manifest());
    byte buffer[] = new byte[BUFFER_SIZE];

    for (File jarFile : srcJars) {
        // Add archive entry
        JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName());
        jarAdd.setTime(jarFile.lastModified());
        out.putNextEntry(jarAdd);

        // Write file to archive
        FileInputStream in = new FileInputStream(jarFile);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }
    out.close();
    stream.close();
    LOG.info("Adding jar file to outer jar file completed");
}

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

private Manifest getManifest(Jar jar) throws Exception {
    Manifest manifest = jar.getManifest();
    if (manifest == null) {
        manifest = new Manifest();
    }// w w w .ja  v a2s.c o  m
    return manifest;
}

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

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from  w  w  w . jav a2s  . c o m
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        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 webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#jenkins.war";
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        configurator.setTargetJenkinsHomeBaseDir("/some/silly/random/homeDir");

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

        // 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 {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:org.stem.ExternalNode.java

private void createNodeJar(File jarFile, String mainClass, File nodeDir) throws IOException {
    File conf = new File(nodeDir, "conf");

    FileOutputStream fos = null;//  w w  w .j  av  a  2 s.c  om
    JarOutputStream jos = null;

    try {
        fos = new FileOutputStream(jarFile);
        jos = new JarOutputStream(fos);
        jos.setLevel(JarOutputStream.STORED);
        jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF"));

        Manifest man = new Manifest();

        StringBuilder cp = new StringBuilder();
        cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        log.debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(mvnContext.pluginArtifact)
                + " to the classpath");
        cp.append(new URL(mvnContext.pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        log.debug("Adding: " + mvnContext.classesDir + " to the classpath");
        cp.append(new URL(mvnContext.classesDir.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        for (Artifact artifact : mvnContext.pluginDependencies) {
            log.info("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
            // NOTE: if File points to a directory, this entry MUST end in '/'.
            cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
            cp.append(' ');
        }

        man.getMainAttributes().putValue("Manifest-Version", "1.0");
        man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
        man.getMainAttributes().putValue("Main-Class", mainClass);

        man.write(jos);

    } finally {
        IOUtil.close(jos);
        IOUtil.close(fos);
    }
}

From source file:org.moe.cli.executor.AbstractLinkExecutor.java

@Override
public void execute() throws IOException, URISyntaxException, InterruptedException, CheckArchitectureException,
        UnsupportedTypeException {//  w w w  .  j  a  v  a 2  s  .c  o  m

    //collect all header files
    List<String> headerList = new ArrayList<String>();
    if (headers != null) {
        for (String header : headers) {
            if (header != null && !header.isEmpty()) {
                File tmp = new File(header);
                if (tmp.isDirectory()) {
                    Collection<File> files = FileUtils.listFiles(tmp, new String[] { "h" }, true);
                    for (File file : files)
                        headerList.add(file.getAbsolutePath());
                } else {
                    headerList.add(header);
                }
            }
        }
    }

    List<String> frameworkList = new ArrayList<String>();
    Set<String> frameworksSearchPaths = new HashSet<String>();
    if (frameworks != null) {

        for (String framework : frameworks) {
            frameworkList.add(framework);
            File frFile = new File(framework);
            frameworksSearchPaths.add(frFile.getParent());
        }

    }

    // Initialize native libraries
    NatJGenNativeLoader.initNatives();

    // Read arguments
    MOEJavaProject project = new MOEJavaProject("", "/");

    boolean generated = true;
    File tmpDir = NatJFileUtils.getNewTempDirectory();
    if (javaSource == null) {

        //generate bindings for all frameworks
        String natJGenBody = NatjGenFrameworkConfig.generate(packageName, frameworksSearchPaths,
                tmpDir.getPath(), headerList);

        //generate bindings
        generated = generate(project, natJGenBody);
    } else {

        Set<URI> links = new HashSet<URI>();
        for (String jsource : javaSource) {
            links.add(new URI(jsource));
        }
        GrabUtils.downloadToFolder(links, tmpDir);
    }

    if (generated) {
        //try to compile generated jars
        File destinationJavacDir = new File(tmpDir, "result");
        destinationJavacDir.mkdir();

        String indePath = System.getenv("MOE_HOME");
        if (indePath != null && !indePath.isEmpty()) {
            String coreJar = indePath + File.separator + "sdk" + File.separator + "moe-core.jar";
            String iosJar = indePath + File.separator + "sdk" + File.separator + "moe-ios.jar";

            String compileList = createCompileFileList(tmpDir, javaSource != null ? null : packageName);

            String classPathArg = String.format("%s:%s", coreJar, iosJar);
            ProcessBuilder processBuilder = new ProcessBuilder("javac", "@" + compileList, "-cp", classPathArg,
                    "-d", destinationJavacDir.getPath());
            Process process = processBuilder.start();
            process.waitFor();

            if (process.exitValue() == 0 || headerList.size() == 0) {
                //try to create lib subdirectory
                File libTemp = new File(destinationJavacDir, "lib");
                if (!(libTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + libTemp.getAbsolutePath());
                }

                //try to create bundle subdirectory
                File bundleTemp = new File(destinationJavacDir, "bundle");
                if (!(bundleTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                copyLibrary(libTemp, frameworkList);

                if (bundle != null) {
                    copyBundle(bundleTemp, bundle);
                }

                Map<String, String> flags = getManifestProperties(frameworkList);

                //create manifest file
                Manifest manifest = new Manifest();
                manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

                //Logic from CocoaPods; for more information visit https://github.com/CocoaPods/CocoaPods/issues/3537
                String moe_type = flags.get(MOE_TYPE);
                if (moe_type != null && moe_type.contains("static")) {
                    if (ldFlags != null && !ldFlags.isEmpty()) {
                        if (ldFlags.endsWith(";"))
                            ldFlags += "-ObjC;";
                        else
                            ldFlags += ";-ObjC;";
                    } else {
                        ldFlags = "-ObjC;";
                    }
                }

                if (ldFlags != null && !ldFlags.isEmpty()) {
                    flags.put("MOE_CUSTOM_LINKER_FLAGS", ldFlags);
                }

                for (Map.Entry<String, String> entry : flags.entrySet()) {
                    manifest.getMainAttributes().put(new Attributes.Name(entry.getKey()), entry.getValue());
                }

                //try to create manifest subdirectory
                File manifestTemp = new File(destinationJavacDir, "META-INF");
                if (!(manifestTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                String manifestFileName = "MANIFEST.MF";
                File manifestFile = new File(manifestTemp, manifestFileName);
                FileOutputStream manOut = new FileOutputStream(manifestFile);
                manifest.write(manOut);
                manOut.close();

                //try to pack custom content into jar
                File jarFile = new File(outFile);

                FileOutputStream jarFos = null;
                JarArchiveOutputStream target = null;
                try {
                    jarFos = new FileOutputStream(jarFile);
                    target = new JarArchiveOutputStream(jarFos);

                    for (File file : destinationJavacDir.listFiles()) {
                        ArchiveUtils.addFileToJar(destinationJavacDir, file, target);
                    }
                    target.close();

                } finally {
                    if (jarFos != null) {
                        jarFos.close();
                    }

                    if (target != null) {
                        target.close();
                    }
                }
            } else {
                throw new IOException("An error occured during process of bindings compilation");
            }
        } else {
            throw new IOException("Could not find system variable - MOE_HOME");
        }
    } else {
        throw new IOException("An error occured during process of bindings generation");
    }

}

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

@Test
public void testUpdateZipfile_warAlreadyExists() throws Exception {

    // First, set up our zipfile test.
    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from   www.  ja v a2  s .  co m
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest());

        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 webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        String expectedDestFile = webappsTarget + "s#test123#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir("/some/silly/random/homeDir");

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

        // 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 {
            // Now, try and create it a second time - this should work, even though the war exists.
            configurator.configure(config);
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}