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:lucee.commons.io.compress.CompressUtil.java

private static void unzip(Resource zipFile, Resource targetDir) throws IOException {
    /*if(zipFile instanceof File){
       unzip((File)zipFile, targetDir);//w  w w . j a  v a2s .c  o  m
       return;
    }*/

    ZipInputStream zis = null;
    try {
        zis = new ZipInputStream(IOUtil.toBufferedInputStream(zipFile.getInputStream()));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            Resource target = targetDir.getRealResource(entry.getName());
            if (entry.isDirectory()) {
                target.mkdirs();
            } else {
                Resource parent = target.getParentResource();
                if (!parent.exists())
                    parent.mkdirs();
                IOUtil.copy(zis, target, false);
            }
            target.setLastModified(entry.getTime());
            zis.closeEntry();
        }
    } finally {
        IOUtil.closeEL(zis);
    }
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   findManifest()/*  w  w w  .  j  av a2s .  com*/
** Input:  String zipFileName  --  The name of the zip file to be used
** Output:   Boolean  --  Signifies whether or not the manifest was found.
**
** Description: This method takes in the name of a zip file and tries to 
**              locate the imsmanifest.xml file
**              
*****************************************************************************/
public static boolean findManifest(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in findManifest()      ");
        System.out.println("***********************\n");
    }

    boolean rtn = false;

    try {
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));

        ZipEntry entry;
        int flag = 0;

        while ((flag != 1) && (in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).equalsIgnoreCase("imsmanifest.xml")) {
                    if (_Debug) {
                        System.out.println("Located manifest.... returning true");
                    }
                    flag = 1;
                    rtn = true;
                }
            }
        }

        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
    }
    return rtn;
}

From source file:co.cask.hydrator.transforms.CSVParser2.java

private byte[] unzip(byte[] body) throws IOException {
    Inflater inf = new Inflater();
    ByteArrayInputStream bytein = new ByteArrayInputStream(body);
    ZipInputStream gzin = new ZipInputStream(bytein);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();

    int res = 0;/*from  w ww  .  j a va2s  .co  m*/
    byte buf[] = new byte[1024];
    while (res >= 0) {
        res = gzin.read(buf, 0, buf.length);
        if (res > 0) {
            byteout.write(buf, 0, res);
        }
    }
    byte uncompressed[] = byteout.toByteArray();
    return uncompressed;
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from  w  ww.  ja  va2 s .  c o m*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request//from w w  w  . jav a 2  s .  c o m
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}

From source file:org.vietspider.server.handler.cms.metas.EditContentHandler.java

private byte[] loadZipEntry(File file, String fileName) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipInputStream zipInput = null;
    try {/*from  ww w. j  a va 2  s. com*/
        zipInput = new ZipInputStream(new FileInputStream(file));
        int read = -1;
        byte[] bytes = new byte[4 * 1024];

        ZipEntry entry = null;
        while (true) {
            entry = zipInput.getNextEntry();
            if (entry == null)
                break;
            if (entry.getName().equalsIgnoreCase(fileName)) {
                while ((read = zipInput.read(bytes, 0, bytes.length)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                break;
            }
        }
        zipInput.close();
    } finally {
        try {
            if (zipInput != null)
                zipInput.close();
        } catch (Exception e) {
        }
    }
    return outputStream.toByteArray();
}

From source file:io.apicurio.hub.api.codegen.OpenApi2ThorntailTest.java

/**
 * Test method for {@link io.apicurio.hub.api.codegen.OpenApi2Thorntail#generate()}.
 *///w  w  w .j av a 2 s.  c om
@Test
public void testGenerateFull_GatewayApi() throws IOException {
    OpenApi2Thorntail generator = new OpenApi2Thorntail();
    generator.setUpdateOnly(false);
    generator.setOpenApiDocument(
            getClass().getClassLoader().getResource("OpenApi2ThorntailTest/gateway-api.json"));
    ByteArrayOutputStream outputStream = generator.generate();

    //        FileUtils.writeByteArrayToFile(new File("C:\\Users\\ewittman\\tmp\\testGenerateFull_GatewayApi.zip"), outputStream.toByteArray());

    // Validate the result
    try (ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(outputStream.toByteArray()))) {
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                //                    System.out.println(name);
                Assert.assertNotNull(name);

                URL expectedFile = getClass().getClassLoader().getResource(
                        getClass().getSimpleName() + "/_expected-gatewayApi-full/generated-api/" + name);
                Assert.assertNotNull("Could not find expected file for entry: " + name, expectedFile);
                String expected = IOUtils.toString(expectedFile);

                String actual = IOUtils.toString(zipInputStream);
                //                    System.out.println("-----");
                //                    System.out.println(actual);
                //                    System.out.println("-----");
                Assert.assertEquals("Expected vs. actual failed for entry: " + name, normalizeString(expected),
                        normalizeString(actual));
            }
            zipEntry = zipInputStream.getNextEntry();
        }
    }
}

From source file:com.sliu.framework.app.process.controller.ProcessXNController.java

/**
 * ?,??????API// w  w  w  .  j  a  v a  2 s. co m
 */
@RequestMapping(value = "/deployProcess", method = RequestMethod.POST)
@ResponseBody
public String deployProcess(@RequestParam("attachMentFile") MultipartFile multipartFile)
        throws FileNotFoundException {

    if (multipartFile != null && multipartFile.getSize() != 0) {
        //,???
        FileCommonOperate fileCommonOperate = new FileCommonOperate();
        try {
            String fileName = fileCommonOperate.uploadFile(multipartFile.getInputStream(), deployFilePath,
                    multipartFile.getOriginalFilename());
            InputStream fileInputStream = multipartFile.getInputStream();
            String extension = FilenameUtils.getExtension(fileName);
            if (extension.equals("zip") || extension.equals("bar")) {
                ZipInputStream zip = new ZipInputStream(fileInputStream);
                repositoryService.createDeployment().addZipInputStream(zip).deploy();
            } else {
                repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
    return "{success:true}";
}

From source file:com.ephesoft.gxt.systemconfig.server.ImportPluginUploadServlet.java

private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService)
        throws IOException {
    String errorMessageString = EMPTY_STRING;
    PrintWriter printWriter = resp.getWriter();
    File tempZipFile = null;/*from  ww w .j av a 2s. co  m*/
    InputStream instream = null;
    OutputStream out = null;
    ZipInputStream zipInputStream = null;

    List<ZipEntry> zipEntries = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = EMPTY_STRING;

        try {
            Properties allProperties = ApplicationConfigProperties.getApplicationConfigProperties()
                    .getAllProperties(META_INF_APPLICATION_PROPERTIES);

            exportSerailizationFolderPath = allProperties.getProperty(PLUGIN_UPLOAD_PROPERTY_NAME);
        } catch (IOException e) {
        }
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdir();
        }

        List<FileItem> items;
        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {

                if (!item.isFormField()) {
                    zipFileName = item.getName();
                    if (zipFileName != null) {
                        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                    }
                    zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;

                    try {
                        instream = item.getInputStream();
                        tempZipFile = new File(zipPathname);

                        if (tempZipFile.exists()) {
                            tempZipFile.delete();
                        }
                        out = new FileOutputStream(tempZipFile);
                        byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the export folder." + e, e);
                        printWriter.write("Unable to create the export folder.Please try again.");

                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException ioe) {
                                log.info("Could not close stream for file." + tempZipFile);
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ioe) {
                                log.info("Could not close stream for file." + zipFileName);
                            }
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

        // Unnecessary code to unzip the attached file removed.

        zipInputStream = new ZipInputStream(new FileInputStream(zipPathname));

        zipEntries = new ArrayList<ZipEntry>();
        ZipEntry nextEntry = zipInputStream.getNextEntry();
        while (nextEntry != null) {
            zipEntries.add(nextEntry);
            nextEntry = zipInputStream.getNextEntry();
        }
        errorMessageString = processZipFileContents(zipEntries, zipPathname);

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }

    // Temp file is now not created.

    if (validZipContent) {
        String zipFileNameWithoutExtension = zipPathname.substring(0, zipPathname.lastIndexOf('.'));
        printWriter.write(SystemConfigConstants.PLUGIN_NAME + zipFileNameWithoutExtension);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.append(SystemConfigConstants.JAR_FILE_PATH).append(jarFilePath);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.append(SystemConfigConstants.XML_FILE_PATH).append(xmlFilePath);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.flush();
    } else {
        printWriter.write("Error while importing.Please try again." + CAUSE + errorMessageString);
    }

}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static String getShapefileNameFromCompressed(InputStream is) {
    String shapefileName = null;//  w  ww .j  av a  2 s .c o  m
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry ze;
    try {
        while (((ze = zis.getNextEntry()) != null) && (shapefileName == null)) {
            if (!ze.isDirectory()) {
                String fileName = ze.getName().toLowerCase();
                if (fileName.endsWith(".shp")) {
                    shapefileName = fileName;
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            zis.closeEntry();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            zis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return shapefileName;
}