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) throws IOException 

Source Link

Document

Creates a new JarOutputStream with no manifest.

Usage

From source file:net.ftb.util.FileUtils.java

/**
 * deletes the META-INF/*  w  w  w.ja v  a2s. c o m*/
 */
public static void killMetaInf() {
    File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir()
            + "/minecraft/bin", "minecraft.jar");
    File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/"
            + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp");
    try {
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        if (!inputFile.delete()) {
            Logger.logError("Failed to delete Minecraft.jar.");
            return;
        }
        outputTmpFile.renameTo(inputFile);
    } catch (FileNotFoundException e) {
        Logger.logError("Error while killing META-INF", e);
    } catch (IOException e) {
        Logger.logError("Error while killing META-INF", e);
    }
}

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private byte[] makeJar(VirtualFile[] files) throws IOException {
    JarOutputStream jarOS = null;
    ByteArrayOutputStream byteOS = null;
    try {// www.ja va2s.  c  o m
        progressIndicator.setIndeterminate(true);

        // build list of files to process
        Collection<VirtualFile> filesToProcess = new LinkedHashSet<VirtualFile>();
        for (VirtualFile virtualFile : files) {
            filesToProcess.addAll(getFileList(virtualFile));
        }

        progressIndicator.setIndeterminate(false);
        progressIndicator.setFraction(0.0D);

        totalCount = filesToProcess.size();

        byteOS = new ByteArrayOutputStream();
        jarOS = new JarOutputStream(byteOS);
        int counter = 0;
        for (VirtualFile file : filesToProcess) {
            if (progressIndicator.isCanceled()) {
                break;
            }

            counter++;
            progressIndicator.setFraction((double) counter / (double) totalCount * 0.5D);
            progressIndicator.setText("Adding " + file.getName() + " ...");

            if (canImport(file)) {
                LOGGER.info("Adding file " + (counter + 1) + "/" + totalCount);
                addToJar(jarOS, file);
            } else {
                skippedCount++;
            }
        }
        jarOS.flush();
        return progressIndicator.isCanceled() ? null : byteOS.toByteArray();
    } finally {
        Closeables.close(jarOS, true);
        Closeables.close(byteOS, true);
    }
}

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;/*from  ww  w  . j  av  a  2s  .  c  o  m*/
    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:au.com.addstar.objects.Plugin.java

/**
 * Adds the Spigot.ver file to the jar//  w  w w. j a v a2  s . com
 *
 * @param ver
 */
public void addSpigotVer(String ver) {
    if (latestFile == null)
        return;
    File newFile = new File(latestFile.getParentFile(),
            SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar");
    File spigotFile = new File(latestFile.getParentFile(), "spigot.ver");
    if (spigotFile.exists())
        FileUtils.deleteQuietly(spigotFile);
    try {
        JarFile oldjar = new JarFile(latestFile);
        if (oldjar.getEntry("spigot.ver") != null)
            return;
        JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile));
        try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) {
            writer.write(ver);
            writer.newLine();
        }
        try (FileInputStream stream = new FileInputStream(spigotFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            JarEntry je = new JarEntry(spigotFile.getName());
            tempJarOutputStream.putNextEntry(je);
            while ((bytesRead = stream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            stream.close();
        }
        Enumeration jarEntries = oldjar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntries.nextElement();
            InputStream entryInputStream = oldjar.getInputStream(entry);
            tempJarOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            entryInputStream.close();
        }
        tempJarOutputStream.close();
        oldjar.close();
        FileUtils.deleteQuietly(latestFile);
        FileUtils.deleteQuietly(spigotFile);
        FileUtils.moveFile(newFile, latestFile);
        latestFile = newFile;

    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.filecache.TestMRWithDistributedCache.java

private Path makeJar(Path p, int index) throws FileNotFoundException, IOException {
    FileOutputStream fos = new FileOutputStream(new File(p.toString()));
    JarOutputStream jos = new JarOutputStream(fos);
    ZipEntry ze = new ZipEntry("distributed.jar.inside" + index);
    jos.putNextEntry(ze);//from   w w  w .  j  a  va  2s  .  c  om
    jos.write(("inside the jar!" + index).getBytes());
    jos.closeEntry();
    jos.close();
    return p;
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Test
public void testBuild() throws ProcessException, IOException, ParserConfigurationException, SAXException {
    FileUtils.write(mProject.getBuildFile(),
            "" + "apply from: \"../commonHeader.gradle\"\n" + "buildscript {\n "
                    + "  apply from: \"../commonBuildScript.gradle\"\n" + "}\n" + "\n"
                    + "apply plugin: 'base'\n" + "apply plugin: 'com.android.external.build'\n" + "\n"
                    + "externalBuild {\n" + "  executionRoot = $/" + mProject.getTestDir().getAbsolutePath()
                    + "/$\n" + "  buildManifestPath = $/" + manifestFile.getAbsolutePath() + "/$\n" + "}\n");

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("clean", "process");

    InstantRunBuildContext instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(1);
    assertThat(instantRunBuildContext.getLastBuild()).isNotNull();
    assertThat(instantRunBuildContext.getLastBuild().getArtifacts()).hasSize(1);
    InstantRunBuildContext.Build fullBuild = instantRunBuildContext.getLastBuild();
    assertThat(fullBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.INITIAL_BUILD);
    assertThat(fullBuild.getArtifacts()).hasSize(1);
    InstantRunBuildContext.Artifact artifact = fullBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.MAIN);
    assertThat(artifact.getLocation().exists()).isTrue();

    ApkSubject apkSubject = expect.about(ApkSubject.FACTORY).that(artifact.getLocation());
    apkSubject.contains("instant-run.zip");
    assertThat(apkSubject.hasMainDexFile());

    // now perform a hot swap test.
    File mainClasses = new File(mProject.getTestDir(), "jars/main/classes.jar");
    assertThat(mainClasses.exists()).isTrue();

    File originalFile = new File(mainClasses.getParentFile(), "original_classes.jar");
    assertThat(mainClasses.renameTo(originalFile)).isTrue();

    try (JarFile inputJar = new JarFile(originalFile);
            JarOutputStream jarOutputFile = new JarOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(mainClasses.getParentFile(), "classes.jar"))))) {
        Enumeration<JarEntry> entries = inputJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry element = entries.nextElement();
            try (InputStream inputStream = new BufferedInputStream(inputJar.getInputStream(element))) {
                if (!element.isDirectory()) {
                    jarOutputFile.putNextEntry(new ZipEntry(element.getName()));
                    try {
                        if (element.getName().contains("MainActivity.class")) {
                            // perform hot swap change
                            byte[] classBytes = new byte[(int) element.getSize()];
                            ByteStreams.readFully(inputStream, classBytes);
                            classBytes = hotswapChange(classBytes);
                            jarOutputFile.write(classBytes);
                        } else {
                            ByteStreams.copy(inputStream, jarOutputFile);
                        }/*w  ww.  j ava  2s  . co  m*/
                    } finally {
                        jarOutputFile.closeEntry();
                    }
                }
            }
        }
    }

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("process");

    instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(2);
    InstantRunBuildContext.Build lastBuild = instantRunBuildContext.getLastBuild();
    assertThat(lastBuild).isNotNull();
    assertThat(lastBuild.getVerifierStatus().isPresent());
    assertThat(lastBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.COMPATIBLE);
    assertThat(lastBuild.getArtifacts()).hasSize(1);
    artifact = lastBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.RELOAD_DEX);
    assertThat(artifact.getLocation()).isNotNull();
    File dexFile = artifact.getLocation();
    assertThat(dexFile.exists()).isTrue();
    DexFileSubject reloadDex = expect.about(DexFileSubject.FACTORY).that(dexFile);
    reloadDex.hasClass("Lcom/android/tools/fd/runtime/AppPatchesLoaderImpl;").that();
    reloadDex.hasClass("Lcom/example/jedo/blazeapp/MainActivity$override;").that();
}

From source file:org.apache.hadoop.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs
 *///from   w  w  w.  j ava 2s  . co m
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();
    List<File> outDirEntries = FileListing.getFileListing(new File(jarOutDir));

    String jarFilename = getJarFilename();

    LOG.info("Writing jar file: " + jarFilename);

    findThisJar();
    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        if (!jarFileObj.delete()) {
            LOG.warn("Could not remove existing jar file: " + jarFilename);
        }
    }

    FileOutputStream fstream = null;
    JarOutputStream jstream = null;
    try {
        fstream = new FileOutputStream(jarFilename);
        jstream = new JarOutputStream(fstream);

        // for each input class file, create a zipfile entry for it,
        // read the file into a buffer, and write it to the jar file.

        for (File entry : outDirEntries) {
            if (entry.equals(jarFileObj)) {
                // don't include our own jar!
                continue;
            } else if (entry.isDirectory()) {
                // don't write entries for directories
                continue;
            } else {
                String fileName = entry.getName();

                boolean include = fileName.endsWith(".class") && sources
                        .contains(fileName.substring(0, fileName.length() - ".class".length()) + ".java");

                if (include) {
                    // include this file.

                    // chomp off the portion of the full path that is shared
                    // with the base directory where class files were put;
                    // we only record the subdir parts in the zip entry.
                    String fullPath = entry.getAbsolutePath();
                    String chompedPath = fullPath.substring(jarOutDir.length());

                    LOG.debug("Got classfile: " + entry.getPath() + " -> " + chompedPath);
                    ZipEntry ze = new ZipEntry(chompedPath);
                    jstream.putNextEntry(ze);
                    copyFileToStream(entry, jstream);
                    jstream.closeEntry();
                }
            }
        }

        // put our own jar in there in its lib/ subdir
        String thisJarFile = findThisJar();
        if (null != thisJarFile) {
            File thisJarFileObj = new File(thisJarFile);
            String thisJarBasename = thisJarFileObj.getName();
            String thisJarEntryName = "lib" + File.separator + thisJarBasename;
            ZipEntry ze = new ZipEntry(thisJarEntryName);
            jstream.putNextEntry(ze);
            copyFileToStream(thisJarFileObj, jstream);
            jstream.closeEntry();
        } else {
            // couldn't find our own jar (we were running from .class files?)
            LOG.warn("Could not find jar for Sqoop; MapReduce jobs may not run correctly.");
        }
    } finally {
        IOUtils.closeStream(jstream);
        IOUtils.closeStream(fstream);
    }
}

From source file:org.apache.hadoop.yarn.util.TestFSDownload.java

static LocalResource createJarFile(FileContext files, Path p, int len, Random r, LocalResourceVisibility vis)
        throws IOException, URISyntaxException {
    byte[] bytes = new byte[len];
    r.nextBytes(bytes);/*from  w w  w.  j a va2  s.  c o  m*/

    File archiveFile = new File(p.toUri().getPath() + ".jar");
    archiveFile.createNewFile();
    JarOutputStream out = new JarOutputStream(new FileOutputStream(archiveFile));
    out.putNextEntry(new JarEntry(p.getName()));
    out.write(bytes);
    out.closeEntry();
    out.close();

    LocalResource ret = recordFactory.newRecordInstance(LocalResource.class);
    ret.setResource(URL.fromPath(new Path(p.toString() + ".jar")));
    ret.setSize(len);
    ret.setType(LocalResourceType.ARCHIVE);
    ret.setVisibility(vis);
    ret.setTimestamp(files.getFileStatus(new Path(p.toString() + ".jar")).getModificationTime());
    return ret;
}

From source file:com.streamsets.datacollector.cluster.TestTarFileCreator.java

private File createJar(File parentDir) throws IOException {
    if (parentDir.isFile()) {
        parentDir.delete();//from   w  w w . j av  a 2 s  .c  o m
    }
    parentDir.mkdirs();
    Assert.assertTrue(parentDir.isDirectory());
    String uuid = UUID.randomUUID().toString();
    File jar = new File(parentDir, uuid + ".jar");
    JarOutputStream out = new JarOutputStream(new FileOutputStream(jar));
    JarEntry entry = new JarEntry("sample.txt");
    out.putNextEntry(entry);
    out.write(uuid.getBytes(StandardCharsets.UTF_8));
    out.closeEntry();
    out.close();
    return jar;
}

From source file:org.wso2.carbon.integration.common.utils.FileManager.java

public static void copyJarFile(File sourceFile, String destinationDirectory) throws IOException {
    File destinationFileDirectory = new File(destinationDirectory);
    JarFile jarFile = new JarFile(sourceFile);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
    JarOutputStream jarOutputStream = null;
    try {//from  w  w w  . j ava 2 s  .  co  m
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            //jarOutputStream.putNextEntry(jarEntry);
            //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
            jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                jarOutputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            jarOutputStream.flush();
            jarOutputStream.closeEntry();
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
}