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:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private static void openZipStream(InputStream inputStream, Map<String, Map<String, String>> volPageContents,
        boolean isConcat) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry = null;
    String currentVolID = null;/*from  w  w  w.  j a  v  a2  s .  c  o m*/

    if (!isConcat) {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            if (zipEntry.isDirectory()) {
                // get volume name
                currentVolID = name.split("/")[0];
                volPageContents.put(currentVolID, new HashMap<String, String>());

                if (log.isDebugEnabled())
                    log.debug("Encounter volueme directory : " + currentVolID);

            } else {
                String[] names = name.split("/");

                // each page is a separate entry
                //               assert names.length == 2;
                //               assert names[0].equals(currentVolID);

                // get page(s) content
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                Map<String, String> contents = volPageContents.get(currentVolID);

                int idx = names[1].indexOf(".txt");
                //               assert idx != -1;

                contents.put(names[1].substring(0, idx), sb.toString());
            }
        }
    } else {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            assert !zipEntry.isDirectory();
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            int idx = name.indexOf(".txt");
            //            assert idx != -1;
            String cleanedVolId = name.substring(0, idx);

            if (log.isDebugEnabled())
                log.debug("Encounter volueme whole entry : " + cleanedVolId);

            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            HashMap<String, String> concatContent = new HashMap<String, String>();
            concatContent.put(DataAPIWrapper.WHOLE_CONTENT, sb.toString());
            volPageContents.put(cleanedVolId, concatContent);
        }
    }
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs)
        throws IOException {
    Attributes attrs;//  w  w w .  j av  a2  s.c  o m
    if (jar.getManifest() == null)
        return null;

    JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
    if (manifest_entry == null)
        manifest_entry = jar.stream()
                .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst()
                .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.

    attrs = jar.getManifest().getMainAttributes();

    String modSide = attrs.getValue(LibraryManager.MODSIDE);
    if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
        return null;

    if (attrs.containsKey(MODCONTAINSDEPS)) {
        for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) {
            if (!dep.endsWith(".jar")) {
                FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
            }

            if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
                dep = "META-INF/libraries/" + dep;

            JarEntry depEntry = jar.getJarEntry(dep);
            if (depEntry == null) {
                FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
            }

            String depEndName = new File(dep).getName(); // extract last part of name
            if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
                FMLLog.log.error("Skipping dep at request: {}", dep);
                continue;
            }

            Attributes meta = null;
            byte[] data = null;
            byte[] manifest_data = null;

            JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
            if (metaEntry != null) {
                manifest_data = readAll(jar.getInputStream(metaEntry));
                meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
            } else {
                data = readAll(jar.getInputStream(depEntry));
                try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
                {
                    ZipEntry ze = null;
                    while ((ze = zi.getNextEntry()) != null) {
                        if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
                            manifest_data = readAll(zi);
                            meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
                            break;
                        }
                    }
                }
            }

            if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
            {
                boolean found = false;
                for (File dir : modDirs) {
                    File target = new File(dir, depEndName);
                    if (target.exists()) {
                        FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction",
                                target.getCanonicalPath());
                        found = true;
                    }
                }
                if (!found) {
                    File target = new File(modDirs[0], depEndName);
                    FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(),
                            target.getCanonicalPath());
                    try {
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(),
                                target.getCanonicalPath());
                        extractPacked(target, modlist, modDirs);
                    } catch (IOException e) {
                        FMLLog.log.error("An error occurred extracting dependency", e);
                    }
                }
            } else {
                try {
                    Artifact artifact = readArtifact(modlist.getRepository(), meta);
                    File target = artifact.getFile();
                    if (target.exists()) {
                        FMLLog.log.debug(
                                "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction",
                                dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
                        if (!ENABLE_AUTO_MOD_MOVEMENT) {
                            Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
                            if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                            {
                                modlist.add(artifact);
                            }
                        }
                    } else {
                        FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());

                        if (artifact.isSnapshot()) {
                            SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
                            json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
                            json.write(artifact.getSnapshotMeta());
                        }

                        if (!DISABLE_EXTERNAL_MANIFEST) {
                            File meta_target = new File(target.getAbsolutePath() + ".meta");
                            Files.write(manifest_data, meta_target);
                        }
                        Pair<?, ?> child = extractPacked(target, modlist, modDirs);
                        if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                        {
                            modlist.add(artifact);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                            "An error occurred extracting dependency. Invalid Timestamp: {}",
                            meta.getValue(TIMESTAMP)), nfe);
                } catch (IOException e) {
                    FMLLog.log.error("An error occurred extracting dependency", e);
                }
            }
        }
    }

    if (attrs.containsKey(MAVEN_ARTIFACT)) {
        Artifact artifact = readArtifact(modlist.getRepository(), attrs);
        modlist.add(artifact);
        return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
    }
    return null;
}

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

/****************************************************************************
 **/*from w  w w.j a va 2  s . c om*/
 ** Method:   locateMetadata()
 ** Input:  String zipFileName  --  The name of the zip file to be used
 ** Output: Vector  --  A vector of the names of xml files.  
 **
 ** Description: This method takes in the name of a zip file and locates 
 **              all files with an .xml extension an adds their names to a 
 **              vector. 
 **              
 *****************************************************************************/
public static Vector locateMetadata(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in locateMetadata()    ");
        System.out.println("***********************\n");
    }

    //  An array of names of xml files to be returned to ColdFusion
    Vector metaDataVector = new Vector();
    String suffix = ".xml";

    try {
        //  The zip file being searched.
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        //  An entry in the zip file
        ZipEntry entry;

        if (_Debug) {
            System.out.println("Other meta-data located:");
        }
        while ((in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).endsWith(suffix)) {
                    if (_Debug) {
                        System.out.println(entry.getName());
                    }
                    metaDataVector.addElement(entry.getName());
                }
            }
        }
        in.close();

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

From source file:com.blazemeter.bamboo.plugin.ServiceManager.java

public static void unzip(String srcZipFileName, String destDirectoryName, BuildLogger logger) {
    try {/*from   w ww. j a  v  a 2  s.com*/
        BufferedInputStream bufIS = null;
        // create the destination directory structure (if needed)
        File destDirectory = new File(destDirectoryName);
        destDirectory.mkdirs();

        // open archive for reading
        File file = new File(srcZipFileName);
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);

        //for every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            logger.addBuildLogEntry("\tExtracting jtl report: " + entry);

            //create destination file
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            bufIS = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte data[] = new byte[BUFFER_SIZE];

            // write the current file to disk
            FileOutputStream fOS = new FileOutputStream(destFile);
            BufferedOutputStream bufOS = new BufferedOutputStream(fOS, BUFFER_SIZE);

            while ((currentByte = bufIS.read(data, 0, BUFFER_SIZE)) != -1) {
                bufOS.write(data, 0, currentByte);
            }

            // close BufferedOutputStream
            bufOS.flush();
            bufOS.close();
        }
        bufIS.close();
    } catch (Exception e) {
        logger.addErrorLogEntry("Failed to unzip report: check that it is downloaded");
    }
}

From source file:cn.ipanel.apps.portalBackOffice.util.CommonsFiend.java

/**
 * marqueezip//from  ww w  .  j ava 2  s  .  c o  m
 * @param imageList
 * @param zipfilePath
 * @return
 */
public static boolean validateMarqueeZipPic(List imageList, String zipfilePath) {
    if (imageList.size() == 0) {
        return true; //zip
    }
    if (FileFiend.judgeFileZip(zipfilePath) == false) { //zip
        return false;
    }
    boolean result = true;
    InputStream in = null;
    ZipInputStream zipInput = null;
    List zipPicList = new ArrayList();
    try {
        File file = new File(zipfilePath);
        in = new FileInputStream(file);
        zipInput = new ZipInputStream(in);
        ZipEntry zipEntry = null;
        while ((zipEntry = zipInput.getNextEntry()) != null) {
            String fileName = zipEntry.getName();
            if (CommonsFiend.validateImgFormat(fileName) == false) { //marqueeContent
                return false;
            }
            zipPicList.add(fileName);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (zipInput != null) {
                zipInput.closeEntry();
                zipInput.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    for (int i = 0; i < imageList.size(); i++) {
        String imageName = (String) imageList.get(i);
        boolean contain = false;
        for (int j = 0; j < zipPicList.size(); j++) {
            String fileName = (String) zipPicList.get(j);
            if (imageName.equals(fileName)) {
                contain = true; //
                break;
            }
        }
        if (contain == false) { //
            result = false;
            break;
        }
    }

    return result;
}

From source file:com.glaf.core.util.ZipUtils.java

public static byte[] getBytes(ZipInputStream zipInputStream, String name) {
    byte[] bytes = null;
    try {/*ww w  . jav a2  s  .  c  om*/
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String entryName = zipEntry.getName();
            if (entryName.equalsIgnoreCase(name)) {
                bytes = FileUtils.getBytes(zipInputStream);
                if (bytes != null) {
                    break;
                }
            }
            zipEntry = zipInputStream.getNextEntry();
        }
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

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

public static InputStream getResourceStream(String jar$, String resource$) {
    try {/*  w  ww. ja  v  a 2s. co m*/
        //      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:net.rptools.lib.FileUtil.java

public static void unzipFile(File sourceFile, File destDir) throws IOException {
    if (!sourceFile.exists())
        throw new IOException("source file does not exist: " + sourceFile);

    ZipFile zipFile = null;/* w w w.ja  v a  2s  . co m*/
    InputStream is = null;
    OutputStream os = null;
    try {
        zipFile = new ZipFile(sourceFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory())
                continue;

            File file = new File(destDir, entry.getName());
            String path = file.getAbsolutePath();
            file.getParentFile().mkdirs();

            //System.out.println("Writing file: " + path);
            is = zipFile.getInputStream(entry);
            os = new BufferedOutputStream(new FileOutputStream(path));
            copyWithClose(is, os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        try {
            if (zipFile != null)
                zipFile.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.glaf.core.util.ZipUtils.java

public static byte[] getBytes(InputStream inputStream, String name) {
    byte[] bytes = null;
    ZipInputStream zipInputStream = null;
    try {//from   www .  ja  v  a2  s. com
        zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String entryName = zipEntry.getName();
            if (entryName.equalsIgnoreCase(name)) {
                bytes = FileUtils.getBytes(zipInputStream);
                if (bytes != null) {
                    break;
                }
            }
            zipEntry = zipInputStream.getNextEntry();
        }
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
    }
}

From source file:com.microsoft.intellij.helpers.IDEHelperImpl.java

private static void copyJarFiles(@NotNull final Module module, @NotNull VirtualFile baseDir,
        @NotNull File zipFile, @NotNull String zipPath) throws IOException {
    if (baseDir.isDirectory()) {
        final ZipFile zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            final ZipEntry zipEntry = entries.nextElement();

            if (!zipEntry.isDirectory() && zipEntry.getName().startsWith(zipPath)
                    && zipEntry.getName().endsWith(".jar") && !(zipEntry.getName().endsWith("-sources.jar")
                            || zipEntry.getName().endsWith("-javadoc.jar"))) {
                VirtualFile libsVf = null;

                for (VirtualFile vf : baseDir.getChildren()) {
                    if (vf.getName().equals("libs")) {
                        libsVf = vf;//from  ww w.  ja  v  a  2  s  .  c  om
                        break;
                    }
                }

                if (libsVf == null) {
                    libsVf = baseDir.createChildDirectory(module.getProject(), "libs");
                }

                final VirtualFile libs = libsVf;
                final String fileName = zipEntry.getName().split("/")[1];

                if (libs.findChild(fileName) == null) {
                    ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        InputStream mobileserviceInputStream = zip.getInputStream(zipEntry);
                                        VirtualFile msVF = libs.createChildData(module.getProject(), fileName);
                                        msVF.setBinaryContent(getArray(mobileserviceInputStream));
                                    } catch (Throwable ex) {
                                        DefaultLoader.getUIHelper().showException(
                                                "An error occurred while attempting "
                                                        + "to configure Azure Mobile Services.",
                                                ex,
                                                "Azure Services Explorer - Error Configuring Mobile Services",
                                                false, true);
                                    }
                                }
                            });
                        }
                    }, ModalityState.defaultModalityState());
                }
            }
        }
    }
}