Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream write

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream write

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream write.

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the current archive entry.

Usage

From source file:com.haulmont.cuba.core.sys.logging.LogArchiver.java

public static void writeArchivedLogTailToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }/*from   ww  w .  j av a  2  s . c o m*/

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    byte[] content = getTailBytes(logFile);

    ArchiveEntry archiveEntry = newTailArchive(logFile.getName(), content);
    zipOutputStream.putArchiveEntry(archiveEntry);
    zipOutputStream.write(content);

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();
}

From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java

/**
 * Create a XAR file using commons compress.
 *
 * @param docs The documents to include.
 * @param encodings The charset for each document.
 * @param packageXmlEncoding The encoding of package.xml
 * @return the XAR file as a byte array.
 *//*ww w .ja v a2 s  .c  om*/
protected byte[] createZipFileUsingCommonsCompress(XWikiDocument docs[], String[] encodings,
        String packageXmlEncoding) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(baos);
    ZipArchiveEntry zipp = new ZipArchiveEntry("package.xml");
    zos.putArchiveEntry(zipp);
    zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding));
    for (int i = 0; i < docs.length; i++) {
        String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName();
        if (docs[i].getTranslation() != 0) {
            zipEntryName += "." + docs[i].getLanguage();
        }
        ZipArchiveEntry zipe = new ZipArchiveEntry(zipEntryName);
        zos.putArchiveEntry(zipe);
        String xmlCode = docs[i].toXML(false, false, false, false, getContext());
        zos.write(getEncodedByteArray(xmlCode, encodings[i]));
        zos.closeArchiveEntry();
    }
    zos.finish();
    zos.close();
    return baos.toByteArray();
}

From source file:com.gitblit.servlet.PtServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   w w  w  .ja v  a  2  s . c om*/
        response.setContentType("application/octet-stream");
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("Cache-Control", "none");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        boolean windows = false;
        try {
            String useragent = request.getHeader("user-agent").toString();
            windows = useragent.toLowerCase().contains("windows");
        } catch (Exception e) {
        }

        byte[] pyBytes;
        File file = runtimeManager.getFileOrFolder("tickets.pt", "${baseFolder}/pt.py");
        if (file.exists()) {
            // custom script
            pyBytes = readAll(new FileInputStream(file));
        } else {
            // default script
            pyBytes = readAll(getClass().getResourceAsStream("/pt.py"));
        }

        if (windows) {
            // windows: download zip file with pt.py and pt.cmd
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.zip\"");

            OutputStream os = response.getOutputStream();
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);

            // add the Python script
            ZipArchiveEntry pyEntry = new ZipArchiveEntry("pt.py");
            pyEntry.setSize(pyBytes.length);
            pyEntry.setUnixMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setTime(lastModified);
            zos.putArchiveEntry(pyEntry);
            zos.write(pyBytes);
            zos.closeArchiveEntry();

            // add a Python launch cmd file
            byte[] cmdBytes = readAll(getClass().getResourceAsStream("/pt.cmd"));
            ZipArchiveEntry cmdEntry = new ZipArchiveEntry("pt.cmd");
            cmdEntry.setSize(cmdBytes.length);
            cmdEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            cmdEntry.setTime(lastModified);
            zos.putArchiveEntry(cmdEntry);
            zos.write(cmdBytes);
            zos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            ZipArchiveEntry txtEntry = new ZipArchiveEntry("readme.txt");
            txtEntry.setSize(txtBytes.length);
            txtEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setTime(lastModified);
            zos.putArchiveEntry(txtEntry);
            zos.write(txtBytes);
            zos.closeArchiveEntry();

            // cleanup
            zos.finish();
            zos.close();
            os.flush();
        } else {
            // unix: download a tar.gz file with pt.py set with execute permissions
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.tar.gz\"");

            OutputStream os = response.getOutputStream();
            CompressorOutputStream cos = new CompressorStreamFactory()
                    .createCompressorOutputStream(CompressorStreamFactory.GZIP, os);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
            tos.setAddPaxHeadersForNonAsciiNames(true);
            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

            // add the Python script
            TarArchiveEntry pyEntry = new TarArchiveEntry("pt");
            pyEntry.setMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setModTime(lastModified);
            pyEntry.setSize(pyBytes.length);
            tos.putArchiveEntry(pyEntry);
            tos.write(pyBytes);
            tos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            TarArchiveEntry txtEntry = new TarArchiveEntry("README");
            txtEntry.setMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setModTime(lastModified);
            txtEntry.setSize(txtBytes.length);
            tos.putArchiveEntry(txtEntry);
            tos.write(txtBytes);
            tos.closeArchiveEntry();

            // cleanup
            tos.finish();
            tos.close();
            cos.close();
            os.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Computes the binary differences of two zip files. For all files contained in source and target which
 * are not equal, the binary difference is caluclated by using
 * {@link com.nothome.delta.Delta#compute(byte[], InputStream, DiffWriter)}.
 * If the files are equal, nothing is written to the output for them.
 * Files contained only in target and files to small for {@link com.nothome.delta.Delta} are copied to output.
 * Files contained only in source are ignored.
 * At last a list of all files contained in target is written to <code>META-INF/file.list</code> in output.
 *
 * @param sourceName the original zip file
 * @param targetName a modification of the original zip file
 * @param source the original zip file// w ww  .ja v a  2 s . c  o  m
 * @param target a modification of the original zip file
 * @param output the zip file where the patches have to be written to
 * @throws IOException if an error occurs reading or writing any entry in a zip file
 */
public void computeDelta(String sourceName, String targetName, ZipFile source, ZipFile target,
        ZipArchiveOutputStream output) throws IOException {
    ByteArrayOutputStream listBytes = new ByteArrayOutputStream();
    PrintWriter list = new PrintWriter(new OutputStreamWriter(listBytes));
    list.println(sourceName);
    list.println(targetName);
    computeDelta(source, target, output, list, "");
    list.close();
    ZipArchiveEntry listEntry = new ZipArchiveEntry("META-INF/file.list");
    output.putArchiveEntry(listEntry);
    output.write(listBytes.toByteArray());
    output.closeArchiveEntry();
    output.finish();
    output.flush();
}

From source file:com.amazon.aws.samplecode.travellog.util.DataExtractor.java

public void run() {
    try {/*from   w w w  . j a  va2s  .  c om*/
        //Create temporary directory
        File tmpDir = File.createTempFile("travellog", "");
        tmpDir.delete(); //Wipe out temporary file to replace with a directory
        tmpDir.mkdirs();

        logger.log(Level.INFO, "Extract temp dir: " + tmpDir);

        //Store journal to props file
        Journal journal = dao.getJournal();
        Properties journalProps = buildProps(journal);
        File journalFile = new File(tmpDir, "journal");
        journalProps.store(new FileOutputStream(journalFile), "");

        //Iterate through entries and grab related photos
        List<Entry> entries = dao.getEntries(journal);
        int entryIndex = 1;
        int imageFileIndex = 1;
        for (Entry entry : entries) {
            Properties entryProps = buildProps(entry);
            File entryFile = new File(tmpDir, "entry." + (entryIndex++));
            entryProps.store(new FileOutputStream(entryFile), "");

            List<Photo> photos = dao.getPhotos(entry);
            int photoIndex = 1;
            for (Photo photo : photos) {
                Properties photoProps = buildProps(photo);

                InputStream photoData = S3PhotoUtil.loadOriginalPhoto(photo);
                String imageFileName = "imgdata." + (imageFileIndex++);
                File imageFile = new File(tmpDir, imageFileName);

                FileOutputStream outputStream = new FileOutputStream(imageFile);
                IOUtils.copy(photoData, outputStream);
                photoProps.setProperty("file", imageFileName);
                outputStream.close();
                photoData.close();

                File photoFile = new File(tmpDir, "photo." + (entryIndex - 1) + "." + (photoIndex++));
                photoProps.store(new FileOutputStream(photoFile), "");
            }

            List<Comment> comments = dao.getComments(entry);
            int commentIndex = 1;
            for (Comment comment : comments) {
                Properties commentProps = buildProps(comment);
                File commentFile = new File(tmpDir, "comment." + (entryIndex - 1) + "." + commentIndex++);
                commentProps.store(new FileOutputStream(commentFile), "");
            }
        }

        //Bundle up the folder as a zip
        final File zipOut;

        //If we have an output path store locally
        if (outputPath != null) {
            zipOut = new File(outputPath);
        } else {
            //storing to S3
            zipOut = File.createTempFile("export", ".zip");
        }

        zipOut.getParentFile().mkdirs(); //make sure directory structure is in place
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipOut);

        //Create the zip file
        File[] files = tmpDir.listFiles();
        for (File file : files) {
            ZipArchiveEntry archiveEntry = new ZipArchiveEntry(file.getName());
            byte[] fileData = FileUtils.readFileToByteArray(file);
            archiveEntry.setSize(fileData.length);
            zaos.putArchiveEntry(archiveEntry);
            zaos.write(fileData);
            zaos.flush();
            zaos.closeArchiveEntry();
        }
        zaos.close();

        //If outputpath
        if (outputPath == null) {
            TravelLogStorageObject obj = new TravelLogStorageObject();
            obj.setBucketName(bucketName);
            obj.setStoragePath(storagePath);
            obj.setData(FileUtils.readFileToByteArray(zipOut));
            obj.setMimeType("application/zip");

            S3StorageManager mgr = new S3StorageManager();
            mgr.store(obj, false, null); //Store with full redundancy and default permissions
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java

@Override
public byte[] exportFolder(Folder folder) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    String xml = createXStream().toXML(folder);
    byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes);
    zipOutputStream.putArchiveEntry(zipEntryDesign);
    zipOutputStream.write(xmlBytes);
    try {/*from  w w w.  j av  a2  s.c o  m*/
        zipOutputStream.closeArchiveEntry();
    } catch (Exception ex) {
        throw new RuntimeException(
                String.format("Exception occurred while exporting folder %s.", folder.getName()));
    }

    zipOutputStream.close();
    return byteArrayOutputStream.toByteArray();
}

From source file:com.haulmont.cuba.core.app.importexport.EntityImportExport.java

@Override
public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) {
    String json = entitySerialization.toJson(entities, null,
            EntitySerializationOption.COMPACT_REPEATED_ENTITIES);
    byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes);
    try {/*w w w  .ja  v  a  2  s . c  o  m*/
        zipOutputStream.putArchiveEntry(singleDesignEntry);
        zipOutputStream.write(jsonBytes);
        zipOutputStream.closeArchiveEntry();
    } catch (Exception e) {
        throw new RuntimeException("Error on creating zip archive during entities export", e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}

From source file:divconq.tool.release.Main.java

@Override
public void run(Scanner scan, ApiSession api) {
    Path relpath = null;//from   w  ww . j a v a  2s.co  m
    Path gitpath = null;
    Path wikigitpath = null;

    XElement fldset = Hub.instance.getConfig().selectFirst("CommandLine/Settings");

    if (fldset != null) {
        relpath = Paths.get(fldset.getAttribute("ReleasePath"));
        gitpath = Paths.get(fldset.getAttribute("GitPath"));
        wikigitpath = Paths.get(fldset.getAttribute("WikiGitPath"));
    }

    boolean running = true;

    while (running) {
        try {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("   Release Builder Menu");
            System.out.println("-----------------------------------------------");
            System.out.println("0)  Exit");

            if (relpath != null)
                System.out.println("1)  Build release package from Settings File");

            System.out.println("2)  Build custom release package [under construction]");

            System.out.println("4)  Pack the .jar files");

            if (gitpath != null)
                System.out.println("5)  Copy Source to GitHub folder");

            System.out.println("6)  Update AWWW");

            String opt = scan.nextLine();

            Long mopt = StringUtil.parseInt(opt);

            if (mopt == null)
                continue;

            switch (mopt.intValue()) {
            case 0:
                running = false;
                break;

            case 1: {
                ReleasesHelper releases = new ReleasesHelper();

                if (!releases.init(relpath))
                    break;

                System.out.println("Select a release to build");
                System.out.println("0) None");

                List<String> rnames = releases.names();

                for (int i = 0; i < rnames.size(); i++)
                    System.out.println((i + 1) + ") " + rnames.get(i));

                System.out.println("Option #: ");
                opt = scan.nextLine();

                mopt = StringUtil.parseInt(opt);

                if ((mopt == null) || (mopt == 0))
                    break;

                XElement relchoice = releases.get(mopt.intValue() - 1);

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                XElement prindesc = availpackages.get(inst.prinpackage);

                XElement prininst = prindesc.find("Install");

                if (prininst == null) {
                    System.out.println("Principle package: " + inst.prinpackagenm
                            + " cannot be released directly, it must be part of another package.");
                    break;
                }

                String relvers = prindesc.getAttribute("Version");

                System.out.println("Building release version " + relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    System.out.println("Previous release version " + prindesc.getAttribute("LastVersion"));

                String rname = relchoice.getAttribute("Name");
                Path destpath = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.exists(destpath)) {
                    System.out.println("Version " + relvers + " already exists, overwrite? (y/n): ");
                    if (!scan.nextLine().toLowerCase().startsWith("y"))
                        break;

                    Files.delete(destpath);
                }

                System.out.println("Preparing zip files");

                AtomicBoolean errored = new AtomicBoolean();
                Path tempfolder = FileUtil.allocateTempFolder2();

                ListStruct ignorepaths = new ListStruct();
                Set<String> nolongerdepends = new HashSet<>();
                Set<String> dependson = new HashSet<>();

                // put all the release files into a temp folder
                inst.instpkgs.forEach(pname -> {
                    availpackages.get(pname).selectAll("DependsOn").stream()
                            .filter(doel -> !doel.hasAttribute("Option")
                                    || inst.relopts.contains(doel.getAttribute("Option")))
                            .forEach(doel -> {
                                // copy all libraries we rely on
                                doel.selectAll("Library").forEach(libel -> {
                                    dependson.add(libel.getAttribute("File"));

                                    Path src = Paths.get("./lib/" + libel.getAttribute("File"));
                                    Path dest = tempfolder.resolve("lib/" + libel.getAttribute("File"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all files we rely on
                                doel.selectAll("File").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all folders we rely on
                                doel.selectAll("Folder").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }

                                    OperationResult cres = FileUtil.copyFileTree(src, dest);

                                    if (cres.hasErrors())
                                        errored.set(true);
                                });
                            });

                    availpackages.get(pname).selectAll("IgnorePaths/Ignore")
                            .forEach(doel -> ignorepaths.addItem(doel.getAttribute("Path")));

                    // NoLongerDependsOn functionally currently only applies to libraries
                    availpackages.get(pname).selectAll("NoLongerDependsOn/Library")
                            .forEach(doel -> nolongerdepends.add(doel.getAttribute("File")));

                    // copy the released packages folders
                    Path src = Paths.get("./packages/" + pname);
                    Path dest = tempfolder.resolve("packages/" + pname);

                    try {
                        Files.createDirectories(dest.getParent());
                    } catch (Exception x) {
                        errored.set(true);
                        System.out.println("Unable to copy file: " + src);
                    }

                    // we may wish to enhance filter to allow .JAR sometimes, but this is meant to prevent copying of packages/pname/lib/abc.lib.jar files 
                    OperationResult cres = FileUtil.copyFileTree(src, dest,
                            path -> !path.toString().endsWith(".jar"));

                    if (cres.hasErrors())
                        errored.set(true);

                    // copy the released packages libraries
                    Path libsrc = Paths.get("./packages/" + pname + "/lib");
                    Path libdest = tempfolder.resolve("lib");

                    if (Files.exists(libsrc)) {
                        cres = FileUtil.copyFileTree(libsrc, libdest);

                        if (cres.hasErrors())
                            errored.set(true);
                    }
                });

                if (errored.get()) {
                    System.out.println("Error with assembling package");
                    break;
                }

                // copy the principle config
                Path csrc = Paths.get("./packages/" + inst.prinpackage + "/config");
                Path cdest = tempfolder.resolve("config/" + inst.prinpackagenm);

                if (Files.exists(csrc)) {
                    Files.createDirectories(cdest);

                    OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                    if (cres.hasErrors()) {
                        System.out.println("Error with prepping config");
                        break;
                    }
                }

                boolean configpassed = true;

                // copy packages with config = true
                for (XElement pkg : relchoice.selectAll("Package")) {
                    if (!"true".equals(pkg.getAttribute("Config")))
                        break;

                    String pname = pkg.getAttribute("Name");

                    int pspos = pname.lastIndexOf('/');
                    String pnm = (pspos != -1) ? pname.substring(pspos + 1) : pname;

                    csrc = Paths.get("./packages/" + pname + "/config");
                    cdest = tempfolder.resolve("config/" + pnm);

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping extra config");
                            configpassed = false;
                            break;
                        }
                    }
                }

                if (!configpassed)
                    break;

                // also copy installer config if being used
                if (inst.includeinstaller) {
                    csrc = Paths.get("./packages/dc/dcInstall/config");
                    cdest = tempfolder.resolve("config/dcInstall");

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping install config");
                            break;
                        }
                    }
                }

                // write out the deployed file
                RecordStruct deployed = new RecordStruct();

                deployed.setField("Version", relvers);
                deployed.setField("PackageFolder", relpath.resolve(rname));
                deployed.setField("PackagePrefix", rname);

                OperationResult d1res = IOUtil.saveEntireFile(tempfolder.resolve("config/deployed.json"),
                        deployed.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployed");
                    break;
                }

                RecordStruct deployment = new RecordStruct();

                deployment.setField("Version", relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    deployment.setField("DependsOn", prindesc.getAttribute("LastVersion"));

                deployment.setField("UpdateMessage",
                        "This update is complete, you may accept this update as runnable.");

                nolongerdepends.removeAll(dependson);

                ListStruct deletefiles = new ListStruct();

                nolongerdepends.forEach(fname -> deletefiles.addItem("lib/" + fname));

                deployment.setField("DeleteFiles", deletefiles);
                deployment.setField("IgnorePaths", ignorepaths);

                d1res = IOUtil.saveEntireFile(tempfolder.resolve("deployment.json"),
                        deployment.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployment");
                    break;
                }

                // write env file
                d1res = IOUtil.saveEntireFile(tempfolder.resolve("env.bat"), "set mem="
                        + relchoice.getAttribute("Memory", "2048") + "\r\n" + "SET project="
                        + inst.prinpackagenm + "\r\n" + "SET service="
                        + relchoice.getAttribute("Service", inst.prinpackagenm) + "\r\n" + "SET servicename="
                        + relchoice.getAttribute("ServiceName", inst.prinpackagenm + " Service") + "\r\n");

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping env");
                    break;
                }

                System.out.println("Packing Release file.");

                Path relbin = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.notExists(relbin.getParent()))
                    Files.createDirectories(relbin.getParent());

                ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                try {
                    Files.walkFileTree(tempfolder, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                            new SimpleFileVisitor<Path>() {
                                @Override
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                        throws IOException {
                                    ZipArchiveEntry entry = new ZipArchiveEntry(
                                            tempfolder.relativize(file).toString());
                                    entry.setSize(Files.size(file));
                                    zipout.putArchiveEntry(entry);
                                    zipout.write(Files.readAllBytes(file));
                                    zipout.closeArchiveEntry();

                                    return FileVisitResult.CONTINUE;
                                }
                            });
                } catch (IOException x) {
                    System.out.println("Error building zip: " + x);
                }

                zipout.close();

                System.out.println("Release file written");

                FileUtil.deleteDirectory(tempfolder);

                break;
            } // end case 1

            case 3: {
                System.out.println("Note these utilities are only good from the main console,");
                System.out.println("if you are using a remote connection then the encryption will");
                System.out.println("not work as expected.  [we do not have access the master keys]");
                System.out.println();

                Foreground.utilityMenu(scan);

                break;
            }

            case 4: {
                System.out.println("Packing jar library files.");

                String[] packlist = new String[] { "divconq.core", "divconq.interchange", "divconq.web",
                        "divconq.tasks", "divconq.tasks.api", "ncc.uploader.api", "ncc.uploader.core",
                        "ncc.workflow", "sd.core" };

                String[] packnames = new String[] { "dcCore", "dcInterchange", "dcWeb", "dcTasks", "dcTasksApi",
                        "nccUploaderApi", "nccUploader", "nccWorkflow", "sd/sdBackend" };

                for (int i = 0; i < packlist.length; i++) {
                    String lib = packlist[i];
                    String pname = packnames[i];

                    Path relbin = Paths.get("./ext/" + lib + ".jar");
                    Path srcbin = Paths.get("./" + lib + "/bin");
                    Path packbin = Paths.get("./packages/" + pname + "/lib/" + lib + ".jar");

                    if (Files.notExists(relbin.getParent()))
                        Files.createDirectories(relbin.getParent());

                    Files.deleteIfExists(relbin);

                    ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                    try {
                        Files.walkFileTree(srcbin, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                                new SimpleFileVisitor<Path>() {
                                    @Override
                                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                            throws IOException {
                                        ZipArchiveEntry entry = new ZipArchiveEntry(
                                                srcbin.relativize(file).toString());
                                        entry.setSize(Files.size(file));
                                        zipout.putArchiveEntry(entry);
                                        zipout.write(Files.readAllBytes(file));
                                        zipout.closeArchiveEntry();

                                        return FileVisitResult.CONTINUE;
                                    }
                                });
                    } catch (IOException x) {
                        System.out.println("Error building zip: " + x);
                    }

                    zipout.close();

                    Files.copy(relbin, packbin, StandardCopyOption.REPLACE_EXISTING);
                }

                System.out.println("Done");

                break;
            }

            case 5: {
                System.out.println("Copying Source Files");

                System.out.println("Cleaning folders");

                OperationResult or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/resources"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("packages"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectoryContent(wikigitpath, ".git");

                if (or.hasErrors()) {
                    System.out.println("Error deleting wiki files");
                    break;
                }

                System.out.println("Copying folders");

                System.out.println("Copy tree ./divconq.core/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/divconq"),
                        gitpath.resolve("divconq.core/src/main/java/divconq"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/org"),
                        gitpath.resolve("divconq.core/src/main/java/org"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/localize"),
                        gitpath.resolve("divconq.core/src/main/resources/localize"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".xml");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.interchange/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.interchange/src"),
                        gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks/src"),
                        gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks.api/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks.api/src"),
                        gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.web/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.web/src"),
                        gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCore");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCore"), gitpath.resolve("packages/dcCore"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCorePublic");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCorePublic"),
                        gitpath.resolve("packages/dcCorePublic"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcInterchange");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcInterchange"),
                        gitpath.resolve("packages/dcInterchange"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasks");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasks"),
                        gitpath.resolve("packages/dcTasks"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksApi");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksApi"),
                        gitpath.resolve("packages/dcTasksApi"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksWeb"),
                        gitpath.resolve("packages/dcTasksWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTest");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTest"), gitpath.resolve("packages/dcTest"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcWeb"), gitpath.resolve("packages/dcWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.wiki/public");

                or = FileUtil.copyFileTree(Paths.get("./divconq.wiki/public"), wikigitpath);

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copying files");

                Files.copy(Paths.get("./README.md"), gitpath.resolve("README.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./RELEASE_NOTES.md"), gitpath.resolve("RELEASE_NOTES.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./NOTICE.txt"), gitpath.resolve("NOTICE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./LICENSE.txt"), gitpath.resolve("LICENSE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                System.out.println("Done");

                break;
            }
            case 6: {
                System.out.println("Are you sure you want to update AWWW Server? (y/n): ");
                if (!scan.nextLine().toLowerCase().startsWith("y"))
                    break;

                ReleasesHelper releases = new ReleasesHelper();
                if (!releases.init(relpath))
                    break;

                XElement relchoice = releases.get("AWWWServer");

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                ServerHelper ssh = new ServerHelper();
                if (!ssh.init(relchoice.find("SSH")))
                    break;

                ChannelSftp sftp = null;

                try {
                    Channel channel = ssh.session().openChannel("sftp");
                    channel.connect();
                    sftp = (ChannelSftp) channel;

                    // go to routines folder
                    sftp.cd("/usr/local/bin/dc/AWWWServer");

                    FileRepositoryBuilder builder = new FileRepositoryBuilder();

                    Repository repository = builder.setGitDir(new File(".git")).findGitDir() // scan up the file system tree
                            .build();

                    String lastsync = releases.getData("AWWWServer").getFieldAsString("LastCommitSync");

                    RevWalk rw = new RevWalk(repository);
                    ObjectId head1 = repository.resolve(Constants.HEAD);
                    RevCommit commit1 = rw.parseCommit(head1);

                    releases.getData("AWWWServer").setField("LastCommitSync", head1.name());

                    ObjectId rev2 = repository.resolve(lastsync);
                    RevCommit parent = rw.parseCommit(rev2);
                    //RevCommit parent2 = rw.parseCommit(parent.getParent(0).getId());

                    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
                    df.setRepository(repository);
                    df.setDiffComparator(RawTextComparator.DEFAULT);
                    df.setDetectRenames(true);

                    // list oldest first or change types are all wrong!!
                    List<DiffEntry> diffs = df.scan(parent.getTree(), commit1.getTree());

                    for (DiffEntry diff : diffs) {
                        String gnpath = diff.getNewPath();
                        String gopath = diff.getOldPath();

                        Path npath = Paths.get("./" + gnpath);
                        Path opath = Paths.get("./" + gopath);

                        if (diff.getChangeType() == ChangeType.DELETE) {
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if ((diff.getChangeType() == ChangeType.ADD)
                                || (diff.getChangeType() == ChangeType.MODIFY)
                                || (diff.getChangeType() == ChangeType.COPY)) {
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if (diff.getChangeType() == ChangeType.RENAME) {
                            // remove the old
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }

                            // add the new path
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else {
                            System.out.println("??????????????????????????????????????????????????????????");
                            System.out.println(": " + diff.getChangeType().name() + " - " + gnpath
                                    + " ?????????????????????????");
                            System.out.println("??????????????????????????????????????????????????????????");
                        }
                    }

                    rw.dispose();

                    repository.close();

                    releases.saveData();
                } catch (JSchException x) {
                    System.out.println("Sftp Error: " + x);
                } finally {
                    if (sftp.isConnected())
                        sftp.exit();

                    ssh.close();
                }

                break;
            }

            case 7: {
                Path sfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly");
                Path dfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly-js");

                Files.list(sfolder).forEach(file -> {
                    String fname = file.getFileName().toString();

                    if (!fname.endsWith(".xml"))
                        return;

                    FuncResult<XElement> lres = XmlReader.loadFile(file, false);

                    if (lres.isEmptyResult()) {
                        System.out.println("Unable to parse: " + file);
                        return;
                    }

                    String zc = fname.substring(5, 8);
                    String code = "zipsData['" + zc + "'] = ";
                    XElement root = lres.getResult();

                    /*
                    <polyline1 lng="-90.620897" lat="45.377447"/>
                    <polyline1 lng="-90.619327" lat="45.3805"/>
                            
                                   [-71.196845,41.67757],[-71.120168,41.496831],[-71.317338,41.474923],[-71.196845,41.67757]
                     */
                    ListStruct center = new ListStruct();
                    ListStruct cords = new ListStruct();
                    ListStruct currentPoly = null;
                    //String currentName = null;

                    for (XElement child : root.selectAll("*")) {
                        String cname = child.getName();

                        if (cname.startsWith("marker")) {
                            // not always accurate
                            if (center.isEmpty())
                                center.addItem(Struct.objectToDecimal(child.getAttribute("lng")),
                                        Struct.objectToDecimal(child.getAttribute("lat")));

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));

                            continue;
                        }

                        /*
                        if (cname.startsWith("info")) {
                           System.out.println("areas: " + child.getAttribute("areas"));
                           continue;
                        }
                        */

                        if (!cname.startsWith("polyline"))
                            continue;

                        if (currentPoly == null) {
                            //if (!cname.equals(currentName)) {
                            //if (currentName == null) {
                            //   currentName = cname;

                            //   System.out.println("new poly: " + cname);

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));
                        }

                        currentPoly.addItem(new ListStruct(Struct.objectToDecimal(child.getAttribute("lng")),
                                Struct.objectToDecimal(child.getAttribute("lat"))));
                    }

                    RecordStruct feat = new RecordStruct().withField("type", "Feature")
                            .withField("id", "zip" + zc)
                            .withField("properties",
                                    new RecordStruct().withField("name", "Prefix " + zc).withField("alias", zc))
                            .withField("geometry", new RecordStruct().withField("type", "MultiPolygon")
                                    .withField("coordinates", cords));

                    RecordStruct entry = new RecordStruct().withField("code", zc).withField("geo", feat)
                            .withField("center", center);

                    IOUtil.saveEntireFile2(dfolder.resolve("us-zips-" + zc + ".js"),
                            code + entry.toPrettyString() + ";");
                });

                break;
            }

            }
        } catch (Exception x) {
            System.out.println("CLI error: " + x);
        }
    }
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Writes the SignedDoc to an output file
 * and automatically calculates DataFile sizes
 * and digests//  w w w .ja  v  a 2  s .  c o m
 * @param outputFile output file name
 * @param fTempSdoc temporrary file, copy of original for copying items
 * @throws DigiDocException for all errors
 */
public void writeToStream(OutputStream os/*, File fTempSdoc*/) throws DigiDocException {
    DigiDocException ex1 = validateFormatAndVersion();
    if (ex1 != null)
        throw ex1;
    try {
        DigiDocXmlGenFactory genFac = new DigiDocXmlGenFactory(this);
        if (m_format.equals(SignedDoc.FORMAT_BDOC)) {
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("UTF-8");
            if (m_logger.isDebugEnabled())
                m_logger.debug("OS: " + ((os != null) ? "OK" : "NULL"));
            // write mimetype
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MIMET_FILE_NAME);
            ZipArchiveEntry ze = new ZipArchiveEntry(MIMET_FILE_NAME);
            if (m_comment == null)
                m_comment = DigiDocGenFactory.getUserInfo(m_format, m_version);
            ze.setComment(m_comment);
            ze.setMethod(ZipArchiveEntry.STORED);
            java.util.zip.CRC32 crc = new java.util.zip.CRC32();
            if (m_version.equals(BDOC_VERSION_1_0)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_10.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_11.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_20.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            ze.setCrc(crc.getValue());
            zos.putArchiveEntry(ze);
            if (m_version.equals(BDOC_VERSION_1_0)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            zos.closeArchiveEntry();
            // write manifest.xml
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MANIF_FILE_NAME);
            ze = new ZipArchiveEntry(MANIF_DIR_META_INF);
            ze = new ZipArchiveEntry(MANIF_FILE_NAME);
            ze.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
            zos.putArchiveEntry(ze);
            //if(m_logger.isDebugEnabled())
            //   m_logger.debug("Writing manif:\n" + m_manifest.toString());
            zos.write(m_manifest.toXML());
            zos.closeArchiveEntry();
            // write data files
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing DF: " + df.getFileName() + " content: " + df.getContentType()
                            + " df-cache: "
                            + ((df.getDfCacheFile() != null) ? df.getDfCacheFile().getAbsolutePath() : "NONE"));
                InputStream is = null;
                if (df.hasAccessToDataFile())
                    is = df.getBodyAsStream();
                else
                    is = findDataFileAsStream(df.getFileName());
                if (is != null) {
                    File dfFile = new File(df.getFileName());
                    String fileName = dfFile.getName();
                    ze = new ZipArchiveEntry(fileName);
                    if (df.getComment() == null)
                        df.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                    ze.setComment(df.getComment());
                    ze.setSize(dfFile.length());
                    ze.setTime(
                            (df.getLastModDt() != null) ? df.getLastModDt().getTime() : dfFile.lastModified());
                    zos.putArchiveEntry(ze);
                    byte[] data = new byte[2048];
                    int nRead = 0, nTotal = 0;
                    crc = new java.util.zip.CRC32();
                    while ((nRead = is.read(data)) > 0) {
                        zos.write(data, 0, nRead);
                        nTotal += nRead;
                        crc.update(data, 0, nRead);
                    }
                    ze.setSize(nTotal);
                    ze.setCrc(crc.getValue());
                    zos.closeArchiveEntry();
                    is.close();
                }
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                String sFileName = sig.getPath();
                if (sFileName == null) {
                    if (m_version.equals(BDOC_VERSION_2_1))
                        sFileName = SIG_FILE_NAME_20 + (i + 1) + ".xml";
                    else
                        sFileName = SIG_FILE_NAME + (i + 1) + ".xml";
                }
                if (!sFileName.startsWith("META-INF"))
                    sFileName = "META-INF/" + sFileName;
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " orig: "
                            + ((sig.getOrigContent() != null) ? "OK" : "NULL"));
                ze = new ZipArchiveEntry(sFileName);
                if (sig.getComment() == null)
                    sig.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                ze.setComment(sig.getComment());
                String sSig = null;
                if (sig.getOrigContent() != null)
                    sSig = new String(sig.getOrigContent(), "UTF-8");
                else
                    sSig = sig.toString();
                if (sSig != null && !sSig.startsWith("<?xml"))
                    sSig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sSig;
                byte[] sdata = sSig.getBytes("UTF-8");
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " xml:\n---\n "
                            + ((sSig != null) ? sSig : "NULL") + "\n---\n ");
                ze.setSize(sdata.length);
                crc = new java.util.zip.CRC32();
                crc.update(sdata);
                ze.setCrc(crc.getValue());
                zos.putArchiveEntry(ze);
                zos.write(sdata);
                zos.closeArchiveEntry();
            }
            zos.close();
        } else if (m_format.equals(SignedDoc.FORMAT_DIGIDOC_XML)) { // ddoc format
            os.write(xmlHeader().getBytes());
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                df.writeToFile(os);
                os.write("\n".getBytes());
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                if (sig.getOrigContent() != null)
                    os.write(sig.getOrigContent());
                else
                    os.write(genFac.signatureToXML(sig));
                os.write("\n".getBytes());
            }
            os.write(xmlTrailer().getBytes());
        }
    } catch (DigiDocException ex) {
        throw ex; // allready handled
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_WRITE_FILE);
    }
}

From source file:com.eucalyptus.www.X509Download.java

private static byte[] getX509Zip(User u) throws Exception {
    X509Certificate cloudCert = null;
    final X509Certificate x509;
    String userAccessKey = null;/* w  w  w.  j  a  v  a  2s .  com*/
    String userSecretKey = null;
    KeyPair keyPair = null;
    try {
        for (AccessKey k : u.getKeys()) {
            if (k.isActive()) {
                userAccessKey = k.getAccessKey();
                userSecretKey = k.getSecretKey();
            }
        }
        if (userAccessKey == null) {
            AccessKey k = u.createKey();
            userAccessKey = k.getAccessKey();
            userSecretKey = k.getSecretKey();
        }
        keyPair = Certs.generateKeyPair();
        x509 = Certs.generateCertificate(keyPair, u.getName());
        x509.checkValidity();
        u.addCertificate(x509);
        cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate();
    } catch (Exception e) {
        LOG.fatal(e, e);
        throw e;
    }
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut);
    ZipArchiveEntry entry = null;
    String fingerPrint = Certs.getFingerPrint(keyPair.getPublic());
    if (fingerPrint != null) {
        String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-"
                + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8);

        zipOut.setComment("To setup the environment run: source /path/to/eucarc");
        StringBuilder sb = new StringBuilder();
        //TODO:GRZE:FIXME velocity
        String userNumber = u.getAccount().getAccountNumber();
        sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)");
        final Optional<String> computeUrl = remotePublicify(Compute.class);
        if (computeUrl.isPresent()) {
            sb.append(entryFor("EC2_URL", null, computeUrl));
        } else {
            sb.append("\necho WARN:  Eucalyptus URL is not configured. >&2");
            ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class);
            ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(),
                    Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort());
            sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig));
        }

        sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. "
                + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. "
                + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage",
                remotePublicify(ObjectStorage.class)));
        sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class)));
        sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class)));
        sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.",
                remotePublicify(AutoScaling.class)));
        sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class)));
        sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.",
                remotePublicify(CloudWatch.class)));
        sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.",
                remotePublicify(LoadBalancing.class)));
        sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL);
        sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem");
        sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem");
        sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts");
        sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem");
        sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'");
        sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'");
        sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'");
        sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'");
        sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'");
        sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc");
        sb.append("\nexport EC2_USER_ID='" + userNumber + "'");
        sb.append(
                "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\"");
        sb.append(
                "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\"");
        sb.append("\n");
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc"));
        entry.setUnixMode(0600);
        zipOut.write(sb.toString().getBytes("UTF-8"));
        zipOut.closeArchiveEntry();

        sb = new StringBuilder();
        sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n');
        sb.append("AWSSecretKey=").append(userSecretKey);
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc"));
        entry.setUnixMode(0600);
        zipOut.write(sb.toString().getBytes("UTF-8"));
        zipOut.closeArchiveEntry();

        /** write the private key to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes(cloudCert));
        zipOut.closeArchiveEntry();

        zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts"));
        entry.setUnixMode(0600);
        KeyStore tempKs = KeyStore.getInstance("jks");
        tempKs.load(null);
        tempKs.setCertificateEntry("eucalyptus", cloudCert);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        tempKs.store(bos, "changeit".toCharArray());
        zipOut.write(bos.toByteArray());
        zipOut.closeArchiveEntry();

        /** write the private key to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY",
                Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate())));
        zipOut.closeArchiveEntry();

        /** write the X509 certificate to the zip stream **/
        zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem"));
        entry.setUnixMode(0600);
        zipOut.write(PEMFiles.getBytes(x509));
        zipOut.closeArchiveEntry();
    }
    /** close the zip output stream and return the bytes **/
    zipOut.close();
    return byteOut.toByteArray();
}