Example usage for org.apache.commons.compress.archivers.jar JarArchiveEntry JarArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.jar JarArchiveEntry JarArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.jar JarArchiveEntry JarArchiveEntry.

Prototype

public JarArchiveEntry(JarEntry entry) throws ZipException 

Source Link

Usage

From source file:es.jamisoft.comun.utils.compression.Jar.java

private void addToJar(File afFichero, String asDir) {
    try {/*from   ww w . j  av  a 2s. c  o  m*/
        String lsRutaAbs = afFichero.getPath();
        String lsRutaRelat = lsRutaAbs.substring(isDirectorioRelativoComp.length(), lsRutaAbs.length());
        JarArchiveEntry entry = new JarArchiveEntry(lsRutaRelat);

        sout.putArchiveEntry(entry);

        FileInputStream lfin = new FileInputStream(afFichero);
        byte buffer[] = new byte[2048];
        int liLeido = -1;
        int numCaracteresLeidos = 0;

        while ((liLeido = lfin.read(buffer, 0, 2048)) != -1) {
            sout.write(buffer, 0, liLeido);
        }

        sout.flush();
        sout.closeArchiveEntry();
        lfin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ikon.util.ArchiveUtils.java

/**
 * Recursively create JAR archive from directory 
 *///from w  w  w  .  j  a va2 s  . com
public static void createJar(File path, String root, OutputStream os) throws IOException {
    log.debug("createJar({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        JarArchiveOutputStream jaos = new JarArchiveOutputStream(os);
        jaos.setComment("Generated by openkm");
        jaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        jaos.setUseLanguageEncodingFlag(true);
        jaos.setFallbackToUTF8(true);
        jaos.setEncoding("UTF-8");

        // Prevents java.util.jar.JarException: JAR file must have at least one entry
        JarArchiveEntry jae = new JarArchiveEntry(root + "/");
        jaos.putArchiveEntry(jae);
        jaos.closeArchiveEntry();

        createJarHelper(path, jaos, root);

        jaos.flush();
        jaos.finish();
        jaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createJar: void");
}

From source file:com.ikon.util.ArchiveUtils.java

/**
 * Recursively create JAR archive from directory helper utility 
 *///from   w  w w . j ava2 s  .c  om
private static void createJarHelper(File fs, JarArchiveOutputStream jaos, String zePath) throws IOException {
    log.debug("createJarHelper({}, {}, {})", new Object[] { fs, jaos, zePath });
    File[] files = fs.listFiles();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            log.debug("DIRECTORY {}", files[i]);
            JarArchiveEntry jae = new JarArchiveEntry(zePath + "/" + files[i].getName() + "/");
            jaos.putArchiveEntry(jae);
            jaos.closeArchiveEntry();

            createJarHelper(files[i], jaos, zePath + "/" + files[i].getName());
        } else {
            log.debug("FILE {}", files[i]);
            JarArchiveEntry jae = new JarArchiveEntry(zePath + "/" + files[i].getName());
            jaos.putArchiveEntry(jae);
            FileInputStream fis = new FileInputStream(files[i]);
            IOUtils.copy(fis, jaos);
            fis.close();
            jaos.closeArchiveEntry();
        }
    }

    log.debug("createJarHelper: void");
}

From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java

@Override
public void execute() throws MojoExecutionException {

    Path warExecFile = Paths.get(this.buildDirectory, this.finalName);
    try {/*from www . ja  va2 s .c  om*/
        Files.deleteIfExists(warExecFile);
        Files.createDirectories(warExecFile.getParent());

        try (OutputStream os = Files.newOutputStream(warExecFile);
                ArchiveOutputStream aos = new ArchiveStreamFactory()
                        .createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) {

            // If project is a war project add the war to the project
            if ("war".equalsIgnoreCase(this.project.getPackaging())) {
                File projectArtifact = this.project.getArtifact().getFile();
                if (projectArtifact != null && Files.exists(projectArtifact.toPath())) {
                    aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName()));
                    try (InputStream is = Files.newInputStream(projectArtifact.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();
                }
            }

            // Add extraWars into the jar
            if (this.extraWars != null) {
                for (Dependency extraWarDependency : this.extraWars) {
                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(extraWarDependency.getGroupId(),
                            extraWarDependency.getArtifactId(), extraWarDependency.getType(),
                            extraWarDependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    File extraWarFile = result.getArtifact().getFile();
                    aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName()));
                    try (InputStream is = Files.newInputStream(extraWarFile.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();

                }
            }

            // Add extraResources into the jar. Folder /extra
            if (this.extraResources != null) {
                for (Resource extraResource : this.extraResources) {
                    DirectoryScanner directoryScanner = new DirectoryScanner();
                    directoryScanner.setBasedir(extraResource.getDirectory());

                    directoryScanner.setExcludes(extraResource.getExcludes()
                            .toArray(new String[extraResource.getExcludes().size()]));

                    if (!extraResource.getIncludes().isEmpty()) {
                        directoryScanner.setIncludes(extraResource.getIncludes()
                                .toArray(new String[extraResource.getIncludes().size()]));
                    } else {
                        // include everything by default
                        directoryScanner.setIncludes(new String[] { "**" });
                    }

                    directoryScanner.scan();
                    for (String includeFile : directoryScanner.getIncludedFiles()) {
                        aos.putArchiveEntry(
                                new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile));

                        Path extraFile = Paths.get(extraResource.getDirectory(), includeFile);
                        try (InputStream is = Files.newInputStream(extraFile)) {
                            IOUtils.copy(is, aos);
                        }
                        aos.closeArchiveEntry();
                    }

                }
            }

            Set<String> includeArtifacts = new HashSet<>();
            includeArtifacts.add("org.apache.tomcat:tomcat-jdbc");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-websocket");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli");
            includeArtifacts.add("org.yaml:snakeyaml");
            includeArtifacts.add("com.beust:jcommander");

            if (this.includeJSPSupport) {
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper");
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-el");
                includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj");
            }

            for (Artifact pluginArtifact : this.pluginArtifacts) {
                String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId();
                if (includeArtifacts.contains(artifactName)) {
                    try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.extraDependencies != null) {
                for (Dependency dependency : this.extraDependencies) {

                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
                            dependency.getType(), dependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.includeJSPSupport) {
                addFile(aos, "/conf/web.xml", "conf/web.xml");
            } else {
                addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml");
            }
            addFile(aos, "/conf/logging.properties", "conf/logging.properties");

            if (this.includeTcNativeWin32 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32"));
                Files.copy(Paths.get(this.includeTcNativeWin32), aos);
                aos.closeArchiveEntry();
            }

            if (this.includeTcNativeWin64 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64"));
                Files.copy(Paths.get(this.includeTcNativeWin64), aos);
                aos.closeArchiveEntry();
            }

            String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions",
                    "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config",
                    "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context",
                    "ch.rasc.embeddedtc.runner.DeleteDirectory",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1",
                    "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions",
                    "ch.rasc.embeddedtc.runner.Runner$StopOptions",
                    "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" };

            for (String rc : runnerClasses) {
                String classAsPath = rc.replace('.', '/') + ".class";

                try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) {
                    aos.putArchiveEntry(new JarArchiveEntry(classAsPath));
                    IOUtils.copy(is, aos);
                    aos.closeArchiveEntry();
                }
            }

            Manifest manifest = new Manifest();

            Manifest.Attribute mainClassAtt = new Manifest.Attribute();
            mainClassAtt.setName("Main-Class");
            mainClassAtt.setValue(Runner.class.getName());
            manifest.addConfiguredAttribute(mainClassAtt);

            aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
            manifest.write(aos);
            aos.closeArchiveEntry();

            aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME));
            aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
            aos.closeArchiveEntry();

        }
    } catch (IOException | ArchiveException | ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create JAR archive from directory
 *///from www .j a v a2  s. co  m
public static void createJar(File path, String root, OutputStream os) throws IOException {
    log.debug("createJar({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        JarArchiveOutputStream jaos = new JarArchiveOutputStream(os);
        jaos.setComment("Generated by OpenKM");
        jaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        jaos.setUseLanguageEncodingFlag(true);
        jaos.setFallbackToUTF8(true);
        jaos.setEncoding("UTF-8");

        // Prevents java.util.jar.JarException: JAR file must have at least one entry
        JarArchiveEntry jae = new JarArchiveEntry(root + "/");
        jaos.putArchiveEntry(jae);
        jaos.closeArchiveEntry();

        createJarHelper(path, jaos, root);

        jaos.flush();
        jaos.finish();
        jaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createJar: void");
}

From source file:com.jrummyapps.busybox.utils.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys.//w  ww .ja v  a  2  s .c o m
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IoUtils.closeQuietly(inputJar);
        IoUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys./*  w w  w.j  a  va2  s.  c om*/
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IOUtils.closeQuietly(inputJar);
        IOUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:es.jamisoft.comun.utils.compression.Jar.java

private void metaInf() {
    byte[] buf = "Manifest-Version: 1.0\r\nX-COMMENT: www.jamisoft.es - Jose Antonio Jamilena Daza".getBytes();
    ByteArrayInputStream manifest = new ByteArrayInputStream(buf);
    String asDir = "/META-INF/";
    try {//from   w w w  . j a va 2 s  .  c om
        String lsRutaAbs = "/META-INF/manifest.mf";
        //String lsRutaRelat = lsRutaAbs.substring(isDirectorioRelativoComp.length(), lsRutaAbs.length());
        String lsRutaRelat = lsRutaAbs;
        JarArchiveEntry entry = new JarArchiveEntry(lsRutaRelat);

        sout.putArchiveEntry(entry);

        byte buffer[] = new byte[2048];
        int liLeido = -1;
        int numCaracteresLeidos = 0;

        while ((liLeido = manifest.read(buffer, 0, 2048)) != -1) {
            sout.write(buffer, 0, liLeido);
        }

        sout.flush();
        sout.closeArchiveEntry();
        manifest.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  w  w  .j  av  a 2s .  c  o  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:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

private static void writeJarEntry(JarArchiveOutputStream jaos, String name, byte[] data) throws IOException {
    ZipArchiveEntry entry = new JarArchiveEntry(name);
    entry.setSize(data.length);//from  w  ww. j a  v  a2  s  .c o m
    jaos.putArchiveEntry(entry);
    jaos.write(data);
    jaos.closeArchiveEntry();
}