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.mgmtp.jfunk.data.source.ArchiveDataSource.java

private Map<String, DataSet> getDataSets() {
    if (dataSets == null) {
        String archiveFileName = configuration.get("dataSource." + getName() + ".archiveFileName");
        if (archiveFileName == null) {
            throw new IllegalStateException("No archive files configured.");
        }//  w w w.  j a  va  2s .  c om
        log.info("Using " + archiveFileName);

        dataSets = newHashMap();
        try {
            ZipFile zip = new ZipFile(archiveFileName);
            for (Enumeration<? extends ZipEntry> zipEntryEnum = zip.entries(); zipEntryEnum
                    .hasMoreElements();) {
                ZipEntry zipEntry = zipEntryEnum.nextElement();
                String name = zipEntry.getName();
                Matcher matcher = KEY_PATTERN.matcher(name);
                if (matcher.find()) {
                    InputStream is = null;
                    try {
                        is = zip.getInputStream(zipEntry);
                        String key = matcher.group(1);
                        ExtendedProperties props = new ExtendedProperties();
                        props.load(is);
                        log.debug("Adding data for key=" + key);
                        dataSets.put(key, new DefaultDataSet(props));
                    } finally {
                        closeQuietly(is);
                    }
                }
            }
        } catch (IOException ex) {
            throw new JFunkException("Error getting data sets.", ex);
        }
    }
    return dataSets;
}

From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPaths.java

private void ExtractStructuralFeaturesInMemory(String filePath, Map<String, Integer> structuralPaths) {
    String path;/*from w w w.  j  a v  a 2s  .  c om*/
    String directoryPath;
    String fileExtension;
    try {
        ZipFile zipFile = new ZipFile(filePath);

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            path = entry.getName();
            directoryPath = FilenameUtils.getFullPath(path);
            fileExtension = FilenameUtils.getExtension(path);

            AddStructuralPath(directoryPath, structuralPaths);
            AddStructuralPath(path, structuralPaths);

            if (fileExtension.equals("rels") || fileExtension.equals("xml")) {
                AddXMLStructuralPaths(zipFile.getInputStream(entry), path, structuralPaths);
            }
        }
    } catch (IOException ex) {
        Console.PrintException(
                String.format("Error extracting OOXML structural features from file: %s", filePath), ex);
    }
}

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 );
    }/*  w  w  w  .  ja v  a2s .  co  m*/
    return null;
}

From source file:com.heliosdecompiler.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;/*from www .jav a 2 s  . c  o m*/
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O",
                    "disassemble.py", "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:com.samczsun.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;//ww w. ja  v  a 2  s . c o m
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.samczsun.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O", "disassemble.py",
                    "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:com.silverpeas.wiki.WikiInstanciator.java

protected void createPages(File directory, String componentId) throws IOException, WikiException {
    ZipInputStream zipFile = new ZipInputStream(loader.getResourceAsStream("pages.zip"));
    ZipEntry page = zipFile.getNextEntry();
    while (page != null) {
        String pageName = page.getName();
        File newPage = new File(directory, pageName);
        if (page.isDirectory()) {
            newPage.mkdirs();/*w  ww  .j a  v a2s. com*/
        } else {
            FileUtil.writeFile(newPage, new InputStreamReader(zipFile, "UTF-8"));
            PageDetail newPageDetail = new PageDetail();
            newPageDetail.setInstanceId(componentId);
            newPageDetail.setPageName(pageName.substring(0, pageName.lastIndexOf('.')));
            wikiDAO.createPage(newPageDetail);
            zipFile.closeEntry();
            page = zipFile.getNextEntry();
        }
    }
}

From source file:UnZip.java

/**
 * Process one file from the zip, given its name. Either print the name, or
 * create the file on disk.//from  w w  w  .j a  va 2  s .co m
 */
protected void getFile(ZipEntry e) throws IOException {
    String zipName = e.getName();
    switch (mode) {
    case EXTRACT:
        if (zipName.startsWith("/")) {
            if (!warnedMkDir)
                System.out.println("Ignoring absolute paths");
            warnedMkDir = true;
            zipName = zipName.substring(1);
        }
        // if a directory, just return. We mkdir for every file,
        // since some widely-used Zip creators don't put out
        // any directory entries, or put them in the wrong place.
        if (zipName.endsWith("/")) {
            return;
        }
        // Else must be a file; open the file for output
        // Get the directory part.
        int ix = zipName.lastIndexOf('/');
        if (ix > 0) {
            String dirName = zipName.substring(0, ix);
            if (!dirsMade.contains(dirName)) {
                File d = new File(dirName);
                // If it already exists as a dir, don't do anything
                if (!(d.exists() && d.isDirectory())) {
                    // Try to create the directory, warn if it fails
                    System.out.println("Creating Directory: " + dirName);
                    if (!d.mkdirs()) {
                        System.err.println("Warning: unable to mkdir " + dirName);
                    }
                    dirsMade.add(dirName);
                }
            }
        }
        System.err.println("Creating " + zipName);
        FileOutputStream os = new FileOutputStream(zipName);
        InputStream is = zippy.getInputStream(e);
        int n = 0;
        while ((n = is.read(b)) > 0)
            os.write(b, 0, n);
        is.close();
        os.close();
        break;
    case LIST:
        // Not extracting, just list
        if (e.isDirectory()) {
            System.out.println("Directory " + zipName);
        } else {
            System.out.println("File " + zipName);
        }
        break;
    default:
        throw new IllegalStateException("mode value (" + mode + ") bad");
    }
}

From source file:com.intuit.tank.agent.AgentStartup.java

public void run() {
    logger.info("Starting up...");
    if (AmazonUtil.usingEip()) {
        try {/* w  w  w  .j  a  va2  s. c  o m*/
            logger.info("Using EIP. Sleeping for " + WAIT_FOR_RESTART_TIME + " ms.");
            Thread.sleep(WAIT_FOR_RESTART_TIME);
        } catch (InterruptedException e1) {
            logger.info("Exception waiting.");
            System.exit(0);
        }
    }
    try {
        if (controllerBase == null) {
            controllerBase = AmazonUtil.getControllerBaseUrl();
        }

        logger.info("Starting up: ControllerBaseUrl=" + controllerBase);
        URL url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SETTINGS);
        logger.info("Starting up: making call to tank service url to get settings.xml " + url.toExternalForm());
        InputStream settingsStream = url.openStream();
        try {
            String settings = IOUtils.toString(settingsStream);
            FileUtils.writeStringToFile(new File("settings.xml"), settings);
            logger.info("got settings file...");
        } finally {
            IOUtils.closeQuietly(settingsStream);
        }
        url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SUPPORT);
        logger.info("Making call to tank service url to get support files " + url.toExternalForm());
        ZipInputStream zip = new ZipInputStream(url.openStream());
        try {
            ZipEntry entry = zip.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                logger.info("Got file from controller: " + name);
                File f = new File(name);
                FileOutputStream fout = FileUtils.openOutputStream(f);
                try {
                    IOUtils.copy(zip, fout);
                } finally {
                    IOUtils.closeQuietly(fout);
                }
                entry = zip.getNextEntry();
            }
        } finally {
            IOUtils.closeQuietly(zip);
        }
        // now start the harness
        String jvmArgs = AmazonUtil.getUserDataAsMap().get(TankConstants.KEY_JVM_ARGS);
        logger.info("Starting apiharness with command: " + API_HARNESS_COMMAND + " -http=" + controllerBase
                + " " + jvmArgs);
        Runtime.getRuntime().exec(API_HARNESS_COMMAND + " -http=" + controllerBase + " " + jvmArgs);
    } catch (Exception e) {
        logger.error("Error in AgentStartup " + e, e);
    }
}

From source file:net.minecraftforge.fml.common.discovery.JarDiscoverer.java

@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table) {
    List<ModContainer> foundMods = Lists.newArrayList();
    FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName());
    JarFile jar = null;/*ww w.  j  a  v  a  2s . c o m*/
    try {
        jar = new JarFile(candidate.getModContainer());

        ZipEntry modInfo = jar.getEntry("mcmod.info");
        MetadataCollection mc = null;
        if (modInfo != null) {
            FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName());
            InputStream inputStream = jar.getInputStream(modInfo);
            try {
                mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName());
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        } else {
            FMLLog.fine("The mod container %s appears to be missing an mcmod.info file",
                    candidate.getModContainer().getName());
            mc = MetadataCollection.from(null, "");
        }
        for (ZipEntry ze : Collections.list(jar.entries())) {
            if (ze.getName() != null && ze.getName().startsWith("__MACOSX")) {
                continue;
            }
            Matcher match = classFile.matcher(ze.getName());
            if (match.matches()) {
                ASMModParser modParser;
                try {
                    InputStream inputStream = jar.getInputStream(ze);
                    try {
                        modParser = new ASMModParser(inputStream);
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                    }
                    candidate.addClassEntry(ze.getName());
                } catch (LoaderException e) {
                    FMLLog.log(Level.ERROR, e,
                            "There was a problem reading the entry %s in the jar %s - probably a corrupt zip",
                            ze.getName(), candidate.getModContainer().getPath());
                    jar.close();
                    throw e;
                }
                modParser.validate();
                modParser.sendToTable(table, candidate);
                ModContainer container = ModContainerFactory.instance().build(modParser,
                        candidate.getModContainer(), candidate);
                if (container != null) {
                    table.addContainer(container);
                    foundMods.add(container);
                    container.bindMetadata(mc);
                    container.setClassVersion(modParser.getClassVersion());
                }
            }
        }
    } catch (Exception e) {
        FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored",
                candidate.getModContainer().getName());
    } finally {
        Java6Utils.closeZipQuietly(jar);
    }
    return foundMods;
}

From source file:com.joliciel.talismane.machineLearning.ModelFactory.java

public MachineLearningModel getMachineLearningModel(ZipInputStream zis) {
    try {/*from w  ww.j  ava  2  s  . c  om*/
        MachineLearningModel machineLearningModel = null;
        ZipEntry ze = zis.getNextEntry();
        if (!ze.getName().equals("algorithm.txt")) {
            throw new JolicielException("Expected algorithm.txt as first entry in zip. Was: " + ze.getName());
        }

        // note: assuming the model type will always be the first entry
        Scanner typeScanner = new Scanner(zis, "UTF-8");
        MachineLearningAlgorithm algorithm = MachineLearningAlgorithm.MaxEnt;
        if (typeScanner.hasNextLine()) {
            String algorithmString = typeScanner.nextLine();
            try {
                algorithm = MachineLearningAlgorithm.valueOf(algorithmString);
            } catch (IllegalArgumentException iae) {
                LogUtils.logError(LOG, iae);
                throw new JolicielException("Unknown algorithm: " + algorithmString);
            }
        } else {
            throw new JolicielException("Cannot find algorithm in zip file");
        }
        switch (algorithm) {
        case MaxEnt:
            machineLearningModel = maxentService.getMaxentModel();
            break;
        case LinearSVM:
            machineLearningModel = linearSVMService.getLinearSVMModel();
            break;
        case Perceptron:
            machineLearningModel = perceptronService.getPerceptronModel();
            break;
        case PerceptronRanking:
            machineLearningModel = perceptronService.getPerceptronRankingModel();
            break;
        case OpenNLPPerceptron:
            machineLearningModel = maxentService.getPerceptronModel();
            break;
        default:
            throw new JolicielException("Machine learning algorithm not yet supported: " + algorithm);
        }

        while ((ze = zis.getNextEntry()) != null) {
            LOG.debug(ze.getName());
            machineLearningModel.loadZipEntry(zis, ze);
        } // next zip entry

        machineLearningModel.onLoadComplete();

        return machineLearningModel;
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    } finally {
        try {
            zis.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
        }
    }
}