Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

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/>/*  w w w . ja v a  2  s . co  m*/
 * <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.wso2.esb.integration.common.utils.common.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws IOException, URISyntaxException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    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 = 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);
        }/*from  w  w  w.  j av  a 2 s.c  o  m*/
        inputStream.close();
        jarOutputStream.flush();
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
}

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

/**
 * Recursively jars up the given path under the given directory.
 */// w  ww. j av a 2  s.co m
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path) throws IOException {
    //if (mVerbose)
    {
        //System.out.println("checking " + dirOrFile2jar);
    }
    if (dirOrFile2jar.isDirectory()) {
        String[] dirList = dirOrFile2jar.list();
        String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
        if (path != null) {
            JarEntry je = new JarEntry(subPath);
            je.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(je);
            jos.flush();
            jos.closeEntry();
        }
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(dirOrFile2jar, dirList[i]);
            jarDir(f, jos, subPath);
        }
    } else {
        if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
            //if (mVerbose)
            {
                //System.out.println("skipping " + dirOrFile2jar.getPath());
            }
            return;
        }

        if (mVerbose) {
            //System.out.println("adding " + dirOrFile2jar.getPath());
        }
        FileInputStream fis = new FileInputStream(dirOrFile2jar);
        try {
            JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
            entry.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(entry);
            while ((mByteCount = fis.read(mBuffer)) != -1) {
                jos.write(mBuffer, 0, mByteCount);
                if (mVerbose) {
                    //System.out.println("wrote " + mByteCount + " bytes");
                }
            }
            jos.flush();
            jos.closeEntry();
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            fis.close();
        }
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

@Override
public synchronized void saveContents(String contents, String prefix, int msgNum)
        throws IOException, GeneralSecurityException {
    JarOutputStream jos = getContentsJarOS(prefix);

    // create the bytes
    ZipEntry ze = new ZipEntry(msgNum + ".content");
    ze.setMethod(ZipEntry.DEFLATED);
    //      byte[] buf = CryptoUtils.getEncryptedBytes(contents.getBytes("UTF-8"));
    byte[] buf = contents.getBytes("UTF-8");
    jos.putNextEntry(ze);
    jos.write(buf, 0, buf.length);//from   w  w  w.j  av a2s  . c  o m
    jos.closeEntry();
    jos.flush();
}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private void copyStream(InputStream inputStream, JarOutputStream jos, JarEntry ze, String pathName) {
    try {/*from   ww  w  . j a  v  a2 s . c  o m*/

        ZipEntry newEntry = new ZipEntry(pathName);
        // Make sure there is date and time set.
        if (ze.getTime() != -1) {
            newEntry.setTime(ze.getTime());
            newEntry.setCrc(ze.getCrc()); // If found set it into output file.
        }
        jos.putNextEntry(newEntry);
        IOUtils.copy(inputStream, jos);
        IOUtils.closeQuietly(inputStream);
    } catch (Exception e) {
        //throw new GradleException("copy stream exception", e);
        //e.printStackTrace();
        logger.error("copy stream exception >>> " + pathName + " >>>" + e.getMessage());
    }
}

From source file:org.apache.solr.core.TestCoreContainer.java

@Test
public void testSharedLib() throws Exception {
    Path tmpRoot = createTempDir("testSharedLib");

    File lib = new File(tmpRoot.toFile(), "lib");
    lib.mkdirs();//w  ww. ja  v a2  s.  c om

    JarOutputStream jar1 = new JarOutputStream(new FileOutputStream(new File(lib, "jar1.jar")));
    jar1.putNextEntry(new JarEntry("defaultSharedLibFile"));
    jar1.closeEntry();
    jar1.close();

    File customLib = new File(tmpRoot.toFile(), "customLib");
    customLib.mkdirs();

    JarOutputStream jar2 = new JarOutputStream(new FileOutputStream(new File(customLib, "jar2.jar")));
    jar2.putNextEntry(new JarEntry("customSharedLibFile"));
    jar2.closeEntry();
    jar2.close();

    final CoreContainer cc1 = init(tmpRoot, "<solr></solr>");
    try {
        cc1.loader.openResource("defaultSharedLibFile").close();
    } finally {
        cc1.shutdown();
    }

    final CoreContainer cc2 = init(tmpRoot, "<solr><str name=\"sharedLib\">lib</str></solr>");
    try {
        cc2.loader.openResource("defaultSharedLibFile").close();
    } finally {
        cc2.shutdown();
    }

    final CoreContainer cc3 = init(tmpRoot, "<solr><str name=\"sharedLib\">customLib</str></solr>");
    try {
        cc3.loader.openResource("customSharedLibFile").close();
    } finally {
        cc3.shutdown();
    }
}

From source file:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }//  w ww.j a va2  s.  co m
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

private boolean createFeatureJar(final String featureId, final String featureVersion, final String featureXml,
        final String jarDir) {

    final File file = new File(jarDir, featureId + "_" + featureVersion + ".jar");
    file.getParentFile().mkdirs();/*from w ww  .j  a  v  a  2  s.  c om*/

    try {
        final JarOutputStream jarOutputStream = new JarOutputStream(
                new BufferedOutputStream(new FileOutputStream(file)));

        final JarEntry entry = new JarEntry("feature.xml");
        jarOutputStream.putNextEntry(entry);

        final BufferedInputStream featureXmlStream = new BufferedInputStream(new FileInputStream(featureXml));
        copy(featureXmlStream, jarOutputStream);

        jarOutputStream.close();

    } catch (final FileNotFoundException e) {
        throw new RuntimeException("Could not create Feature Jar: " + file.getAbsolutePath(), e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not create Feature Jar: " + file.getAbsolutePath(), e);
    }

    return true;
}

From source file:com.moss.nomad.core.packager.Packager.java

public void write(OutputStream o) throws Exception {

    JarOutputStream out = new JarOutputStream(o);

    {/*from ww w  . j a  va 2s . c o m*/
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(container, bao);

        byte[] containerIndex = bao.toByteArray();

        JarEntry entry = new JarEntry("META-INF/container.xml");
        out.putNextEntry(entry);
        out.write(containerIndex);
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (String path : dependencies.keySet()) {
        ResolvedDependencyInfo info = dependencies.get(path);

        JarEntry entry = new JarEntry(path);
        out.putNextEntry(entry);

        InputStream in = new FileInputStream(info.file());
        for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
            out.write(buffer, 0, numRead);
        }
        in.close();
    }

    out.close();
}

From source file:com.alu.e3.prov.service.ApiJarBuilder.java

@Override
public byte[] build(Api api, ExchangeData exchange) {
    final Map<Object, Object> variablesMap = new HashMap<Object, Object>();
    variablesMap.put("exchange", exchange);

    byte[] jarBytes = null;
    ByteArrayOutputStream baos = null;
    JarOutputStream jos = null;
    try {//from   ww  w .j  a v  a  2  s.  c om
        baos = new ByteArrayOutputStream();
        jos = new JarOutputStream(baos);

        List<JarEntryData> entries = new ArrayList<JarEntryData>();
        doGenXML(entries, api, variablesMap);
        doGenManifest(entries, api, variablesMap);
        doGenResources(entries, api, variablesMap);

        for (JarEntryData anEntry : entries) {
            jos.putNextEntry(anEntry.jarEntry);
            jos.write(anEntry.bytes);

        }
        // the close is necessary before getting bytes
        jos.close();
        jarBytes = baos.toByteArray();

        if (this.generateJarInFile) {
            // generate Jar in Disk for debug only
            doGenJar(jarBytes, api, variablesMap);
        }

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error building the jar for apiID:" + api.getId(), e);
        }
    } finally {
        if (jos != null)
            try {
                jos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }

        if (baos != null)
            try {
                baos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }
    }

    return jarBytes;
}