Example usage for org.apache.commons.compress.archivers ArchiveOutputStream closeArchiveEntry

List of usage examples for org.apache.commons.compress.archivers ArchiveOutputStream closeArchiveEntry

Introduction

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

Prototype

public abstract void closeArchiveEntry() throws IOException;

Source Link

Document

Closes the archive entry, writing any trailer information that may be required.

Usage

From source file:de.fischer.thotti.core.distbuilder.DistributionBuilder.java

public File buildDistribution() throws Exception, ArchiveException {
    String mahoutVersion = org.apache.mahout.Version.version();
    // @todo Throw an exception if the distfile cannot created
    File output = targetFile;//from w ww  . j a  v a  2 s . c  om

    Set<String> addedFiles = new HashSet<String>();

    List<FetchResult> fetchedArtifacts = depFetcher.fetchDependencies();

    final OutputStream out = new FileOutputStream(output);
    ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    String subDirectory;

    for (FetchResult fetch : fetchedArtifacts) {
        String coord = fetch.getArtifactCoordinates();

        // @todo This is not safe! It is a hack!
        if (coord.split(":")[0].equals(MAHOUT_GROUP_ID)) {
            subDirectory = MAHOUT_LIB_DIRECTORY;
        } else {
            subDirectory = EXTERNAL_LIB_DIRECTORY;
        }

        for (File file : fetch.getFiles()) {
            String targetCP = subDirectory + "/" + file.getName();
            String targetArchive = BASE_DIRECTORY + "/" + targetCP;

            if (!addedFiles.contains(targetCP)) {
                cpBuilder.addPath(targetCP);

                if (getListener() != null) {
                    StringBuilder sb = new StringBuilder();

                    sb.append("Add: ").append(file.toURI()).append(" as ").append(targetCP);

                    getListener().onAddingMavenArtifact(sb.toString());
                }

                os.putArchiveEntry(new ZipArchiveEntry(targetArchive));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();

                addedFiles.add(targetCP);
            }
        }
    }

    cpBuilder.addPath(DATA_DIRECTORY);

    for (File file : dataFiles) {
        String targetCP = DATA_DIRECTORY + "/" + file.getName();
        String targetArchive = BASE_DIRECTORY + "/" + targetCP;

        if (getListener() != null) {
            StringBuilder sb = new StringBuilder();

            sb.append("Add: ").append(file.toURI()).append(" as ").append(targetCP);

            getListener().onAddingTestData(sb.toString());
        }

        os.putArchiveEntry(new ZipArchiveEntry(targetArchive));
        IOUtils.copy(new FileInputStream(file), os);
        os.closeArchiveEntry();
    }

    String testCaseTargetCP = TEST_CASE_LIB_DIRECTORY + "/" + testArtifact.getName();
    String testCaseTargetArchive = BASE_DIRECTORY + "/" + testCaseTargetCP;

    if (getListener() != null) {
        StringBuilder sb = new StringBuilder();

        sb.append("Add: ").append(testArtifact.toURI()).append(" as ").append(testCaseTargetCP);

        listener.onAddingTestCases(sb.toString());
    }

    os.putArchiveEntry(new ZipArchiveEntry(testCaseTargetArchive));
    IOUtils.copy(new FileInputStream(testArtifact), os);
    os.closeArchiveEntry();

    cpBuilder.addPath(testCaseTargetCP);

    generateRunSkript(os);

    out.flush();
    os.close();

    return output;
}

From source file:big.BigZip.java

/**
  * Copies one file into the big archive
  * @param fileToCopy/* ww  w .  j  av  a 2  s .c o  m*/
  * @return 
  */
public boolean writeFile(final File fileToCopy) {

    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    try {
        /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        /* Create Archieve entry - write header information*/
        logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName()));
        /* Copy input file */
        IOUtils.copy(new FileInputStream(fileToCopy), logical_zip);
        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }
        // if there is something else to be flushed, do it now
        outputStream.flush();

        // calculate the base path
        final String resultingPath = fileToCopy.getAbsolutePath().replace(basePath, "");

        // calculate the SHA1 signature
        final String output = utils.hashing.checksum.generateFileChecksum("SHA-1", fileToCopy);

        // write a new line in our index file
        writerFileIndex.write(
                "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + output + " " + resultingPath);
        // increase the position counter
        currentPosition += counter + magicSignature.length();
    } catch (Exception e) {
        System.err.println("BIG346 - Error copying file: " + fileToCopy.getAbsolutePath());
        return false;
    }

    finally {
    }
    return true;
}

From source file:big.BigZip.java

/**
 * Copies one file into the big archive/*w  ww.j  av  a 2s. c o m*/
 * @param fileToCopy
 * @param SHA1
 * @param filePathToWriteInTextLine
 * @return 
 */
public boolean quickWrite(final File fileToCopy, final String SHA1, final String filePathToWriteInTextLine) {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    try {
        // save this operation on the log of commits
        addTagStarted(fileToCopy.getName());
        //pointRestoreAndSave(fileToCopy);

        /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        /* Create Archieve entry - write header information*/
        logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName()));
        /* Copy input file */
        IOUtils.copy(new FileInputStream(fileToCopy), logical_zip);
        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }
        // if there is something else to be flushed, do it now
        //outputStream.flush();

        // calculate the base path
        //final String resultingPath = fileToCopy.getAbsolutePath().replace(rootFolder, "");

        final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " "
                + filePathToWriteInTextLine;

        // write a new line in our index file
        writerFileIndex.write(line);
        //writer.flush();
        // increase the position counter
        currentPosition += counter + magicSignature.length();

        // close the log with success
        addTagEnded();
    } catch (Exception e) {
        System.err.println("BIG600 - Error copying file: " + fileToCopy.getAbsolutePath());
        return false;
    } finally {
    }
    return true;
}

From source file:big.BigZip.java

/**
 * Copies one file into the big archive/* w  w  w.j  a  v a  2 s . c o  m*/
 * @param stream
 * @param SHA1
 * @param filePathToWriteInTextLine
 * @return 
 * @throws java.io.IOException 
 */
public boolean quickWriteGenericStream(final InputStream stream, final String SHA1,
        final String filePathToWriteInTextLine) throws IOException {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    ByteArrayInputStream byteInput = null;
    try {
        // save this operation on the log of commits
        addTagStarted(filePathToWriteInTextLine);
        // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        // Create Archive entry - write header information
        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine);
        logical_zip.putArchiveEntry(zipArchiveEntry);
        // Copy input file

        IOUtils.copy(stream, logical_zip);

        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }

        final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " "
                + filePathToWriteInTextLine;

        // write a new line in our index file
        writerFileIndex.write(line);
        //writer.flush();
        // increase the position counter
        currentPosition += counter + magicSignature.length();

        // close the log with success
        addTagEnded();
    } catch (Exception e) {
        System.err.println("BIG600 - Error copying file: " + filePathToWriteInTextLine);
        return false;
    } finally {
        if (byteInput != null) {
            byteInput.close();
        }
        stream.close();
        outputZipStream.close();
        outputStream.close();
    }
    return true;
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeAllPagesFile(String tname, Map<String, String> id2Title, ArchiveOutputStream out) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "?");
    htmlHeader = htmlHeader.replace("../aone.css", "./aone.css");
    StringBuilder sb = new StringBuilder();
    sb.append(htmlHeader);/*  w  w  w .  j  a  v a2  s .  co m*/
    sb.append("<body><h1>?</h1><ul>");
    for (Entry<String, String> entry : id2Title.entrySet()) {
        sb.append("<li><a target=\"pageFrame\" href=\"").append(entry.getKey()).append("\">")
                .append(entry.getValue()).append("</a></li>");
    }
    sb.append("</ul></body>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/allPages.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export all collections in the repository.
 * //  w w  w . j  av a2s.c  o  m
 * @param repository - repository to export
 * @throws IOException 
 */
public void export(Repository repository, File zipFileDestination) throws IOException {
    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, repository.getInstitutionalCollections(),
            true);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export the specified institutional collection.
 * /*from   w ww  .ja va 2  s.co  m*/
 * @param collection - collection to export
 * @param includeChildren - if true children should be exported
 * @param zipFileDestination - zip file destination to store the collection information
 * @throws IOException 
 */
public void export(InstitutionalCollection collection, boolean includeChildren, File zipFileDestination)
        throws IOException {

    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    List<InstitutionalCollection> collections = new LinkedList<InstitutionalCollection>();
    collections.add(collection);
    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, collections, includeChildren);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeOverview(String tname, Map<String, List<Tag>> tagMap, ArchiveOutputStream out,
        VWBContext context, boolean isEpub) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "" + tname);
    htmlHeader = htmlHeader.replaceAll("[\\.]{2}", "\\.");

    StringBuilder sb = new StringBuilder();
    if (isEpub) {
        sb.append(EPUB_XML_HEADER);//from w w w. j a  v a  2 s.co  m
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        writeOverviewItemByTag(context, tagMap, sb, true);
    } else {
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        writeOverviewItemByTag(context, tagMap, sb, false);
    }
    sb.append("</ul></body></html>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/overview.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeOverview(String tag, String tname, int[] rids, ArchiveOutputStream out, VWBContext context,
        boolean isEpub) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "" + tname);
    htmlHeader = htmlHeader.replaceAll("[\\.]{2}", "\\.");

    StringBuilder sb = new StringBuilder();
    if (isEpub) {
        sb.append(EPUB_XML_HEADER);/*from www . j a v  a2 s  .c o m*/
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        for (int rid : rids) {
            writeOverviewItemByResource(context, rid, sb, tag, tname, true);
        }
    } else {
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        for (int rid : rids) {
            writeOverviewItemByResource(context, rid, sb, tag, tname, false);
        }
    }
    sb.append("</ul></body></html>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/overview.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writePage(String path, int resourceId, VWBContext context, ArchiveOutputStream out,
        Map<String, String> id2Title, List<String> allPages, boolean isEpub) {
    Resource page = resourceService.getResource(resourceId);
    StringBuilder sbuf = new StringBuilder();
    String pagePath = path + "/" + resourceId + ".html";
    if (null != page) {
        String resKey = "" + page.getRid() + "_" + page.getTid() + "_" + LynxConstants.TYPE_PAGE;
        if (null != getResTagPath(resKey)) { // ??
            return;
        }//from  w  ww  .j  av  a 2  s .c o  m
        downResPath.put(resKey, pagePath);
        String html = renderingService.getHTML(context, page);
        // site.getHTML(context, page);
        sbuf.append(getHtmlHeader(page, isEpub));
        sbuf.append("<h1 class=\"title\">" + page.getTitle() + "</h1>");
        sbuf.append(getProcessedHtml(html, context, path, out, id2Title, allPages, isEpub));// ?????
        sbuf.append(getHtmlFooter());
    } else {
        sbuf.append(getPageNotFoundHtml(resourceId, isEpub));
    }
    InputStream in = new ByteArrayInputStream(sbuf.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(pagePath));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    String tagname = path.substring(path.indexOf('/') + 1);
    String title = (null == page) ? FAKE_PAGE_TITLE : page.getTitle();
    id2Title.put(tagname + "/" + resourceId + ".html", title);
    if (allPages != null) {
        allPages.add(tagname + "/" + resourceId + ".html");
    }
}