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:com.celements.photo.utilities.Unzip.java

/**
 * Get a List of names of all files contained in the zip file.
 * //from w  w w  . j  a  v a2s. co  m
 * @param zipFile byte array of the zip file.
 * @return List of all filenames (and directory names - ending with a file seperator) contained in the zip file.
 */
public List<String> getZipContentList(byte[] zipFile) {
    String fileSep = System.getProperty("file.separator");
    List<String> contentList = new ArrayList<String>();
    ZipInputStream zipStream = getZipInputStream(zipFile);

    try {
        while (zipStream.available() > 0) {
            ZipEntry entry = zipStream.getNextEntry();
            if (entry != null) {
                String fileName = entry.getName();
                if (entry.isDirectory() && !fileName.endsWith(fileSep)) {
                    fileName += fileSep;
                }
                contentList.add(fileName);
            }
        }
    } catch (IOException e) {
        mLogger.error(e);
    }

    return contentList;
}

From source file:com.izforge.izpack.compiler.helper.CompilerHelper.java

/**
 * Returns the qualified class name for the given class. This method expects as the url param a
 * jar file which contains the given class. It scans the zip entries of the jar file.
 *
 * @param url       url of the jar file which contains the class
 * @param className short name of the class for which the full name should be resolved
 * @return full qualified class name/*from  w ww  . j av  a 2  s.  c  o  m*/
 * @throws IOException if the jar cannot be read
 */
public String getFullClassName(URL url, String className) throws IOException {
    JarInputStream jis = new JarInputStream(url.openStream());
    ZipEntry zentry;
    while ((zentry = jis.getNextEntry()) != null) {
        String name = zentry.getName();
        int lastPos = name.lastIndexOf(".class");
        if (lastPos < 0) {
            continue; // No class file.
        }
        name = name.replace('/', '.');
        int pos = -1;
        int nonCasePos = -1;
        if (className != null) {
            pos = name.indexOf(className);
            nonCasePos = name.toLowerCase().indexOf(className.toLowerCase());
        }
        if (pos != -1 && name.length() == pos + className.length() + 6) // "Main" class found
        {
            jis.close();
            return (name.substring(0, lastPos));
        }

        if (nonCasePos != -1 && name.length() == nonCasePos + className.length() + 6)
        // "Main" class with different case found
        {
            throw new IllegalArgumentException("Fatal error! The declared panel name in the xml file ("
                    + className + ") differs in case to the founded class file (" + name + ").");
        }
    }
    jis.close();
    return (null);
}

From source file:com.google.cloud.tools.gradle.appengine.sourcecontext.SourceContextPluginIntegrationTest.java

/** Create a test project with git source context. */
public void setUpTestProject() throws IOException {
    Path buildFile = testProjectDir.getRoot().toPath().resolve("build.gradle");

    Path src = Files.createDirectory(testProjectDir.getRoot().toPath().resolve("src"));
    InputStream buildFileContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/build.gradle");
    Files.copy(buildFileContent, buildFile);

    Path gitContext = testProjectDir.getRoot().toPath().resolve("gitContext.zip");
    InputStream gitContextContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/gitContext.zip");
    Files.copy(gitContextContent, gitContext);

    try (ZipFile zipFile = new ZipFile(gitContext.toFile())) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(testProjectDir.getRoot(), entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);// w  w  w .  j  a  va 2s . co m
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    }

    FileUtils.delete(gitContext.toFile());

    Path webInf = testProjectDir.getRoot().toPath().resolve("src/main/webapp/WEB-INF");
    Files.createDirectories(webInf);
    File appengineWebXml = Files.createFile(webInf.resolve("appengine-web.xml")).toFile();
    Files.write(appengineWebXml.toPath(), "<appengine-web-app/>".getBytes(Charsets.UTF_8));
}

From source file:com.wso2mobile.mam.packageExtractor.ZipFileReading.java

public String readiOSManifestFile(String filePath, String name) {
    String plist = "";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {//from w  w w .  j  a v  a  2 s  .com
        File file = new File(filePath);
        ZipInputStream stream = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                if (entry.getName().equals("Payload/" + name + ".app/Info.plist")) {
                    InputStream is = stream;

                    int nRead;
                    byte[] data = new byte[16384];

                    while ((nRead = is.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, nRead);
                    }

                    buffer.flush();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }
        NSDictionary rootDict = (NSDictionary) BinaryPropertyListParser.parse(buffer.toByteArray());
        JSONObject obj = new JSONObject();
        obj.put("version", rootDict.objectForKey("CFBundleVersion").toString());
        obj.put("name", rootDict.objectForKey("CFBundleName").toString());
        obj.put("package", rootDict.objectForKey("CFBundleIdentifier").toString());
        plist = obj.toJSONString();
    } catch (Exception e) {
        plist = "Exception occured " + e;
        e.printStackTrace();
    }
    return plist;
}

From source file:ac.simons.tweetarchive.web.ArchiveHandlingController.java

/**
 * As you can see, it get's nasty here...
 * <br>/*from  w  w  w  .jav a  2  s .c  om*/
 * Twitter4j doesn't offer an official way to parse Twitters JSON, so I
 * brute force my way into the twitter4j.StatusJSONImpl implementation of
 * Status.
 * <br>
 * And even if there was an official way, the JSON files inside the
 * official(!) Twitter archive differ from the API, even if they are said to
 * be identical. By the way, I'm not the only one, who
 * <a href="https://twittercommunity.com/t/why-does-twitter-json-archive-have-a-different-format-than-the-rest-api-1-1/35530">noticed
 * that</a>.
 * <br>
 * Furthermore, I didn't even bother to add error handling or tests.
 *
 * @param archive The uploaded archive
 * @return Redirect to the index
 * @throws java.io.IOException
 * @throws twitter4j.JSONException
 */
@PostMapping
public String store(@NotNull final MultipartFile archive, final RedirectAttributes redirectAttributes)
        throws IOException, JSONException {
    try (final ZipInputStream archiv = new ZipInputStream(archive.getInputStream())) {
        ZipEntry entry;
        while ((entry = archiv.getNextEntry()) != null) {
            if (!entry.getName().startsWith("data/js/tweets/") || entry.isDirectory()) {
                continue;
            }
            log.debug("Reading archive entry {}...", entry.getName());
            final BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(archiv, StandardCharsets.UTF_8));

            final String content = buffer.lines().skip(1).map(l -> {
                Matcher m = PATTERN_CREATED_AT.matcher(l);
                String rv = l;
                if (m.find()) {
                    try {
                        rv = m.replaceFirst(
                                "$1\"" + DATE_FORMAT_OUT.format(DATE_FORMAT_IN.parse(m.group(2))) + "\"");
                    } catch (ParseException ex) {
                        log.warn("Unexpected date format in twitter archive", ex);
                    }
                }
                return rv;
            }).collect(Collectors.joining("")).replaceAll("\"sizes\" : \\[.+?\\],", "\"sizes\" : {},");

            final JSONArray statuses = new JSONArray(content);
            for (int i = 0; i < statuses.length(); ++i) {
                final JSONObject rawJSON = statuses.getJSONObject(i);
                // https://twitter.com/lukaseder/status/772772372990586882 ;)
                final Status status = statusFactory.create(rawJSON).as(Status.class);
                this.tweetStorageService.store(status, rawJSON.toString());
            }
        }
    }
    redirectAttributes.addFlashAttribute("message", "Done.");
    return "redirect:/upload";
}

From source file:JarResource.java

private List<String> load(File jarFile) throws IOException {
    List<String> jarContents = new ArrayList<String>();
    try {//from   w  w  w  .  j  av a  2s  .co  m
        ZipFile zf = new ZipFile(jarFile);
        for (Enumeration e = zf.entries(); e.hasMoreElements();) {
            ZipEntry ze = (ZipEntry) e.nextElement();
            if (ze.isDirectory()) {
                continue;
            }
            jarContents.add(ze.getName());
        }
    } catch (NullPointerException e) {
        System.out.println("done.");
    } catch (ZipException ze) {
        ze.printStackTrace();
    }
    return jarContents;
}

From source file:com.wavemaker.tools.project.upgrade.UpgradeTemplateFile.java

@Override
public void doUpgrade(Project project, UpgradeInfo upgradeInfo) {

    if (this.relativePath == null) {
        throw new WMRuntimeException("No file provided");
    }/* ww  w .  ja  va2s. c o m*/

    try {
        File localFile = project.getRootFolder().getFile(this.relativePath);

        InputStream resourceStream = this.getClass().getClassLoader()
                .getResourceAsStream(ProjectManager._TEMPLATE_APP_RESOURCE_NAME);
        ZipInputStream resourceZipStream = new ZipInputStream(resourceStream);

        ZipEntry zipEntry = null;

        while ((zipEntry = resourceZipStream.getNextEntry()) != null) {
            if (this.relativePath.equals(zipEntry.getName())) {
                Writer writer = localFile.getContent().asWriter();
                IOUtils.copy(resourceZipStream, writer);
                writer.close();
            }
        }

        resourceZipStream.close();
        resourceStream.close();
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }

    if (this.message != null) {
        upgradeInfo.addMessage(this.message);
    }
}

From source file:com.arykow.autotools.generator.App.java

private void generate() throws Exception {
    File directory = new File(projectDirectory);
    if (!directory.isDirectory()) {
        throw new RuntimeException();
    }/*  ww  w .ja va 2 s  .c  o  m*/
    File output = new File(directory, projectName);
    if (output.exists()) {
        if (projectForced) {
            if (!output.isDirectory()) {
                throw new RuntimeException();
            }
        } else {
            throw new RuntimeException();
        }
    } else if (!output.mkdir()) {
        throw new RuntimeException();
    }

    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    if (src != null) {
        URL jar = src.getLocation();
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        while (true) {
            ZipEntry e = zip.getNextEntry();
            if (e == null)
                break;
            if (!e.isDirectory() && e.getName().startsWith(String.format("%s", templateName))) {
                // generate(output, e);

                StringWriter writer = new StringWriter();
                IOUtils.copy(zip, writer);
                String content = writer.toString();

                Map<String, String> expressions = new HashMap<String, String>();
                expressions.put("author", "Karim DRIDI");
                expressions.put("name_undescore", projectName);
                expressions.put("license", "<Place your desired license here.>");
                expressions.put("name", projectName);
                expressions.put("version", "1.0");
                expressions.put("copyright", "Your copyright notice");
                expressions.put("description", "Hello World in C++,");

                for (Map.Entry<String, String> entry : expressions.entrySet()) {
                    content = content.replaceAll(String.format("<project\\.%s>", entry.getKey()),
                            entry.getValue());
                }

                String name = e.getName().substring(templateName.length() + 1);
                if ("gitignore".equals(name)) {
                    name = ".gitignore";
                }
                File file = new File(output, name);
                File parent = file.getParentFile();
                if (parent.exists()) {
                    if (!parent.isDirectory()) {
                        throw new RuntimeException();
                    }
                } else {
                    if (!parent.mkdirs()) {
                        throw new RuntimeException();
                    }
                }
                OutputStream stream = new FileOutputStream(file);
                IOUtils.copy(new StringReader(content), stream);
                IOUtils.closeQuietly(stream);
            }
        }
    }
}

From source file:eu.scape_project.up2ti.container.ZipContainer.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param containerFileName//from w w w. j a va2  s.c o  m
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String containerFileName, InputStream containerFileStream) throws IOException {
    extractDirectoryName = "/tmp/up2ti_" + RandomStringUtils.randomAlphabetic(10) + "/";
    File destDir = new File(extractDirectoryName);
    destDir.mkdir();
    String subDestDirStr = extractDirectoryName + containerFileName + "/";
    File subDestDir = new File(subDestDirStr);
    subDestDir.mkdir();
    ZipInputStream zipIn = new ZipInputStream(containerFileStream);
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = subDestDirStr + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:net.daboross.bukkitdev.skywars.world.WorldUnzipper.java

public void doWorldUnzip(Logger logger) throws StartupFailedException {
    Validate.notNull(logger, "Logger cannot be null");
    Path outputDir = Bukkit.getWorldContainer().toPath().resolve(Statics.BASE_WORLD_NAME);
    if (Files.exists(outputDir)) {
        return;/* ww w . ja v a  2  s.co  m*/
    }
    try {
        Files.createDirectories(outputDir);
    } catch (IOException e) {
        throw new StartupFailedException("Couldn't create directory " + outputDir.toAbsolutePath() + ".");
    }

    InputStream fis = WorldUnzipper.class.getResourceAsStream(Statics.ZIP_FILE_PATH);
    if (fis == null) {
        throw new StartupFailedException("Couldn't get resource.\nError creating world. Please delete "
                + Statics.BASE_WORLD_NAME + " and restart server.");
    }
    try {
        try (ZipInputStream zis = new ZipInputStream(fis)) {
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();
                Path newFile = outputDir.resolve(fileName);
                Path parent = newFile.getParent();
                if (parent != null) {
                    Files.createDirectories(parent);
                }
                if (ze.isDirectory()) {
                    logger.log(Level.FINER, "Making dir {0}", newFile);
                    Files.createDirectories(newFile);
                } else if (Files.exists(newFile)) {
                    logger.log(Level.FINER, "Already exists {0}", newFile);
                } else {
                    logger.log(Level.FINER, "Copying {0}", newFile);
                    try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
                        try {
                            int next;
                            while ((next = zis.read()) != -1) {
                                fos.write(next);
                            }
                            fos.flush();
                        } catch (IOException ex) {
                            logger.log(Level.WARNING, "Error copying file from zip", ex);
                            throw new StartupFailedException("Error creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.");
                        }
                        fos.close();
                    }
                }
                try {
                    ze = zis.getNextEntry();
                } catch (IOException ex) {
                    throw new StartupFailedException(
                            "Error getting next zip entry\nError creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.",
                            ex);
                }
            }
        }
    } catch (IOException | RuntimeException ex) {
        throw new StartupFailedException(
                "\nError unzipping world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.",
                ex);
    }
}