Example usage for java.util.jar JarOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

Usage

From source file:com.h3xstream.findbugs.test.service.FindBugsLauncher.java

/**
 * The minimum requirement to have a "valid" archive plugin is to include
 * findbugs.xml, messages.xml and MANIFEST.MF files. The rest of the
 * resources are load using the parent ClassLoader (Not requires to be in
 * the jar)./*from w ww.  ja va 2 s  .  c  o m*/
 * <p>
 * Instead of building a file on disk, the result of the stream is kept in
 * memory and return as a byte array.
 *
 * @return
 * @throws IOException
 * @throws URISyntaxException 
 */
private byte[] buildFakePluginJar() throws IOException, URISyntaxException {
    ClassLoader cl = getClass().getClassLoader();

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream jar = new JarOutputStream(buffer);

    final URL metadata = cl.getResource("metadata");
    if (metadata != null) {
        final File dir = new File(metadata.toURI());

        //Add files to the jar stream
        addFilesToStream(cl, jar, dir, "");
    }
    jar.finish();
    jar.close();

    return buffer.toByteArray();
}

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs.
 *//*from w w  w .j av  a  2  s  . c om*/
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();

    String jarFilename = getJarFilename();

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

    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        LOG.debug("Found existing jar (" + jarFilename + "); removing.");
        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);

        addClassFilesFromDir(new File(jarOutDir), jstream);
        jstream.finish();
    } finally {
        if (null != jstream) {
            try {
                jstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing jar stream: " + ioe.toString());
            }
        }

        if (null != fstream) {
            try {
                fstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing file stream: " + ioe.toString());
            }
        }
    }

    LOG.debug("Finished writing jar file " + jarFilename);
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java

/**
 * Creates a jar based on the given entries and manifest. This method will
 * always close the given output stream.
 * //from  w ww. j a va2s.com
 * @param manifest jar manifest
 * @param entries map of resources keyed by the jar entry named
 * @param outputStream output stream for writing the jar
 * @return number of byte written to the jar
 */
public static int createJar(Manifest manifest, Map entries, OutputStream outputStream) throws IOException {
    int writtenBytes = 0;

    // load manifest
    // add it to the jar
    JarOutputStream jarStream = null;

    try {
        // add a jar stream on top
        jarStream = (manifest != null ? new JarOutputStream(outputStream, manifest)
                : new JarOutputStream(outputStream));

        // select fastest level (no compression)
        jarStream.setLevel(Deflater.NO_COMPRESSION);

        // add deps
        for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
            Map.Entry element = (Map.Entry) iter.next();

            String entryName = (String) element.getKey();

            // safety check - all entries must start with /
            if (!entryName.startsWith(SLASH))
                entryName = SLASH + entryName;

            Resource entryValue = (Resource) element.getValue();

            // skip special/duplicate entries (like MANIFEST.MF)
            if (MANIFEST_JAR_LOCATION.equals(entryName)) {
                iter.remove();
            } else {
                // write jar entry
                writtenBytes += JarUtils.writeToJar(entryValue, entryName, jarStream);
            }
        }
    } finally {
        try {
            jarStream.flush();
        } catch (IOException ex) {
            // ignore
        }
        try {
            jarStream.finish();
        } catch (IOException ex) {
            // ignore
        }

    }

    return writtenBytes;
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

/**
 * Processes a pack200 template, by writing it both as a pack200 file and
 * a Jar file to the output stream./*from w  ww .j a v  a 2 s .  c  om*/
 *
 * @param filename The name of the template. Must end with ".jar.pack.gz".
 * @param in An input stream for reading the contents of the template.
 */
private void processPack200Template(String filename, InputStream in) throws IOException {
    p.setNote("Exporting " + filename + " ...");
    p.setProgress(p.getProgress() + 1);

    // Determine whether we can skip this file
    boolean skip = true;
    int pos1 = filename.lastIndexOf('/');
    int pos2 = filename.lastIndexOf("Player.jar.pack.gz");
    if (pos2 != -1) {
        for (CubeKind ck : playerCubeKinds) {
            if (ck.isNameOfKind(filename.substring(pos1 + 1, pos2))) {
                skip = false;
                break;
            }
        }
        if (skip)
            for (CubeKind ck : virtualCubeKinds) {
                if (ck.isNameOfKind(filename.substring(pos1 + 1, pos2))) {
                    skip = false;
                    break;
                }
            }
    }
    if (skip) {
        pos1 = filename.lastIndexOf("Virtual");
        pos2 = filename.lastIndexOf(".jar.pack.gz");
        if (pos2 != -1) {
            for (CubeKind ck : virtualCubeKinds) {
                if (ck.isNameOfKind(filename.substring(pos1 + 7, pos2))) {
                    skip = false;
                    break;
                }
            }
        }
    }
    if (skip) {
        return;
    }

    byte[] buf = new byte[1024];
    int len;

    // Write the pack200 file into the output and into a temporary buffer
    putNextEntry(filename);
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    while (-1 != (len = in.read(buf, 0, buf.length))) {
        tmp.write(buf, 0, len);
        entryOut.write(buf, 0, len);
    }
    closeEntry();
    tmp.close();

    // Uncompress the pack200 file from the temporary buffer into the output
    putNextEntry(filename.substring(0, filename.length() - 8));
    InputStream itmp = new GZIPInputStream(new ByteArrayInputStream(tmp.toByteArray()));
    JarOutputStream jout = new JarOutputStream(entryOut);
    jout.setLevel(Deflater.BEST_COMPRESSION);
    Unpacker unpacker = Pack200.newUnpacker();
    unpacker.unpack(itmp, jout);

    jout.finish();
    closeEntry();
}

From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java

/**
 * This will publish the artifact to Azkaban for scheduled running.  The artifact should be of the format
 * <p/>/*from   w  ww  .jav  a2 s .  com*/
 * <p/>
 * The artifact at this point in time will already have included the SSL certs.
 * <p/>
 * Its up to the publisher to reorganize the tar file if needed for its PaaS
 *
 * @param artifact    The artifact to deploy
 * @param callerToken - The token of the user or application that initiated this call
 * @throws DeploymentException - On any exceptions
 */
@Override
public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException {
    File unzippedPack = null;
    File azkabanZip = null;
    ZipOutputStream zipOutputStream = null;
    String flowName;
    final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo();

    // Get the Azkaban authentication token
    final AuthenticationResult authenticatorResult;
    try {
        authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(),
                azConf.getPassword()).login();
    } catch (URISyntaxException e) {
        throw new DeploymentException(e.getMessage());
    }

    if (authenticatorResult.hasError()) {
        log.error("Could not log into Azkaban: " + authenticatorResult.getError());
        throw new DeploymentException(authenticatorResult.getError());
    }

    log.info("Successfully logged into Azkaban. Now creating .zip to upload");

    try {
        // Unzip the artifact
        unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact()));
        log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath());

        // Create a .zip file to submit to Azkaban
        azkabanZip = File.createTempFile("ezbatch_", ".zip");
        log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath());
        zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip));

        // Copy the configs from the artifact to the top level of the zip.  This should contain the Azkaban
        // .jobs and .properties
        final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get();
        final File configDirFile = new File(configDir);
        for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, "")));
            IOUtils.copy(new FileInputStream(f), zipOutputStream);
            zipOutputStream.closeEntry();
        }
        log.info("Copied configs to the .zip");

        // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed
        final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/";
        for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream
                    .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/")));

            final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f));
            final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream);

            JarEntry je;
            while ((je = jarInputStream.getNextJarEntry()) != null) {
                jarOutputStream.putNextEntry(je);
                IOUtils.copy(jarInputStream, jarOutputStream);
                jarOutputStream.closeEntry();
            }
            log.info("Created Jar file");

            // Add the SSL certs to the jar
            final String sslPath = UnzipUtil.getSSLPath(configDirFile).get();
            for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE,
                    TrueFileFilter.TRUE)) {
                if (sslFile.isFile()) {
                    jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName()));
                    IOUtils.copy(new FileInputStream(sslFile), jarOutputStream);
                    jarOutputStream.closeEntry();
                }
            }
            log.info("Added SSL certs to jar");

            // Add the application.properties to the jar file so the jobs can read it
            final File appProps = new File(configDir, "application.properties");
            final Properties adjustedProperties = new Properties();
            adjustedProperties.load(new FileInputStream(appProps));
            adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/");
            jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties"));
            adjustedProperties.store(jarOutputStream, null);
            jarOutputStream.closeEntry();

            jarOutputStream.finish();
            zipOutputStream.closeEntry();
        }

        // Check to see if there are any .job files.  If there aren't, this is an external job and we need to create
        // one for the .zip file
        final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false);
        if (jobFiles.isEmpty()) {
            // If there are no job files present then we need to create one for the user
            final StringBuilder sb = new StringBuilder(
                    "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n"
                            + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config");

            for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) {
                sb.append(" -c ").append(xmlConfig.getName());
            }

            zipOutputStream.putNextEntry(new ZipEntry("Analytic.job"));
            IOUtils.copy(new StringReader(sb.toString()), zipOutputStream);
            zipOutputStream.closeEntry();
            log.info("There was no .job file so one was created for the .zip");
            flowName = "Analytic";
        } else {
            flowName = jobInfo.getFlowName();
            if (flowName == null) {
                log.warn("Manifest did not contain flow_name. Guessing what it should be");
                flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName());
                log.info("Guessing the flow name should be:" + flowName);
            }
        }

        zipOutputStream.finish();
        log.info("Finished creating .zip");

        // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip
        // file needs to be uploaded to a project, and the project may or may not already exist.
        final String projectName = ArtifactHelpers.getAppId(artifact) + "_"
                + ArtifactHelpers.getServiceId(artifact);
        final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));
        final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed");

        // If the project already exists, it will return an error, but really it's not a problem
        if (managerResult.hasError()) {
            if (!managerResult.getMessage().contains("already exists")) {
                log.error("Could not create project: " + managerResult.getMessage());
                throw new DeploymentException(managerResult.getMessage());
            } else {
                log.info("Reusing the existing project: " + projectName);
            }
        } else {
            log.info("Created new project: " + projectName);
            log.info("Path: " + managerResult.getPath());
        }

        // Upload the .zip file to the project
        final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(),
                azConf.getAzkabanUrl(), projectName, azkabanZip);
        final UploaderResult uploaderResult = uploader.uploadZip();

        if (uploaderResult.hasError()) {
            log.error("Could not upload the zip file: " + uploaderResult.getError());
            throw new DeploymentException(uploaderResult.getError());
        }

        log.info("Successfully submitted zip file to Azkaban");

        // Schedule the jar to run.  If the start times aren't provided, it will run in 2 minutes

        final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));

        // Add the optional parameters if they are present
        if (jobInfo.isSetStartDate()) {
            scheduler.setScheduleDate(jobInfo.getStartDate());
        }
        if (jobInfo.isSetStartTime()) {
            scheduler.setScheduleTime(jobInfo.getStartTime());
        }
        if (jobInfo.isSetRepeat()) {
            scheduler.setPeriod(jobInfo.getRepeat());
        }

        final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName,
                uploaderResult.getProjectId());
        if (schedulerResult.hasError()) {
            log.error("Failure to schedule job: " + schedulerResult.getError());
            throw new DeploymentException(schedulerResult.getError());
        }

        log.info("Successfully scheduled flow: " + flowName);

    } catch (Exception ex) {
        log.error("No Nos!", ex);
        throw new DeploymentException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        FileUtils.deleteQuietly(azkabanZip);
        FileUtils.deleteQuietly(unzippedPack);
    }
}

From source file:org.apache.hadoop.mapred.TestTaskTrackerLocalization.java

/**
 * @param jobConf// w  w w . ja  v a  2 s  . c om
 * @throws IOException
 * @throws FileNotFoundException
 */
private void uploadJobJar(JobConf jobConf) throws IOException, FileNotFoundException {
    File jobJarFile = new File(TEST_ROOT_DIR, "jobjar-on-dfs.jar");
    JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jobJarFile));
    ZipEntry ze = new ZipEntry("lib/lib1.jar");
    jstream.putNextEntry(ze);
    jstream.closeEntry();
    ze = new ZipEntry("lib/lib2.jar");
    jstream.putNextEntry(ze);
    jstream.closeEntry();
    jstream.finish();
    jstream.close();
    jobConf.setJar(jobJarFile.toURI().toString());
}

From source file:org.apache.openjpa.eclipse.PluginLibrary.java

void copyJar(JarInputStream jar, JarOutputStream out) throws IOException {
    if (jar == null || out == null)
        return;/*from   w w  w.j a v a 2 s  .c  om*/

    try {
        JarEntry entry = null;
        while ((entry = jar.getNextJarEntry()) != null) {
            out.putNextEntry(entry);
            int b = -1;
            while ((b = jar.read()) != -1) {
                out.write(b);
            }
        }
        out.closeEntry();
    } finally {
        out.finish();
        out.flush();
        out.close();
        jar.close();
    }
}

From source file:org.bimserver.plugins.VirtualFile.java

public void createJar(OutputStream outputStream) {
    try {/*from w  ww .  ja  va  2s .com*/
        JarOutputStream jarOutputStream = new JarOutputStream(outputStream);
        createJar(jarOutputStream);
        jarOutputStream.finish();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

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

public void pack(Handler<?> handler, OutputStream to) throws IOException {
    if (handler == null) {
        throw new NullPointerException();
    }/*from  w  ww  . j av a2 s  .  com*/
    if (!(handler instanceof Serializable)) {
        throw new IllegalArgumentException(handler + " is not of type " + Serializable.class.getName() + ".");
    }
    if (to == null) {
        throw new NullPointerException();
    }
    final String dataFileName = getDataFileName();
    // noinspection unchecked
    final Class<? extends Handler<?>> handlerType = (Class<? extends Handler<?>>) handler.getClass();
    final Map<String, JarResource> fileNameToJarResource = buildFileNameToJarResource();
    final Manifest manifest = createManifest(dataFileName, fileNameToJarResource.keySet());
    final JarOutputStream jar = new JarOutputStream(to, manifest);

    final Set<String> namesOfWrittenTypeFiles = new HashSet<String>();
    writeTypes(handlerType, jar, namesOfWrittenTypeFiles);
    writeJarResourcesDependencies(fileNameToJarResource, jar);
    writeData(handler, jar, dataFileName);

    jar.finish();
}

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
 *//*from w ww.j ava2  s .c  o  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$
    }
}