Example usage for java.util.zip ZipEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

private static boolean extract(String uri, List<ExtractionPair> extractions) {
    URL url;/*from   ww  w . jav  a2  s .c  o  m*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1));
        downloadFile.deleteOnExit();

        if (response == HttpURLConnection.HTTP_OK) {
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFile)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath());

            Set<ExtractionPair> usedExtractions = new HashSet<>();

            // Perform extractions
            try (ZipFile zipFile = new ZipFile(downloadFile)) {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();

                    // Only extract files
                    if (entry.isDirectory()) {
                        continue;
                    }

                    for (ExtractionPair extraction : extractions) {
                        String sourcePattern = extraction.source;
                        if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) {
                            usedExtractions.add(extraction);
                            LOG.debug("Found matching file {} for source pattern {}", entry.getName(),
                                    sourcePattern);
                            String filename = getSourcePatternMatch(entry.getName(), sourcePattern);
                            // Workaround: If there is no matcher in 'sourcePattern' it will return the
                            // complete path. Strip it down to the filename
                            if (filename.equals(entry.getName())) {
                                int lastIndexOf = filename.lastIndexOf('/');
                                if (lastIndexOf >= 0) {
                                    filename = filename.substring(lastIndexOf + 1);
                                }
                            }
                            String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename);
                            FileUtils.forceMkdir(new File(name).getParentFile());
                            try (InputStream in = zipFile.getInputStream(entry);
                                    FileOutputStream out = new FileOutputStream(name)) {
                                IOUtils.copy(in, out);
                            }
                            LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri);
                        }
                    }
                }
            }

            for (ExtractionPair extraction : extractions) {
                if (!usedExtractions.contains(extraction)) {
                    LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination,
                            uri);
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (IOException e) {
        LOG.error("Could not download file: {}", e.getMessage(), e);
        return false;
    }
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static InputStream getResourceStream(Entigrator entigrator, String extension$, String resource$) {
    try {/*w ww  . j av  a 2  s. com*/

        System.out.println(
                "ExtensionHandler:getResourceStream:extension=" + extension$ + " resource=" + resource$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //     System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    if (is != null)
                        return is;

                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:anotadorderelacoes.model.UtilidadesPacotes.java

/**
 * Verifica se um dado arquivo  um classificador e, se sim, qual . Faz
 * isso descompactando o arquivo e procurando pelo arquivo "meta.ars".
 * //from   w  w  w. j av a 2  s.co m
 * @param arquivo
 * 
 * @return "invalido" se no  um classificador, "svm" ou "j48" caso
 *         contrrio.
 */
public static String verificarClassificador(File arquivo) {

    String classificador = "invalido";

    try {

        ZipInputStream zis = new ZipInputStream(new FileInputStream(arquivo));
        ZipEntry ze;
        byte[] buffer = new byte[4096];

        while ((ze = zis.getNextEntry()) != null) {

            FileOutputStream fos = new FileOutputStream(ze.getName());
            int numBytes;
            while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
                fos.write(buffer, 0, numBytes);
            fos.close();
            zis.closeEntry();

            if (ze.getName().equals("meta.ars")) {
                BufferedReader br = new BufferedReader(new FileReader("meta.ars"));
                String linha;
                while ((linha = br.readLine()) != null) {
                    String[] valores = linha.split(":");
                    if (valores[0].equals("classificador"))
                        classificador = valores[1];
                }
                br.close();
            }

            new File(ze.getName()).delete();

        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
        //Logger.getLogger( "ARS logger" ).log( Level.SEVERE, null, ex );
        return classificador;
    }

    return classificador;

}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static String loadIcon(Entigrator entigrator, String extension$, String resource$) {
    try {//from  w ww.  java2  s. c om

        //System.out.println("ExtensionHandler:loadIcon:extension="+extension$+" handler="+handlerClass$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //         System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    //            System.out.println("ExtensionHandler:loadIcon:input stream="+is.toString());
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = is.read(b)) != -1) {
                        bos.write(b, 0, bytesRead);
                    }
                    byte[] ba = bos.toByteArray();
                    is.close();
                    return Base64.encodeBase64String(ba);
                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static void unzip(String sourceFile, String destDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(sourceFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry = null;

    int BUFFER_SIZE = 4096;
    while ((entry = zis.getNextEntry()) != null) {
        String dst = destDir + File.separator + entry.getName();
        if (entry.isDirectory()) {
            createDir(destDir, entry);//from   ww w.j a v  a2  s.com
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];

        // write the file to the disk
        FileOutputStream fos = new FileOutputStream(dst);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        // close the output streams
        dest.flush();
        dest.close();
    }

    zis.close();
}

From source file:com.asakusafw.lang.compiler.cli.BatchCompilerCliTest.java

static Matcher<List<ResourceRepository>> deepIncludes(String id) {
    return new BaseMatcher<List<ResourceRepository>>() {
        @Override/*  www . j  av a 2 s .c o m*/
        public boolean matches(Object item) {
            List<?> elements = (List<?>) item;
            for (Object element : elements) {
                ResourceRepository repo = (ResourceRepository) element;
                try (ResourceRepository.Cursor cursor = repo.createCursor()) {
                    while (cursor.next()) {
                        try (ZipInputStream input = new ZipInputStream(cursor.openResource())) {
                            while (true) {
                                ZipEntry entry = input.getNextEntry();
                                if (entry == null) {
                                    break;
                                }
                                if (entry.getName().equals(id)) {
                                    return true;
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new AssertionError(e);
                }
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("deep includes ").appendValue(id);
        }
    };
}

From source file:apim.restful.importexport.utils.APIImportUtil.java

/**
 * This method decompresses API the archive
 *
 * @param sourceFile  The archive containing the API
 * @param destination location of the archive to be extracted
 * @return Name of the extracted directory
 * @throws APIImportException If the decompressing fails
 *///ww  w.j  ava 2s. c o  m
public static String extractArchive(File sourceFile, String destination) throws APIImportException {

    BufferedInputStream inputStream = null;
    InputStream zipInputStream = null;
    FileOutputStream outputStream = null;
    ZipFile zip = null;
    String archiveName = null;

    try {
        zip = new ZipFile(sourceFile);
        Enumeration zipFileEntries = zip.entries();
        int index = 0;

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {

            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            //This index variable is used to get the extracted folder name; that is root directory
            if (index == 0) {
                archiveName = currentEntry.substring(0,
                        currentEntry.indexOf(APIImportExportConstants.ARCHIVE_PATH_SEPARATOR));
                --index;
            }

            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();

            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.info("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }

            if (!entry.isDirectory()) {
                zipInputStream = zip.getInputStream(entry);
                inputStream = new BufferedInputStream(zipInputStream);

                // write the current file to the destination
                outputStream = new FileOutputStream(destinationFile);
                IOUtils.copy(inputStream, outputStream);
            }
        }
        return archiveName;
    } catch (IOException e) {
        log.error("Failed to extract archive file ", e);
        throw new APIImportException("Failed to extract archive file. " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

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);//from w  w  w  .  ja  va 2s. 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:gdt.data.entity.facet.ExtensionHandler.java

public static String[] listResourcesByType(String jar$, String type$) {
    try {/*from  ww  w  . j  a  v a2 s.c  o m*/

        ArrayList<String> sl = new ArrayList<String>();
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        String resource$;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                resource$ = sa[sa.length - 1];
                //     System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (type$.equals(FileExpert.getExtension(resource$))) {
                    sl.add(resource$);
                }
            } catch (Exception e) {

            }
        }
        return sl.toArray(new String[0]);
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:com.taobao.android.utils.ZipUtils.java

/**
 * zip/*  w  w  w  . j a  va 2s . com*/
 *
 * @param zipFile
 * @param file
 * @param destPath  ?
 * @param overwrite ?
 * @throws IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (ZipEntry.STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Close the streams
    zin.close();
    out.close();
}