Example usage for java.util.jar JarOutputStream JarOutputStream

List of usage examples for java.util.jar JarOutputStream JarOutputStream

Introduction

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

Prototype

public JarOutputStream(OutputStream out, Manifest man) throws IOException 

Source Link

Document

Creates a new JarOutputStream with the specified Manifest.

Usage

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }/*  ww  w  .  j a  va2s.c o  m*/
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private static List<String> createClasspathJar(File dir, String jarName, List<String> manifestClasspath)
        throws IOException {
    List<String> classpathArgs = new ArrayList<String>();
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(manifestClasspath, ' '));
    File classpathJar = new File(dir, jarName);
    classpathJar.deleteOnExit();//from  w ww . ja v  a 2  s  . c o  m
    try (JarOutputStream stream = new JarOutputStream(new FileOutputStream(classpathJar), manifest)) {
    }
    classpathArgs.add("-classpath");
    classpathArgs.add(classpathJar.getCanonicalPath());
    return classpathArgs;
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void createJar(String jarName, String folderName, String outputPath) throws IOException {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    JarOutputStream target = new JarOutputStream(new FileOutputStream(outputPath + File.separator + jarName),
            manifest);//  w  ww.j av  a2  s.  c o  m
    add(new File(folderName), target);
    target.close();
}

From source file:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java

@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;

    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();//  w  w  w .  java2 s. c  o  m

    OsgiManager osgiManager = ((ManagementContextInternal) mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid",
            new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);

    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);

    String whileList = bundle.getSymbolicName() + ":" + bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);

    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);

    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}

From source file:de.cologneintelligence.fitgoodies.maven.FitIntegrationTestMojo.java

public File writeBootJar(String classpath) throws IOException {
    File bootJar = new File(outputDirectory, "boot.jar");

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, classpath);

    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(bootJar), manifest);
    jarOutputStream.close();//from  w w  w.j a  v  a 2  s  . c  o m

    return bootJar;
}

From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap)
        throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFiles = new ArrayList<>();
    for (JarContents jarContents : sourceFileToJarMap.values()) {
        sourceFiles.addAll(jarContents.sourceFiles);
    }//from w w w.j  av  a2  s.  c om

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString())));

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles);

    boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    if (!compiled) {
        throw new RuntimeException("failed to compile");
    }

    for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");

        JarOutputStream target = new JarOutputStream(
                new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()),
                manifest);
        List<String> classesForJar = new ArrayList<>();
        for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) {
            //split the file on dot to get the filename from FILENAME.java
            String fileName = sourceFile.getName().split("\\.")[0];
            classesForJar.add(fileName);
        }

        File dir = new File(outputDir);
        File[] directoryListing = dir.listFiles();
        for (File compiledClass : directoryListing) {
            String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0];
            if (classesForJar.contains(classFileName)) {
                addFileToJar(compiledClass, target);
            }
        }

        for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) {
            addFileToJar(propertiesFile, target);
        }

        target.close();

    }
    //delete non jar files
    File dir = new File(outputDir);
    File[] directoryListing = dir.listFiles();
    for (File file : directoryListing) {
        String extension = file.getName().split("\\.")[1];
        if (!extension.equals("jar")) {
            file.delete();
        }
    }

    Map<String, String> jarMap = new HashMap<>();
    jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME);
    jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME);
    return jarMap;
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void createJarArchive(File jarFile, File[] listFiles) throws IOException {
    byte b[] = new byte[10240];
    FileOutputStream fout = new FileOutputStream(jarFile);
    JarOutputStream out = new JarOutputStream(fout, new Manifest());
    for (int i = 0; i < listFiles.length; i++) {
        if (listFiles[i] == null || !listFiles[i].exists() || listFiles[i].isDirectory()) {
            System.out.println();
        }/*  www . j ava 2s  .c  om*/
        JarEntry addFiles = new JarEntry(listFiles[i].getName());
        addFiles.setTime(listFiles[i].lastModified());
        out.putNextEntry(addFiles);

        FileInputStream fin = new FileInputStream(listFiles[i]);
        while (true) {
            int len = fin.read(b, 0, b.length);
            if (len <= 0)
                break;
            out.write(b, 0, len);
        }
        fin.close();
    }
    out.close();
    fout.close();
}

From source file:org.reficio.p2.FeatureBuilder.java

public void generateSourceFeature(File destinationFolder) {
    Element featureElement = XmlUtils.fetchOrCreateElement(xmlDoc, xmlDoc, "feature");
    featureElement.setAttribute("id", featureElement.getAttribute("id") + ".source");
    featureElement.setAttribute("label", featureElement.getAttribute("label") + " Developer Resources");
    NodeList nl = featureElement.getElementsByTagName("plugin");
    List<Element> elements = new ArrayList<Element>();
    //can't remove as we iterate over nl, because its size changes when we remove
    for (int n = 0; n < nl.getLength(); ++n) {
        elements.add((Element) nl.item(n));
    }// www  .j  a v a 2s . c o  m
    for (Element e : elements) {
        featureElement.removeChild(e);
    }

    for (P2Artifact artifact : this.p2FeatureDefintion.artifacts) {
        Element pluginElement = XmlUtils.createElement(xmlDoc, featureElement, "plugin");
        String id = this.bundlerInstructions.get(artifact).getSourceSymbolicName();
        String version = this.bundlerInstructions.get(artifact).getProposedVersion();
        pluginElement.setAttribute("id", id);
        pluginElement.setAttribute("download-size", "0"); //TODO
        pluginElement.setAttribute("install-size", "0"); //TODO
        pluginElement.setAttribute("version", version);
        pluginElement.setAttribute("unpack", "false");

    }

    try {
        File sourceFeatureContent = new File(destinationFolder, this.getFeatureFullName() + ".source");
        sourceFeatureContent.mkdir();
        XmlUtils.writeXml(this.xmlDoc, new File(sourceFeatureContent, "feature.xml"));

        //TODO: add other files that are required by the feature

        FileOutputStream fos = new FileOutputStream(
                new File(destinationFolder, this.getFeatureFullName() + ".jar"));
        Manifest mf = new Manifest();
        JarOutputStream jar = new JarOutputStream(fos, mf);
        addToJar(jar, sourceFeatureContent);
    } catch (Exception e) {
        throw new RuntimeException("Cannot generate feature", e);
    }
}

From source file:rubah.tools.UpdateClassGenerator.java

public void generateConversionJar(File outJar) throws IOException {

    FileOutputStream fos = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(fos, new Manifest());

    this.generateConversionClasses(jos, this.v0, this.preffixes.get(this.v1.getNamespace()));
    this.generateConversionClasses(jos, this.v1, "");

    jos.close();//from  w w w .j  av a 2  s .com
    fos.close();
}

From source file:com.buglabs.bug.ws.program.ProgramServlet.java

/**
 * Code from forum board for creating a Jar.
 * /*from  w  ww  .j  ava  2 s  . c o m*/
 * @param archiveFile
 * @param tobeJared
 * @param rootDir
 * @throws IOException
 */
protected void createJarArchive(File archiveFile, File[] tobeJared, File rootDir) throws IOException {

    byte buffer[] = new byte[BUFFER_SIZE];
    // Open archive file
    FileOutputStream stream = new FileOutputStream(archiveFile);
    JarOutputStream out = new JarOutputStream(stream, new Manifest(new FileInputStream(
            rootDir.getAbsolutePath() + File.separator + "META-INF" + File.separator + MANIFEST_FILENAME)));

    for (int i = 0; i < tobeJared.length; i++) {
        if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory())
            continue; // Just in case...

        String relPath = getRelPath(rootDir.getAbsolutePath(), tobeJared[i].getAbsolutePath());

        // Add archive entry
        JarEntry jarAdd = new JarEntry(relPath);
        jarAdd.setTime(tobeJared[i].lastModified());
        out.putNextEntry(jarAdd);
        // Write file to archive
        FileInputStream in = new FileInputStream(tobeJared[i]);
        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();

}