Example usage for java.util.zip ZipInputStream getNextEntry

List of usage examples for java.util.zip ZipInputStream getNextEntry

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream getNextEntry.

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolManager.java

/**
 * Unzip the given file into the given directory.
 *
 * @param zipFile The zip file to unzip.
 * @param unzipped The directory to put the unzipped files into.
 * @throws IOException on file system error.
 *//*from  w  ww .  j a  v  a  2 s.  com*/
private void unzip(final File zipFile, final File unzipped) throws IOException {

    ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
    try {

        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            Path path = new Path(entry.getName());

            File dest = new File(unzipped, path.toOSString());
            if (entry.isDirectory()) {
                if (!dest.mkdirs()) {
                    throw new RuntimeException("Failed to create directory while unzipping");
                }
            } else {
                FileOutputStream output = new FileOutputStream(dest);
                try {
                    IOUtils.copy(zip, output);
                } finally {
                    output.close();
                }
            }
        }

    } finally {
        zip.close();
    }
}

From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java

@Override
public DocumentVisualization visualizeDocument(byte[] document, String language, List<MimeType> mimeTypes,
        String documentViewerServlet) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;//w ww .j a v a 2 s .c  om
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("<html>");
    stringBuffer.append("<head>");
    stringBuffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
    stringBuffer.append("<title>Associated Signature Container</title>");
    stringBuffer.append("</head>");
    stringBuffer.append("<body>");
    stringBuffer.append("<h1>Associated Signature Container</h1>");
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
            continue;
        }
        String zipEntryName = zipEntry.getName();
        if ("META-INF/container.xml".equals(zipEntryName)) {
            continue;
        }
        if ("META-INF/manifest.xml".equals(zipEntryName)) {
            continue;
        }
        if ("META-INF/metadata.xml".equals(zipEntryName)) {
            continue;
        }
        if ("mimetype".equals(zipEntryName)) {
            continue;
        }
        if (zipEntryName.startsWith("META-INF/")) {
            if (zipEntryName.endsWith(".xml")) {
                if (zipEntryName.indexOf("signatures") != -1) {
                    continue;
                }
            }
        }
        stringBuffer.append("<p>" + zipEntryName + "</p>");
    }
    stringBuffer.append("</body></html>");

    return new DocumentVisualization("text/html;charset=utf-8", stringBuffer.toString().getBytes());
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private void unzipFile(File file) {
    String zipFileFullPath = file.getPath();// path contains file name
    String zipFilePath = zipFileFullPath.substring(0, zipFileFullPath.indexOf(file.getName()));// path without file
                                                                                               // name
    ZipInputStream zin = null;
    try {/* w  w w .  ja  v  a2  s . com*/
        zin = new ZipInputStream(new FileInputStream(zipFileFullPath));
        ZipEntry zipEntry = null;
        byte[] buf = new byte[1024];

        while ((zipEntry = zin.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();
            String newPath = zipFilePath + File.separator
                    + file.getName().substring(0, file.getName().lastIndexOf(".")) + File.separator
                    + zipEntryName;// original path +
                                                                                                                                                                 // zipfile Name + entry
                                                                                                                                                                 // name
            File outfile = new File(newPath);
            if (zipEntry.isDirectory()) {
                outfile.mkdirs();
                continue;
            } else {
                if (!outfile.getParentFile().exists()) {
                    outfile.getParentFile().mkdirs();
                }
            }

            OutputStream os = new BufferedOutputStream(new FileOutputStream(outfile));
            int readLen = 0;
            try {
                readLen = zin.read(buf, 0, 1024);
            } catch (IOException ioe) {
                readLen = -1;
            }
            while (readLen != -1) {
                os.write(buf, 0, readLen);
                try {
                    readLen = zin.read(buf, 0, 1024);
                } catch (IOException ioe) {
                    readLen = -1;
                }
            }
            os.close();
        }
    } catch (IOException e) {
        s_logger.error("unzip file error.", e);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException e) {
                s_logger.error("Error occurs.", e);
            }
        }
    }
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

private String fileContents(File location, String filename) throws IOException {
    ZipInputStream zipIn = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//w  ww.  j a  v a 2 s.c  o  m
        zipIn = new ZipInputStream(new FileInputStream(location));
        while (zipIn.available() > 0) {
            ZipEntry nextEntry = zipIn.getNextEntry();
            if (nextEntry.getName().equals(filename)) {
                IOUtils.copy(zipIn, out);
            }
        }
    } finally {
        if (zipIn != null) {
            zipIn.close();
        }
    }
    return out.toString();
}

From source file:edu.harvard.iq.dvn.core.web.dataaccess.HttpAccessObject.java

public void open() throws IOException {

    StudyFile file = this.getFile();
    DataAccessRequest req = this.getRequest();

    if (req.getParameter("noVarHeader") != null) {
        this.setNoVarHeader(true);
    }// w  w  w .j  a  v  a2  s  .c o m

    try {
        this.studyService = (StudyServiceLocal) new InitialContext().lookup("java:comp/env/studyService");
    } catch (Exception e) {
        throw new IOException("Caught exception trying to look up studyService; " + e.getMessage());
    }

    String remoteFileUrl = file.getFileSystemLocation();

    if (remoteFileUrl != null) {
        remoteFileUrl = remoteFileUrl.replaceAll(" ", "+");
        this.setRemoteUrl(remoteFileUrl);
    }

    Boolean zippedStream = false;

    GetMethod method = null;
    int status = 200;

    try {

        // If it's another DVN from which we are getting
        // the file, we need to pass the "noVarHeader"
        // argument along:

        if (remoteFileUrl.matches(".*FileDownload.*")) {
            if (this.noVarHeader()) {
                remoteFileUrl = remoteFileUrl + "&noVarHeader=1";
            } else {
                // and if we are retreiving this tab file in order
                // to convert it to another format locally, we also
                // have to add the noVarHeader flag, otherwise the
                // header will be treated as a line of data!

                if (req.getParameter("format") != null) {
                    remoteFileUrl = remoteFileUrl + "&noVarHeader=1";
                    // TODO -- ? -- do we need to check if this is
                    // a tab-delimited file?
                }
            }
        }

        // See if remote authentication is required;

        String remoteHost = null;
        String regexRemoteHost = "https*://([^/]*)/";
        Pattern patternRemoteHost = Pattern.compile(regexRemoteHost);
        Matcher hostMatcher = patternRemoteHost.matcher(remoteFileUrl);

        if (hostMatcher.find()) {
            remoteHost = hostMatcher.group(1);
        }

        method = new GetMethod(remoteFileUrl);

        String jsessionid = null;
        String remoteAuthHeader = null;

        String remoteAuthType = remoteAuthRequired(remoteHost);

        if (remoteAuthType != null) {
            if (remoteAuthType.equals("httpbasic")) {
                // get the basic HTTP auth credentials
                // (password and username) from the database:

                remoteAuthHeader = getRemoteAuthCredentials(remoteHost);

                if (remoteAuthHeader != null) {
                    method.addRequestHeader("Authorization", remoteAuthHeader);
                }
            } else if (remoteAuthType.equals("dvn")) {
                // Authenticate with the remote DVN:

                jsessionid = dvnRemoteAuth(remoteHost);
            } else if (remoteAuthType.equals("icpsr")) {
                method = null;
                remoteFileUrl = remoteFileUrl.replace("staging", "www");
                remoteFileUrl = remoteFileUrl.replace("/cgi-bin/file", "/cgi-bin/bob/file");
                method = new GetMethod(remoteFileUrl);

                String icpsrCookie = getICPSRcookie(remoteHost, remoteFileUrl);

                if (icpsrCookie != null) {
                    method.addRequestHeader("Cookie", icpsrCookie);
                }

                if (remoteFileUrl.matches(".*gzip.*")) {
                    zippedStream = true;
                }
            }
        }

        if (jsessionid != null) {
            method.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
        }

        // normally, the HTTP client follows redirects
        // automatically, so we need to explicitely tell it
        // not to:

        method.setFollowRedirects(false);
        status = (new HttpClient()).executeMethod(method);

        // The code below is to enable the click through
        // Terms-of-Use Agreement.
        // We are assuming that if they have gotten here,
        // they must have already clicked on all the
        // licensing agreement forms (the terms-of-use
        // agreements are preserved in the study DDIs as
        // they are exported and harvested between DVNs).

        // There are obvious dangers in this approach.
        // We have to trust the DVN harvesting from us to display
        // the agreements in question to their users. But since
        // terms/restrictions cannot be disabled on harvested
        // content through the normal DVN interface, so they
        // would have to go directly to the database to do so,
        // which would constitute an obvious "hacking" of the
        // mechanism, (hopefully) making them and not us liable
        // for it.

        if (status == 302 || status == 301) {
            // this is a redirect.

            // let's see where it is redirecting us; if it looks like
            // DVN TermsOfUse page, we'll "click" and submit the form,
            // then we'll hopefully be able to download the file.
            // If it's no the TOU page, we are just going to try to
            // follow the redirect and hope for the best.
            // (A good real life example is the Census archive: the
            // URLs for their objects that they give us are actually
            // aliases that are 302-redirected to the actual locations)

            String redirectLocation = null;
            String extraCookies = null;

            for (int i = 0; i < method.getResponseHeaders().length; i++) {
                String headerName = method.getResponseHeaders()[i].getName();
                if (headerName.equals("Location")) {
                    redirectLocation = method.getResponseHeaders()[i].getValue();
                }

                String regexCookie = "^([^;]*;)";
                Pattern patternCookie = Pattern.compile(regexCookie);

                if (headerName.equals("Set-Cookie") || headerName.equals("Set-cookie")) {
                    String cookieHeader = method.getResponseHeaders()[i].getValue();
                    Matcher cookieMatcher = patternCookie.matcher(cookieHeader);
                    String regexpJsession = "JSESSIONID=([^;]*);";
                    Pattern patternJsession = Pattern.compile(regexpJsession);
                    Matcher jsessionMatcher = patternJsession.matcher(cookieHeader);
                    if ((jsessionid == null || jsessionid.equals("")) && jsessionMatcher.find()) {
                        jsessionid = jsessionMatcher.group(1);
                    } else if (cookieMatcher.find()) {
                        extraCookies = cookieMatcher.group(1);
                    }
                }
            }

            if (redirectLocation.matches(".*TermsOfUsePage.*")) {

                // Accept the TOU agreement:

                method = remoteAccessTOU(redirectLocation, jsessionid, remoteFileUrl, extraCookies);

                // If everything has worked right
                // we should be redirected to the final
                // download URL, and the method returned is
                // an established download connection;

                if (method != null) {
                    status = method.getStatusCode();
                } else {
                    // but if something went wrong in the progress,
                    // we just report that we couldn't find
                    // the file:
                    status = 404;
                }

            } else {
                // just try again (and hope for the best!)
                method = new GetMethod(redirectLocation);
                status = (new HttpClient()).executeMethod(method);
            }
        }
    } catch (IOException ex) {
        //if (method != null) {
        //    method.releaseConnection();
        //}
        status = 404;
    }

    this.setStatus(status);

    if (status != 200) {
        if (method != null) {
            method.releaseConnection();
        }

        throw new IOException("HTTP access failed; status: " + status);
    }

    InputStream in = null;

    try {
        if (zippedStream) {
            InputStream zipInputStream = method.getResponseBodyAsStream();
            ZipInputStream zin = new ZipInputStream(zipInputStream);
            zin.getNextEntry();

            this.setIsZippedStream(true);

            in = zin;

        } else {
            in = method.getResponseBodyAsStream();
        }

        this.setInputStream(in);

    } catch (IOException ex) {
        this.setStatus(404);
        String errorMessage = "I/O error has occured while attempting to retreive a remote data file: "
                + ex.getMessage()
                + ". Please try again later and if the problem persists, report it to your DVN technical support contact.";
        this.setErrorMessage(errorMessage);

        throw new IOException(
                "I/O error has occured while attempting to retreive a remote data file: " + ex.getMessage());
    }

    this.setResponseHeaders(method.getResponseHeaders());
    this.setHTTPMethod(method);

}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private ZipEntry getNextZipEntry(final ZipInputStream zipInputStream) throws DSSException {
    try {/* ww w .j  a  va  2s . co  m*/
        return zipInputStream.getNextEntry();
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

private List<String> getRelsEntryNames(URL url) throws IOException {
    List<String> relsEntryNames = new LinkedList<String>();
    ZipInputStream zipInputStream = new ZipInputStream(url.openStream());
    ZipEntry zipEntry;/*from  w w w  .  j ava  2s. c  om*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        String entryName = zipEntry.getName();
        if (entryName.endsWith(".rels")) {
            relsEntryNames.add(entryName);
        }
    }
    return relsEntryNames;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddExperimentWizardController.java

@Override
protected ModelAndView processFinish(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception {
    log.debug("Processing measuration form - adding new measuration");
    ModelAndView mav = new ModelAndView("redirect:/experiments/my-experiments.html");

    mav.addObject("userIsExperimenter", auth.userIsExperimenter());

    AddExperimentWizardCommand data = (AddExperimentWizardCommand) command;

    Experiment experiment;//from   w  w  w .j a v  a  2s  .  c o m

    log.debug("Checking the permission level.");
    if (!auth.userIsExperimenter()) {
        log.debug("User is not experimenter - unable to add experiment. Returning MAV.");
        mav.setViewName("redirect:experiments/userNotExperimenter");
        return mav;
    }

    log.debug("Creating new Measuration object");
    experiment = new Experiment();

    // This assignment is commited only when new experiment is being created
    log.debug("Setting the owner to the logged user.");
    experiment.setPersonByOwnerId(personDao.getLoggedPerson());

    log.debug("Setting the group, which is the new experiment being added into.");
    ResearchGroup researchGroup = new ResearchGroup();
    researchGroup.setResearchGroupId(data.getResearchGroup());
    experiment.setResearchGroup(researchGroup);

    log.debug("Setting Weather object - ID " + data.getWeather());
    Weather weather = new Weather();
    weather.setWeatherId(data.getWeather());
    experiment.setWeather(weather);

    log.debug("Setting Scenario object - ID " + data.getScenario());
    Scenario scenario = new Scenario();
    scenario.setScenarioId(data.getScenario());
    experiment.setScenario(scenario);

    log.debug("Setting Person object (measured person) - ID " + data.getSubjectPerson());
    Person subjectPerson = new Person();
    subjectPerson.setPersonId(data.getSubjectPerson());
    experiment.setPersonBySubjectPersonId(subjectPerson);

    Date startDate = ControllerUtils.getDateFormatWithTime()
            .parse(data.getStartDate() + " " + data.getStartTime());
    experiment.setStartTime(new Timestamp(startDate.getTime()));
    log.debug("Setting start date - " + startDate);

    Date endDate = ControllerUtils.getDateFormatWithTime().parse(data.getEndDate() + " " + data.getEndTime());
    experiment.setEndTime(new Timestamp(endDate.getTime()));
    log.debug("Setting end date - " + endDate);

    log.debug("Setting the temperature - " + data.getTemperature());
    experiment.setTemperature(Integer.parseInt(data.getTemperature()));

    log.debug("Setting the weather note - " + data.getWeatherNote());
    experiment.setEnvironmentNote(data.getWeatherNote());

    log.debug("Started setting the Hardware objects");
    int[] hardwareArray = data.getHardware();
    Set<Hardware> hardwareSet = new HashSet<Hardware>();
    for (int hardwareId : hardwareArray) {
        System.out.println("hardwareId " + hardwareId);
        Hardware tempHardware = hardwareDao.read(hardwareId);
        hardwareSet.add(tempHardware);
        tempHardware.getExperiments().add(experiment);
        log.debug("Added Hardware object - ID " + hardwareId);
    }
    log.debug("Setting Hardware list to Measuration object");
    experiment.setHardwares(hardwareSet);

    log.debug("Started setting the Person objects (coExperimenters)");
    int[] coExperimentersArray = data.getCoExperimenters();
    Set<Person> coExperimenterSet = new HashSet<Person>();
    for (int personId : coExperimentersArray) {
        Person tempExperimenter = personDao.read(personId);
        coExperimenterSet.add(tempExperimenter);
        tempExperimenter.getExperiments().add(experiment);
        log.debug("Added Person object - ID " + tempExperimenter.getPersonId());
    }
    log.debug("Setting Person list to Measuration object");
    experiment.setPersons(coExperimenterSet);

    log.debug("Setting private/public access");
    experiment.setPrivateExperiment(data.isPrivateNote());
    float samplingRate = Float.parseFloat(data.getSamplingRate());
    Digitization digitization = digitizationDao.getDigitizationByParams(samplingRate, -1, "NotKnown");
    if (digitization == null) {
        digitization = new Digitization();
        digitization.setFilter("NotKnown");
        digitization.setGain(-1);
        digitization.setSamplingRate(samplingRate);
        digitizationDao.create(digitization);
    }

    experiment.setDigitization(digitization);
    experiment.setArtifact(artifactDao.read(1));
    experiment.setElectrodeConf(electrodeConfDao.read(1));
    experiment.setSubjectGroup(subjectGroupDao.read(1)); //default subject group

    if (data.getMeasurationId() > 0) { // editing existing measuration
        log.debug("Saving the Measuration object to database using DAO - update()");
        experimentDao.update(experiment);
    } else { // creating new measuration
        log.debug("Saving the Measuration object to database using DAO - create()");
        experimentDao.create(experiment);
    }

    //  log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
    //     experiment.setExperimentId(addDataCommand.getMeasurationId());

    log.debug("Creating new Data object.");
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) httpServletRequest;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);
        if (file.getOriginalFilename().endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
            ZipEntry en = zis.getNextEntry();
            while (en != null) {
                if (en.isDirectory()) {
                    en = zis.getNextEntry();
                    continue;
                }
                DataFile dataFile = new DataFile();
                dataFile.setExperiment(experiment);
                String name[] = en.getName().split("/");
                dataFile.setFilename(name[name.length - 1]);
                data.setFileDescription(data.getFileDescription());
                dataFile.setFileContent(Hibernate.createBlob(zis));
                String[] partOfName = en.getName().split("[.]");
                dataFile.setMimetype(partOfName[partOfName.length - 1]);
                dataFileDao.create(dataFile);
                en = zis.getNextEntry();
            }
        } else {
            DataFile dataFile = new DataFile();
            dataFile.setExperiment(experiment);

            log.debug("Original name of uploaded file: " + file.getOriginalFilename());
            String filename = file.getOriginalFilename().replace(" ", "_");
            dataFile.setFilename(filename);

            log.debug("MIME type of the uploaded file: " + file.getContentType());
            if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                int index = filename.lastIndexOf(".");
                dataFile.setMimetype(filename.substring(index));
            } else {
                dataFile.setMimetype(file.getContentType());
            }

            log.debug("Parsing the sapmling rate.");
            dataFile.setDescription(data.getFileDescription());

            log.debug("Setting the binary data to object.");
            dataFile.setFileContent(Hibernate.createBlob(file.getBytes()));

            dataFileDao.create(dataFile);
            log.debug("Data stored into database.");
        }
    }

    log.debug("Returning MAV object");
    return mav;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

public Document getSignatureDocument(InputStream documentInputStream, String signatureResourceName)
        throws IOException, ParserConfigurationException, SAXException {
    ZipInputStream zipInputStream = new ZipInputStream(documentInputStream);
    ZipEntry zipEntry;/*ww  w  .  j  a v  a2s .  com*/
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!signatureResourceName.equals(zipEntry.getName())) {
            continue;
        }
        return OOXMLSignatureFacet.loadDocument(zipInputStream);
    }
    return null;
}