Example usage for java.util.zip ZipEntry toString

List of usage examples for java.util.zip ZipEntry toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the ZIP entry.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    String zipname = "data.zip";
    ZipFile zipFile = new ZipFile(zipname);
    Enumeration enumeration = zipFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
        System.out.println(zipEntry.toString());
    }//from   ww w . j  a  v a  2s.  c om
}

From source file:Main.java

public static byte[] readZipEntry(File zfile, ZipEntry entry) throws ZipException, IOException {
    Log.d("file3: ", zfile.toString());
    Log.d("zipEntry3: ", entry.toString());
    ZipFile zipFile = new ZipFile(zfile);
    if (entry != null && !entry.isDirectory()) {
        byte[] barr = new byte[(int) entry.getSize()];
        int read = 0;
        int len = 0;
        InputStream is = zipFile.getInputStream(entry);
        BufferedInputStream bis = new BufferedInputStream(is);
        int length = barr.length;
        while ((len = bis.read(barr, read, length - read)) != -1) {
            read += len;/*from  w  w  w  .ja va2s.  co  m*/
        }
        bis.close();
        is.close();
        zipFile.close();
        return barr;
    } else {
        zipFile.close();
        return new byte[0];
    }
}

From source file:de.ingrid.importer.udk.util.Zipper.java

/**
 * Extracts the given ZIP-File and return a vector containing String
 * representation of the extracted files.
 * /*w  w  w.j av a2 s  .c om*/
 * @param zipFileName
 *            the name of the ZIP-file
 * @param targetDir
 *            the target directory
 * @param keepSubfolders
 *            boolean parameter, whether to keep the folder structure
 * 
 * @return a Vector<String> containing String representation of the allowed
 *         files from the ZipperFilter.
 * @return null if the input data was invalid or an Exception occurs
 */
public static final List<String> extractZipFile(InputStream myInputStream, final String targetDir,
        final boolean keepSubfolders, ZipperFilter zipperFilter) {
    if (log.isDebugEnabled()) {
        log.debug("extractZipFile: inputStream=" + myInputStream + ", targetDir='" + targetDir
                + "', keepSubfolders=" + keepSubfolders);
    }

    ArrayList<String> extractedFiles = new ArrayList<String>();

    FileOutputStream fos = null;

    File outdir = new File(targetDir);

    // make some checks
    if (outdir.isFile()) {
        String msg = "The Target Directory \"" + outdir + "\" must not be a file .";
        log.error(msg);
        System.err.println(msg);
        return null;
    }

    // create necessary directories for the output directory
    outdir.mkdirs();

    // Start Unzipping ...
    try {
        if (log.isDebugEnabled()) {
            log.debug("Start unzipping");
        }

        ZipInputStream zis = new ZipInputStream(myInputStream);
        if (log.isDebugEnabled()) {
            log.debug("ZipInputStream from InputStream=" + zis);
        }

        // for every zip-entry
        ZipEntry zEntry;
        String name;
        while ((zEntry = zis.getNextEntry()) != null) {
            name = zEntry.toString();
            if (log.isDebugEnabled()) {
                log.debug("Zip Entry name: " + name + ", size:" + zEntry.getSize());
            }

            boolean isDir = name.endsWith(separator);
            // System.out.println("------------------------------");
            // System.out.println((isDir? "<d>":"< >")+name);

            String[] nameSplitted = name.split(separator);

            // If it's a File, take all Splitted Names except the last one
            int len = (isDir ? nameSplitted.length : nameSplitted.length - 1);

            String currStr = targetDir;

            if (keepSubfolders) {

                // create all directories from the entry
                for (int j = 0; j < len; j++) {
                    // System.out.println("Dirs: " + nameSplitted[j]);
                    currStr += nameSplitted[j] + File.separator;
                    // System.out.println("currStr: "+currStr);

                    File currDir = new File(currStr);
                    currDir.mkdirs();

                }
            }

            // if the entry is a file, then create it.
            if (!isDir) {

                // set the file name of the output file.
                String outputFileName = null;
                if (keepSubfolders) {
                    outputFileName = currStr + nameSplitted[nameSplitted.length - 1];
                } else {
                    outputFileName = targetDir + nameSplitted[nameSplitted.length - 1];
                }

                File outputFile = new File(outputFileName);
                fos = new FileOutputStream(outputFile);

                // write the File
                if (log.isDebugEnabled()) {
                    log.debug("Write Zip Entry '" + name + "' to file '" + outputFile + "'");
                }
                writeFile(zis, fos, buffersize);
                if (log.isDebugEnabled()) {
                    log.debug("FILE WRITTEN: " + outputFile.getAbsolutePath());
                }

                // add the file to the vector to be returned

                if (zipperFilter != null) {
                    String[] accFiles = zipperFilter.getAcceptedFiles();
                    String currFileName = outputFile.getAbsolutePath();

                    for (int i = 0; i < accFiles.length; i++) {
                        if (currFileName.endsWith(accFiles[i])) {
                            extractedFiles.add(currFileName);
                        }
                    }

                } else {
                    extractedFiles.add(outputFile.getAbsolutePath());
                }

            }

        } // end while

        zis.close();

    } catch (Exception e) {
        log.error("Problems unzipping file", e);
        e.printStackTrace();
        return null;
    }

    return extractedFiles;
}

From source file:edu.clemson.cs.nestbed.common.util.ZipUtils.java

public static File unzip(byte[] zipData, File directory) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(zipData);
    ZipInputStream zis = new ZipInputStream(bais);
    ZipEntry entry = zis.getNextEntry();
    File root = null;//from w  ww .j av  a  2s .  co m

    while (entry != null) {
        if (entry.isDirectory()) {
            File f = new File(directory, entry.getName());
            f.mkdir();

            if (root == null) {
                root = f;
            }
        } else {
            BufferedOutputStream out;
            out = new BufferedOutputStream(new FileOutputStream(new File(directory, entry.toString())),
                    BUFFER_SIZE);

            // ZipInputStream can only give us one byte at a time...
            for (int data = zis.read(); data != -1; data = zis.read()) {
                out.write(data);
            }
            out.close();
        }

        zis.closeEntry();
        entry = zis.getNextEntry();
    }
    zis.close();

    return root;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * Check if the zip file is webanno compatible
 * /* w  w  w. ja  va 2 s  . com*/
 * @param aZipFile the file.
 * @return if it is valid.
 * @throws ZipException if the ZIP file is corrupt.
 * @throws IOException if an I/O error occurs.
 *
 */
@SuppressWarnings({ "rawtypes" })
public static boolean isZipValidWebanno(File aZipFile) throws ZipException, IOException {

    boolean isZipValidWebanno = false;
    ZipFile zip = new ZipFile(aZipFile);
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
        if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT)
                && entry.toString().replace("/", "").endsWith(".json")) {
            isZipValidWebanno = true;
            break;
        }
    }
    return isZipValidWebanno;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

private static String normalizeEntryName(ZipEntry aEntry) {
    // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
    String entryName = aEntry.toString();
    if (entryName.startsWith("/")) {
        entryName = entryName.substring(1);
    }//from ww  w .j  a v  a 2  s.  c  o m

    return entryName;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

private void uploadSourceDocument(ZipFile zip, ZipEntry entry, Project project, User user, String aFileType)
        throws IOException, UIMAException {
    String fileName = FilenameUtils.getName(entry.toString());

    InputStream zipStream = zip.getInputStream(entry);
    SourceDocument document = new SourceDocument();
    document.setName(fileName);/*from   w w  w. j  a v  a  2  s  .c  o m*/
    document.setProject(project);
    document.setFormat(aFileType);
    // Meta data entry to the database
    projectRepository.createSourceDocument(document, user);
    // Import source document to the project repository folder
    projectRepository.uploadSourceDocument(zipStream, document);
}

From source file:com.dclab.preparation.ReadTest.java

public String handleZip(final ZipFile zf, final ZipEntry ze) throws IOException {

    if (ze.isDirectory()) {
        System.out.println(ze.getName() + " is folder ");
    } else if (ze.getName().endsWith(".xml")) {
        Logger.getAnonymousLogger().info("process file " + ze.getName());

        String s = ze.toString();

        // ByteBuffer bb = ByteBuffer.allocate(MAX_CAPACITY);
        InputStream is = zf.getInputStream(ze);

        byte[] bytes = IOUtils.toByteArray(is);

        return extract(new String(bytes));

        //scan( sr );
    }// ww w. ja  va2  s  . c  o  m
    return null;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

/**
 * Create a new project./*from  www . j  a  v a  2s  .c  om*/
 *
 * To test, use the Linux "curl" command.
 *
 * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf'
 * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project
 * '
 *
 * @param aName
 *            the name of the project to create.
 * @param aFileType
 *            the type of the files contained in the ZIP. The possible file types are configured
 *            in the formats.properties configuration file of WebAnno.
 * @param aFile
 *            a ZIP file containing the project data.
 * @throws Exception if there was en error.
 */
@RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile,
        @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception {
    LOG.info("Creating project [" + aName + "]");

    if (!ZipUtils.isZipStream(aFile.getInputStream())) {
        throw new InvalidFileNameException("", "is an invalid Zip file");
    }

    // Get current user
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userRepository.get(username);
    Project project = null;

    // Configure project
    if (!projectRepository.existsProject(aName)) {
        project = new Project();
        project.setName(aName);

        // Create the project and initialize tags
        projectRepository.createProject(project, user);
        annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {},
                new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {},
                new String[] {});
        // Create permission for this user
        ProjectPermission permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.ADMIN);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);

        permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.USER);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);
    }
    // Existing project
    else {
        throw new IOException("The project with name [" + aName + "] exists");
    }

    // Iterate through all the files in the ZIP

    // If the current filename does not start with "." and is in the root folder of the ZIP,
    // import it as a source document
    File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip");
    aFile.transferTo(zimpFile);
    ZipFile zip = new ZipFile(zimpFile);

    for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        //
        // Get ZipEntry which is a file or a directory
        //
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // If it is the zip name, ignore it
        if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) {
            continue;
        }
        // IF the current filename is META-INF/webanno/source-meta-data.properties store it
        // as
        // project meta data
        else if (entry.toString().replace("/", "")
                .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) {
            InputStream zipStream = zip.getInputStream(entry);
            projectRepository.savePropertiesFile(project, zipStream, entry.toString());

        }
        // File not in the Zip's root folder OR not
        // META-INF/webanno/source-meta-data.properties
        else if (StringUtils.countMatches(entry.toString(), "/") > 1) {
            continue;
        }
        // If the current filename does not start with "." and is in the root folder of the
        // ZIP, import it as a source document
        else if (!FilenameUtils.getExtension(entry.toString()).equals("")
                && !FilenameUtils.getName(entry.toString()).equals(".")) {

            uploadSourceDocument(zip, entry, project, user, aFileType);
        }

    }

    LOG.info("Successfully created project [" + aName + "] for user [" + username + "]");

}