Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:controller.servlet.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w  w.  j av  a2s .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Subida de los ficheros al sistema.

    UploadedFile uF;
    UploadedFileDaoImpl uFD = new UploadedFileDaoImpl();

    int numberOfCsvFiles = 0;
    int numberOfNotCsvFiles = 0;

    for (Part part : request.getParts()) {
        if (part.getName().equals("file")) {
            try (InputStream is = request.getPart(part.getName()).getInputStream()) {
                int i = is.available();
                byte[] b = new byte[i];

                if (b.length == 0) {
                    break;
                }

                is.read(b);
                String fileName = obtenerNombreFichero(part);
                String extension = FilenameUtils.getExtension(fileName);
                String path = this.getServletContext().getRealPath("");
                String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName;
                File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER);
                if (!directorio.exists()) {
                    directorio.mkdirs();
                }

                // Se sube el fichero en caso de ser zip o csv.
                if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) {
                    try (FileOutputStream os = new FileOutputStream(ruta)) {
                        os.write(b);
                    }
                    if (extension.equals(Path.CSV_EXTENSION)) {
                        numberOfCsvFiles++;
                    }
                } else {
                    numberOfNotCsvFiles++;
                }

                // Extraccin de los ficheros incluidos en el zip.
                if (extension.equals(Path.ZIP_EXTENSION)) {
                    ZipInputStream zis = new ZipInputStream(
                            new FileInputStream(directorio + File.separator + fileName));
                    ZipEntry eachFile;
                    while (null != (eachFile = zis.getNextEntry())) {
                        File newFile = new File(directorio + File.separator + eachFile.getName());
                        // Se guardan los csv.
                        if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName())
                                .equals(Path.CSV_EXTENSION)) {
                            numberOfCsvFiles++;
                            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                                int len;
                                byte[] buffer = new byte[1024];
                                while ((len = zis.read(buffer)) > 0) {
                                    fos.write(buffer, 0, len);
                                }
                            }
                            zis.closeEntry();
                            // Insertar en BD
                            uF = new UploadedFile(0, eachFile.getName(),
                                    new java.sql.Date(new Date().getTime()), false, null);
                            uFD.createFile(uF);
                        } else {
                            numberOfNotCsvFiles++;
                        }
                    }
                    File fileToDelete = new File(
                            path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName);
                    fileToDelete.delete();
                } else {
                    // Insertar en BD
                    uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null);
                    uFD.createFile(uF);
                }
            }
        }
    }

    // Asignacin de valores.
    HttpSession session = request.getSession(true);
    session.setAttribute("numberOfCsvFiles", numberOfCsvFiles);
    session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles);

    if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) {
        session.setAttribute("error", true);
    } else {
        session.setAttribute("error", false);
    }

    processRequest(request, response);
}

From source file:com.nuvolect.securesuite.util.OmniZip.java

public static List<String> getFilesList(OmniFile zipOmni) {

    ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream());

    List<String> arrayList = new ArrayList<>();

    ZipEntry entry = null;/*w  ww .  ja  v  a  2  s.  c  o  m*/
    try {
        while ((entry = zis.getNextEntry()) != null) {

            arrayList.add(entry.getName());
        }
        zis.close();

    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
    }

    return arrayList;
}

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

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }//from   ww  w.j av  a2  s.  c  o  m
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
            break;
        }
    }
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    if (null == zipEntry) {
        return signatureInfos;
    }
    XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);
    Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream);
    NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
        Element signatureElement = (Element) signatureNodeList.item(idx);
        xadesValidation.prepareDocument(signatureElement);
        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
        ASiCURIDereferencer dereferencer = new ASiCURIDereferencer(document);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);
        if (!valid) {
            continue;
        }

        // check whether all files have been signed properly
        SignedInfo signedInfo = xmlSignature.getSignedInfo();
        @SuppressWarnings("unchecked")
        List<Reference> references = signedInfo.getReferences();
        Set<String> referenceUris = new HashSet<String>();
        for (Reference reference : references) {
            String referenceUri = reference.getURI();
            referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8"));
        }
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
                continue;
            }
            if (false == referenceUris.contains(zipEntry.getName())) {
                LOG.warn("no ds:Reference for ASiC entry: " + zipEntry.getName());
                return signatureInfos;
            }
        }

        X509Certificate signer = keySelector.getCertificate();
        SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature,
                signatureElement, signer);
        signatureInfos.add(signatureInfo);
    }
    return signatureInfos;
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java

@Override
public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from   w w  w  .  j  a  v  a 2  s .c o  m*/

    InputStream urlStream = null;
    try {
        URL url = getUrl();
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);

        int length = connection.getContentLength();
        monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()),
                length >= 0 ? length : IProgressMonitor.UNKNOWN);

        urlStream = connection.getInputStream();
        ZipInputStream zipStream = new ZipInputStream(urlStream);
        byte[] buffer = new byte[1024 * 8];
        long start = System.currentTimeMillis();
        int total = length;
        int totalRead = 0;
        ZipEntry entry;
        float kBps = -1;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (monitor.isCanceled())
                break;
            String fullFilename = entry.getName();
            IPath fullFilenamePath = new Path(fullFilename);
            int secsRemaining = (int) ((total - totalRead) / 1024 / kBps);
            String textRemaining = secsToText(secsRemaining);
            monitor.subTask(NLS.bind("{0} remaining. Reading {1}",
                    textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils
                            .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45)));
            int entrySize = (int) entry.getCompressedSize();
            OutputStream output = null;
            try {
                int len = 0;
                int read = 0;
                String action = null;
                if (jarFiles.contains(fullFilename)) {
                    action = "Copying";
                    String filename = FilenameUtils.getName(fullFilename);
                    output = new FileOutputStream(dirPath.append(filename).toOSString());
                } else {
                    action = "Skipping";
                    output = new NullOutputStream();
                }
                int secs = (int) ((System.currentTimeMillis() - start) / 1000);
                kBps = (float) totalRead / 1024 / secs;

                while ((len = zipStream.read(buffer)) > 0) {
                    if (monitor.isCanceled())
                        break;
                    read += len;
                    monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)",
                            new Object[] {
                                    String.format("%s",
                                            textRemaining.length() > 0 ? textRemaining : "unknown time"),
                                    action,
                                    StringUtils.abbreviateMiddle(
                                            fullFilenamePath.removeFirstSegments(1).toString(), "...", 45),
                                    String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024),
                                    String.format("%,.1f", (float) entry.getSize() / 1024) }));
                    output.write(buffer, 0, len);
                }
                totalRead += entrySize;
                monitor.worked(entrySize);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    } finally {
        IOUtils.closeQuietly(urlStream);
        monitor.done();
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param stream zip input stream/* w w w. j a  va2 s.  c om*/
 * @param dir directory to unzip
 * @param unique if need add unique suffix to every file name then true
 * @throws java.io.IOException
 * @return list of unzipped file names
 */
public static List<String> unZIP(InputStream stream, File dir, boolean unique) throws IOException {
    Long createdTime = new Date().getTime();
    String randomName = SecurityHelper.generateRandomSequence(16);
    List<String> fileNames = new ArrayList<String>();
    ZipInputStream in = new ZipInputStream(stream);
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String name = entry.getName();
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(new File(dir, name));
        } else {
            String dirName = "";
            if (name.contains("/") && !File.separator.equals("/"))
                name = name.replaceAll("/", File.separator + File.separator);
            if (name.contains("\\") && !File.separator.equals("\\"))
                name = name.replaceAll("\\\\", File.separator);

            if (name.lastIndexOf(File.separator) != -1)
                dirName = name.substring(0, name.lastIndexOf(File.separator));
            String fileName = name.substring(name.lastIndexOf(File.separator) + 1, name.length());
            if (unique) {
                fileName = fileName + "." + randomName + "." + createdTime;
            }
            OutputStream out = FileUtils.openOutputStream(FileUtils.create(dir, dirName, fileName));
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            fileNames.add(fileName);
        }
    }
    IOUtils.closeQuietly(in);
    return fileNames;
}

From source file:com.moss.error_reporting.server.Notifier.java

public void sendEmailNotification(ReportId id, ErrorReport report) {
    try {//from w ww  .  jav  a2s .  c  o  m
        HtmlEmail email = new HtmlEmail();
        prepEmail(email, id);

        StringBuffer body = new StringBuffer();
        body.append("<html><body>");

        List<ErrorReportChunk> chunks = report.getReportChunks();
        for (int x = 0; x < chunks.size(); x++) {

            ErrorReportChunk chunk = chunks.get(x);
            body.append("<div style=\"padding:5px;text-align:center;border:1px solid black;\">");
            body.append("<span style=\"font-weight:bold;\">" + chunk.getName() + "</span>");
            body.append("<span style=\"font-style:italic;\">[" + chunk.getMimeType() + "</span>]");
            body.append("</div>");
            String mimeType = chunk.getMimeType();
            if (mimeType != null && mimeType.equals("text/plain")) {
                body.append(
                        "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>");
                boolean needsTruncation = chunk.getData().length > MAX_MESSAGE_LENGTH;
                int length = needsTruncation ? MAX_MESSAGE_LENGTH : chunk.getData().length;

                body.append(new String(chunk.getData(), 0, length));
                if (needsTruncation) {
                    body.append("\n");
                    body.append((chunk.getData().length - MAX_MESSAGE_LENGTH) + " more bytes");
                }
                body.append("</pre></div>");
            } else if (mimeType != null && mimeType.equals("application/zip")) {
                body.append(
                        "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>");
                ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(chunk.getData()));
                try {
                    new ZipToTextTool().run(in, body);
                } catch (IOException e) {
                    e.printStackTrace();
                    body.append("Error Reading Zip:" + e.getMessage());
                }
                body.append("</pre></div>");
            }
            if (x != chunks.size() - 1 && chunks.size() > 1)
                body.append("<br/><br/>");

        }
        body.append("</body></html>");

        //         email.setHtmlMsg("<html><body>Hello World</body></html>");
        email.setHtmlMsg(body.toString());
        //         email.setTextMsg("HTML EMAIL");
        email.buildMimeMessage();
        email.sendMimeMessage();

    } catch (EmailException e) {
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectHybridizationsActionTest.java

@Test
public void testDownload() throws Exception {
    assertEquals("noHybData", this.action.download());

    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Hybridization h1 = new Hybridization();
    final Hybridization h2 = new Hybridization();
    final RawArrayData raw = new RawArrayData();
    h1.addArrayData(raw);//from   w ww  . j av  a 2 s . c o m
    final DerivedArrayData derived = new DerivedArrayData();
    h2.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentHybridization(h1);
    this.action.setProject(p);
    List<CaArrayFile> files = new ArrayList<CaArrayFile>(h1.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(1, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    files = new ArrayList<CaArrayFile>(h2.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(1, files.size());
    assertEquals("missing_term_source.sdrf", files.get(0).getName());

    assertEquals(null, this.action.download());
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:com.aurel.track.dbase.InitReportTemplateBL.java

/**
 * Extracts and copies the template definitions from the zips from the classpath
 * to the directory parallel with the attachment directory in the disk
 *
 *//*from w  w w. ja v  a2  s.co m*/
public static void verifyReportTemplates() {
    LOGGER.info("Verifying report templates...");
    List<TExportTemplateBean> templatesList = ReportBL.getAllTemplates();

    int noOfDbTemplates = templatesList.size();
    int noOfNewlyInstalled = 0;

    for (int i = 0; i < templatesList.size(); i++) {
        TExportTemplateBean templateBean = templatesList.get(i);
        Integer templateID = templateBean.getObjectID();
        File f = ReportBL.getDirTemplate(templateID);
        LOGGER.debug("Move template:" + templateBean.getName() + " to" + f.getAbsolutePath());
        NumberFormat nf = new DecimalFormat("00000");
        String dbId = nf.format(templateID);
        String reportTemplateName = ReportBL.RESOURCE_PATH + "/" + ReportBL.EXPORT_TEMPLATE_PREFIX + dbId
                + ".zip";
        InputStream is = StartServlet.class.getClassLoader().getResourceAsStream(reportTemplateName);
        if (is == null) {
            //zip not found in the classpath: nothing to expand and copy
            continue;
        }
        if (!f.exists()) {
            boolean pathCreated = f.mkdirs();
            if (!pathCreated) {
                LOGGER.error("The destination directory " + f.getAbsolutePath() + " can't be created. "
                        + "This might be caused by OS file permissions or "
                        + "because the default directory lies inside the tomcat application. "
                        + "Set the attachment directory to a writable absolute path directory (outside tomcat) and restart tomcat");
                continue;
            }
        }
        ZipInputStream zf = new ZipInputStream(new BufferedInputStream(is));
        try {
            ReportBL.saveTemplate(templateID, zf);
            ++noOfNewlyInstalled;
        } catch (IOException e) {
            LOGGER.error("Can't move template:" + templateBean.getName() + "!", e);
        }
    }
    LOGGER.debug("Verifying report templates ready!");
    LOGGER.info("There are " + noOfDbTemplates + " report templates in the database; " + noOfNewlyInstalled
            + " were newly installed.");
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static Map<String, String> getResource(String inputResource) {
    Map<String, String> data = new HashMap<>();
    InputStream inputStream = loadResource(inputResource);
    try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
        ZipEntry entry;/*from   w  ww.  j a  va  2 s.  c  o  m*/
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if (entry.getName().lastIndexOf('.') == -1) {
                continue;
            }
            StringWriter writer = new StringWriter();
            IOUtils.copy(zipInputStream, writer, StandardCharsets.UTF_8.name());
            String fileName = entry.getName();
            fileName = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.lastIndexOf('.'));
            data.put(fileName, writer.toString());
            zipInputStream.closeEntry();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        System.out.println("InputResource : " + inputResource);
    }
    return data;
}

From source file:com.termmed.utils.ResourceUtils.java

/**
 * Gets the resource scripts.//from ww  w  .j  a v a  2 s . c o m
 *
 * @param path the path
 * @return the resource scripts
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Collection<String> getResourceScripts(String path) throws IOException {
    System.out.println("getting files from " + path);
    List<String> strFiles = new ArrayList<String>();

    //      InputStream is=ResourceUtils.class.getResourceAsStream("/" + path);
    //      InputStreamReader risr = new InputStreamReader(is);
    //      BufferedReader br=new BufferedReader(risr);
    //      String line;
    //      while((line=br.readLine())!=null){
    //         strFiles.add(line);
    //      }

    String file = null;
    if (new File("stats-build.jar").exists()) {
        file = "stats-build.jar";
    } else {
        file = "target/stats-build.jar";
    }
    ZipInputStream zip = new ZipInputStream(new FileInputStream(file));
    while (true) {
        ZipEntry e = zip.getNextEntry();
        if (e == null)
            break;
        String name = e.getName();
        if (name.startsWith(path) && !name.endsWith("/")) {
            //            if (!name.startsWith("/")){
            //               name="/" + name;
            //            }
            strFiles.add(name);
        }
    }

    System.out.println("files:" + strFiles.toString());
    return strFiles;
}