Example usage for org.apache.commons.compress.archivers.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

From source file:org.cytobank.acs.core.ACS.java

/**
 * Writes out a file contained within this <code>ACS</code> instance to the
 * specified <code>OutputStream</code>.
 * //w w  w .j a  va  2s. c  o  m
 * @param filePath
 *            the <code>String</code> path representing a file within this
 *            <code>ACS</code> instance.
 * @param outputStream
 *            to write the requested file to
 * @throws IOException
 *             If an input or output exception occurred
 */
public void extractFile(String filePath, OutputStream outputStream) throws IOException {
    ZipFile zipFile = new ZipFile(acsFile);

    if (filePath.startsWith("/"))
        filePath = filePath.substring(1);

    InputStream inputStream = null;
    ZipArchiveEntry entry = zipFile.getEntry(filePath);
    try {
        if (entry == null)
            throw new IOException("Could not find zip file entry " + filePath);

        inputStream = zipFile.getInputStream(entry);
        IOUtils.copy(inputStream, outputStream);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ignore) {
        }

        try {
            zipFile.close();
        } catch (IOException ignore) {
        }
    }

}

From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace.ArchiveUtil.java

private static ZipFile getSpecifiedZipSourceFile(String fileName) {
    if (fileName.length() == 0) {
        return null;
    }/*from  w w  w. j a  v  a 2  s .  c om*/

    File file = new File(fileName);
    if (file.isDirectory()) {
        return null;
    }

    try {
        return new ZipFile(file);
    } catch (IOException e) {
        // ignore
    }

    return null;
}

From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.tracepkg.AbstractTracePackageOperation.java

/**
 * Answer a handle to the archive file currently specified as being the
 * source. Return null if this file does not exist or is not of valid
 * format.//  w w w  .  jav  a2s.  co  m
 *
 * @return the archive file
 */
public ArchiveFile getSpecifiedArchiveFile() {
    if (fFileName.length() == 0) {
        return null;
    }

    File file = new File(fFileName);
    if (file.isDirectory()) {
        return null;
    }

    try {
        return new ZipArchiveFile(new ZipFile(file));
    } catch (IOException e) {
        // ignore
    }

    try {
        return new TarArchiveFile(new TarFile(file));
    } catch (IOException e) {
        // ignore
    }

    return null;
}

From source file:org.epics.archiverappliance.etl.ConsolidateETLJobsForOnePVTest.java

@SuppressWarnings("deprecation")
private void Consolidate() throws AlreadyRegisteredException, IOException, InterruptedException {
    PVTypeInfo typeInfo = new PVTypeInfo(pvName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
    String[] dataStores = new String[] { storageplugin1.getURLRepresentation(),
            storageplugin2.getURLRepresentation(), storageplugin3.getURLRepresentation() };
    typeInfo.setDataStores(dataStores);//from  www . ja va  2 s .c  o  m
    configService.updateTypeInfoForPV(pvName, typeInfo);
    configService.registerPVToAppliance(pvName, configService.getMyApplianceInfo());
    configService.getETLLookup().manualControlForUnitTests();
    //generate datas of 10 days PB file 2012_01_01.pb  to 2012_01_10.pb
    int dayCount = 10;
    for (int day = 0; day < dayCount; day++) {
        logger.debug("Generating data for day " + 1);
        int startofdayinseconds = day * 24 * 60 * 60;
        int runsperday = 12;
        int eventsperrun = 24 * 60 * 60 / runsperday;
        for (int currentrun = 0; currentrun < runsperday; currentrun++) {
            try (BasicContext context = new BasicContext()) {
                logger.debug("Generating data for run " + currentrun);

                YearSecondTimestamp yts = new YearSecondTimestamp(currentYear, (day + 1) * 24 * 60 * 60, 0);
                Timestamp etlTime = TimeUtils.convertFromYearSecondTimestamp(yts);
                logger.debug("Running ETL as if it were " + TimeUtils.convertToHumanReadableString(etlTime));
                ETLExecutor.runETLs(configService, etlTime);
                ArrayListEventStream testData = new ArrayListEventStream(eventsperrun,
                        new RemotableEventStreamDesc(type, pvName, currentYear));
                for (int secondsinrun = 0; secondsinrun < eventsperrun; secondsinrun++) {
                    testData.add(
                            new SimulationEvent(startofdayinseconds + currentrun * eventsperrun + secondsinrun,
                                    currentYear, type, new ScalarValue<Double>((double) secondsinrun)));
                }
                storageplugin1.appendData(context, pvName, testData);
            }
            // Sleep for a couple of seconds so that the modification times are different.
            Thread.sleep(2 * 1000);
        }
    } // end for 

    File shortTermFIle = new File(shortTermFolderName);
    File mediumTermFIle = new File(mediumTermFolderName);
    //File longTermFIle=new File(longTermFolderName);

    String[] filesShortTerm = shortTermFIle.list();
    String[] filesMediumTerm = mediumTermFIle.list();
    assertTrue("there should be PB files int short term storage but there is no ", filesShortTerm.length != 0);
    assertTrue("there should be PB files int medium term storage but there is no ",
            filesMediumTerm.length != 0);
    //ArchUnitTestConsolidateETLJobsForOnePVTest:_pb.zip
    File zipFileOflongTermFile = new File(longTermFolderName + "/" + pvName + ":_pb.zip");
    assertTrue(longTermFolderName + "/" + pvName + ":_pb.zip shoule exist but it doesn't",
            zipFileOflongTermFile.exists());
    ZipFile lastZipFile1 = new ZipFile(zipFileOflongTermFile);
    Enumeration<ZipArchiveEntry> enumeration1 = lastZipFile1.getEntries();
    int ss = 0;
    while (enumeration1.hasMoreElements()) {
        enumeration1.nextElement();
        ss++;
    }
    assertTrue(
            "the zip file of " + longTermFolderName + "/" + pvName
                    + ":_pb.zip should contain pb files less than " + dayCount + ",but the number is " + ss,
            ss < dayCount);
    // consolidate
    String storageName = "LTS";
    Timestamp oneYearLaterTimeStamp = TimeUtils
            .convertFromEpochSeconds(TimeUtils.getCurrentEpochSeconds() + 365 * 24 * 60 * 60, 0);
    // The ConfigServiceForTests automatically adds a ETL Job for each PV. For consolidate, we need to have "paused" the PV; we fake this by deleting the jobs.
    configService.getETLLookup().deleteETLJobs(pvName);
    ETLExecutor.runPvETLsBeforeOneStorage(configService, oneYearLaterTimeStamp, pvName, storageName);
    // make sure there are no pb files in short term storage , medium term storage and all files in long term storage
    Thread.sleep(4000);
    String[] filesShortTerm2 = shortTermFIle.list();
    String[] filesMediumTerm2 = mediumTermFIle.list();
    assertTrue("there should be no files int short term storage but there are still " + filesShortTerm2.length
            + "PB files", filesShortTerm2.length == 0);
    assertTrue("there should be no files int medium term storage but there are still " + filesMediumTerm2.length
            + "PB files", filesMediumTerm2.length == 0);
    //ArchUnitTestConsolidateETLJobsForOnePVTest:_pb.zip
    File zipFileOflongTermFile2 = new File(longTermFolderName + "/" + pvName + ":_pb.zip");
    assertTrue(longTermFolderName + "/" + pvName + ":_pb.zip shoule exist but it doesn't",
            zipFileOflongTermFile2.exists());

    ZipFile lastZipFile = new ZipFile(zipFileOflongTermFile2);
    Enumeration<ZipArchiveEntry> enumeration = lastZipFile.getEntries();
    ZipEntry zipEntry = null;
    HashMap<String, String> fileNameMap = new HashMap<String, String>();
    while (enumeration.hasMoreElements()) {
        zipEntry = (ZipEntry) enumeration.nextElement();

        String fileNameTemp = zipEntry.getName();
        logger.info("fileName1=" + fileNameTemp);

        int indexPB = fileNameTemp.indexOf(".pb");
        int indexDate = indexPB - 5;
        String dateFileName = fileNameTemp.substring(indexDate, indexPB);
        fileNameMap.put(dateFileName, dateFileName);
        //System.out.println("fileName="+dateFileName);
        logger.info("fileName=" + dateFileName);
    }

    assertTrue("The number of files should be " + dayCount + ", acutuallly, it is " + fileNameMap.size(),
            fileNameMap.size() == dayCount);
    Date beinningDate = new Date();
    beinningDate.setYear(currentYear - 1);
    beinningDate.setMonth(11);
    beinningDate.setDate(31);
    logger.info("currentYear=" + currentYear);
    logger.info("beinningDate=" + beinningDate);
    Calendar calendarBeingining = Calendar.getInstance();
    calendarBeingining.setTime(beinningDate);
    SimpleDateFormat df = new SimpleDateFormat("MM_dd");
    for (int m = 0; m < dayCount; m++) {
        calendarBeingining.add(Calendar.DAY_OF_MONTH, 1);
        String fileNameTemp1 = df.format(calendarBeingining.getTime());
        logger.info("fileNameTemp1=" + fileNameTemp1);
        assertTrue("the file  whose name is like " + pvName + ":" + currentYear + "_" + fileNameTemp1
                + ".pb should exist,but it doesn't", fileNameMap.get(fileNameTemp1) != null);
    }

}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

public final void unpackZipFile(final File file, final File destinationDirectory) throws IOException {
    destinationDirectory.mkdirs();//from  w  w w .j a v a 2 s  .  c om
    ZipFile zipFile = new ZipFile(file);

    try {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String name = entry.getName();
            File destFile = new File(destinationDirectory, name);
            if (entry.isDirectory()) {
                destFile.mkdirs();
            } else {
                File parentFolder = destFile.getParentFile();
                parentFolder.mkdirs();
                InputStream inputStream = zipFile.getInputStream(entry);
                overCopyFile(inputStream, destFile);
                FileManager.setPermissionsOnFile(destFile, entry);
            }

        }
    } finally {
        zipFile.close();
    }
}

From source file:org.fabrician.maven.plugins.CompressUtils.java

public static void copyZipToArchiveOutputStream(File zipSrc, FilenamePatternFilter filter,
        ArchiveOutputStream out, String alternateBaseDir) throws IOException {
    ZipFile zip = new ZipFile(zipSrc);
    for (Enumeration<ZipArchiveEntry> zipEnum = zip.getEntries(); zipEnum.hasMoreElements();) {
        ZipArchiveEntry source = zipEnum.nextElement();
        if (filter != null && !filter.accept(source.getName())) {
            System.out.println("Excluding " + source.getName());
            continue;
        }//from  ww  w  .j a  v  a 2s .  c  om
        InputStream in = null;
        try {
            in = zip.getInputStream(source);
            out.putArchiveEntry(createArchiveEntry(source, out, alternateBaseDir));
            IOUtils.copy(in, out);
            out.closeArchiveEntry();
        } finally {
            close(in);
        }
    }
}

From source file:org.fabrician.maven.plugins.CompressUtils.java

public static boolean entryExistsInZip(File zipFile, String entryName) throws IOException {
    ZipFile zip = new ZipFile(zipFile);
    for (Enumeration<ZipArchiveEntry> zipEnum = zip.getEntries(); zipEnum.hasMoreElements();) {
        ZipArchiveEntry source = zipEnum.nextElement();
        if (source.getName().equals(entryName)) {
            return true;
        }// w ww.ja va 2  s . c o m
    }
    return false;
}

From source file:org.itstechupnorth.walrus.text.GutenburgParser.java

private Reader open() throws IOException, ZipException, FileNotFoundException, UnsupportedEncodingException {
    final Reader reader;
    final InputStream input;
    if (FilenameUtils.isExtension(file.getName(), ZIP)) {
        try {/*from ww w  .  jav  a2s .co m*/
            final ZipFile zip = new ZipFile(file);
            input = zip.getInputStream((ZipArchiveEntry) zip.getEntries().nextElement());
        } catch (IllegalArgumentException e) {
            throw new RuntimeWarningException(e.getMessage() + "(" + file + ")", e);
        }
    } else {
        input = new FileInputStream(file);
    }
    reader = new InputStreamReader(new BufferedInputStream(input), "UTF-8");
    return reader;
}

From source file:org.itstechupnorth.walrus.zip.Archive.java

public Archive open() throws IOException {
    zip = new ZipFile(this.file);
    return this;
}

From source file:org.itstechupnorth.walrus.zip.ArchiveManagerTest.java

public void testOneRound() throws Exception {

    final File file = file("round.zip");
    ArchiveSaver manager = new ArchiveSaver(file);
    manager.open();//  w  ww  .j ava 2s . c  o m
    ArticleBuffer buffer = new ArticleBuffer();
    final String title = "Hello";
    buffer.title(title.toCharArray(), 0, 5);
    buffer.text("World".toCharArray(), 0, 5);
    manager.save(buffer);
    manager.close();

    ZipFile zip = new ZipFile(file);
    assertEquals("UTF8", zip.getEncoding());
    @SuppressWarnings("rawtypes")
    final Enumeration entries = zip.getEntries();
    assertEquals(true, entries.hasMoreElements());
    final ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
    assertEquals(title, entry.getComment());
    assertEquals(false, entries.hasMoreElements());
}