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.opengamma.integration.copier.portfolio.reader.ZippedPortfolioReader.java

private PortfolioReader getReader(ZipEntry entry) {

    if (!entry.isDirectory()
            && entry.getName().substring(entry.getName().lastIndexOf('.')).equalsIgnoreCase(SHEET_EXTENSION)) {
        try {//from   w  w  w.  j a v a2 s  .  c o m
            // Extract full path
            String[] fullPath = entry.getName().split("/");

            // Extract security name
            String secType = fullPath[fullPath.length - 1].substring(0,
                    fullPath[fullPath.length - 1].lastIndexOf('.'));

            _currentPath = (String[]) ArrayUtils.subarray(fullPath, 0, fullPath.length - 1);

            // Set up a sheet reader and a row parser for the current CSV file in the ZIP archive
            SheetReader sheet = new CsvSheetReader(_zipFile.getInputStream(entry));

            RowParser parser = JodaBeanRowParser.newJodaBeanRowParser(secType);
            if (parser == null) {
                s_logger.error("Could not build a row parser for security type '" + secType + "'");
                return null;
            }
            if (!_ignoreVersion) {
                if (_versionMap.get(secType) == null) {
                    s_logger.error("Versioning hash for security type '" + secType + "' could not be found");
                    return null;
                }
                if (parser.getSecurityHashCode() != _versionMap.get(secType)) {
                    s_logger.error("The parser version for the '" + secType + "' security (hash "
                            + Integer.toHexString(parser.getSecurityHashCode())
                            + ") does not match the data stored in the archive (hash "
                            + Integer.toHexString(_versionMap.get(secType)) + ")");
                    return null;
                }
            }

            s_logger.info("Processing rows in archive entry " + entry.getName() + " as " + secType);

            // Create a simple portfolio reader for the current sheet
            return new SingleSheetSimplePortfolioReader(sheet, parser);

        } catch (Throwable ex) {
            s_logger.warn(
                    "Could not import from " + entry.getName() + ", skipping file (exception is " + ex + ")");
            return null;
        }
    } else {
        return null;
    }
}

From source file:io.gromit.geolite2.geonames.CountryFinder.java

/**
 * Read countries./*www .j ava 2 s . c  om*/
 *
 * @param countriesLocationUrl the countries location url
 * @return the country finder
 */
private CountryFinder readCountries(String countriesLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(countriesLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }

        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Country country = new Country();
            country.setIso(entry[0]);
            country.setIso3(entry[1]);
            country.setName(entry[2]);
            country.setCapital(entry[3]);
            country.setContinent(entry[4]);
            country.setCurrencyCode(entry[5]);
            country.setCurrencyName(entry[6]);
            country.setPhone(entry[7]);
            country.setLanguage(StringUtils.substringBefore(entry[8], ","));
            country.setGeonameId(NumberUtils.toInt(entry[9]));
            geonameMap.put(country.getGeonameId(), country);
            isoMap.put(country.getIso(), country);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    logger.info("loaded " + geonameMap.size() + " countries");
    return this;
}

From source file:net.firejack.platform.service.content.broker.collection.ImportCollectionArchiveFileBroker.java

@Override
protected ServiceResponse perform(ServiceRequest<NamedValues<InputStream>> request) throws Exception {
    InputStream inputStream = request.getData().get("inputStream");

    try {/*w w  w. ja va2  s.  c  om*/
        Long uploadFileTime = new Date().getTime();
        String randomName = SecurityHelper.generateRandomSequence(16);
        String temporaryUploadFileName = randomName + "." + uploadFileTime;
        OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, temporaryUploadFileName, inputStream,
                helper.getTemp());

        String contentXmlUploadedFile = null;
        String resourceZipUploadedFile = null;

        ZipInputStream zipFile = new ZipInputStream(OPFEngine.FileStoreService
                .download(OpenFlame.FILESTORE_BASE, temporaryUploadFileName, helper.getTemp()));
        try {
            ZipEntry entry;
            while ((entry = zipFile.getNextEntry()) != null) {
                if (PackageFileType.CONTENT_XML.getOfrFileName().equals(entry.getName())) {
                    contentXmlUploadedFile = PackageFileType.CONTENT_XML.name() + randomName + "."
                            + uploadFileTime;
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, contentXmlUploadedFile, zipFile,
                            helper.getTemp());
                } else if (PackageFileType.RESOURCE_ZIP.getOfrFileName().equals(entry.getName())) {
                    resourceZipUploadedFile = PackageFileType.RESOURCE_ZIP.name() + randomName + "."
                            + uploadFileTime;
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile,
                            zipFile, helper.getTemp());
                }
            }
        } catch (IOException e) {
            throw new BusinessFunctionException(e.getMessage());
        } finally {
            zipFile.close();
        }

        InputStream contentXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                contentXmlUploadedFile, helper.getTemp());
        InputStream resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                resourceZipUploadedFile, helper.getTemp());
        importContentProcessor.importContent(contentXml, resourceZip);
        IOUtils.closeQuietly(contentXml);
        IOUtils.closeQuietly(resourceZip);
    } catch (IOException e) {
        throw new BusinessFunctionException(e.getMessage());
    } catch (JAXBException e) {
        throw new BusinessFunctionException(e.getMessage());
    }
    return new ServiceResponse("Content Archive has uploaded successfully.", true);
}

From source file:edu.monash.merc.system.remote.HttpHpaFileGetter.java

public boolean importHPAXML(String remoteFile, String localFile) {
    //use httpclient to get the remote file
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(remoteFile);

    ZipInputStream zis = null;/*  w  w  w. j  av  a  2  s  .c  o m*/
    FileOutputStream fos = null;
    try {
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream in = entity.getContent();
                zis = new ZipInputStream(in);
                ZipEntry zipEntry = zis.getNextEntry();
                while (zipEntry != null) {
                    String fileName = zipEntry.getName();
                    if (StringUtils.contains(fileName, HPA_FILE_NAME)) {
                        System.out.println("======= found file.");
                        File aFile = new File(localFile);
                        fos = new FileOutputStream(aFile);
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                        fos.flush();
                        break;
                    }
                }
            }
        } else {
            throw new DMRemoteException("can't get the file from " + remoteFile);
        }
    } catch (Exception ex) {
        throw new DMRemoteException(ex);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (zis != null) {
                zis.closeEntry();
                zis.close();
            }
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            //ignore whatever caught
        }
    }
    return true;
}

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }//  ww  w  . j av a2 s .  co m
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.skcraft.launcher.creator.util.ModInfoReader.java

/**
 * Detect the mods listed in the given .jar
 *
 * @param file The file//from   w w w .  ja  v  a2  s  .  c  o m
 * @return A list of detected mods
 */
public List<? extends ModInfo> detectMods(File file) {
    Closer closer = Closer.create();

    try {
        FileInputStream fis = closer.register(new FileInputStream(file));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ZipInputStream zis = closer.register(new ZipInputStream(bis));

        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.getName().equalsIgnoreCase(FORGE_INFO_FILENAME)) {
                List<ForgeModInfo> mods;
                String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8));

                try {
                    mods = mapper.readValue(content, ForgeModManifest.class).getMods();
                } catch (JsonMappingException | JsonParseException e) {
                    mods = mapper.readValue(content, new TypeReference<List<ForgeModInfo>>() {
                    });
                }

                if (mods != null) {
                    // Ignore "examplemod"
                    return Collections.unmodifiableList(
                            mods.stream().filter(info -> !info.getModId().equals("examplemod"))
                                    .collect(Collectors.toList()));
                } else {
                    return Collections.emptyList();
                }

            } else if (entry.getName().equalsIgnoreCase(LITELOADER_INFO_FILENAME)) {
                String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8));
                return new ImmutableList.Builder<ModInfo>()
                        .add(mapper.readValue(content, LiteLoaderModInfo.class)).build();
            }
        }

        return Collections.emptyList();
    } catch (JsonMappingException e) {
        log.log(Level.WARNING, "Unknown format " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(),
                e);
        return Collections.emptyList();
    } catch (JsonParseException e) {
        log.log(Level.WARNING, "Corrupt " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(), e);
        return Collections.emptyList();
    } catch (IOException e) {
        log.log(Level.WARNING, "Failed to read " + file.getAbsolutePath(), e);
        return Collections.emptyList();
    } finally {
        try {
            closer.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerABZ.java

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);

    Format format = new Format(ABZ_FORMAT);

    try {/*from   w w  w  .  j  a v a2  s  .  com*/
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        boolean foundMetadataFile = false;
        boolean foundCover = false;
        boolean foundPlaylist = false;
        String zeCover = null;
        String zePlaylist = null;
        List<String> assets = new ArrayList<String>();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();

            if (lower.endsWith(ABZ_DEFAULT_COVER_JPG) || lower.endsWith(ABZ_DEFAULT_COVER_PNG)) {
                zeCover = name;
            } else if (lower.endsWith(ABZ_EXTENSION_PLAYLIST)) {
                zePlaylist = name;
            } else if (this.fileHasAllowedExtension(lower, ABZ_AUDIO_EXTENSIONS)) {
                p.isValid(true);
                assets.add(name);
            } else if (lower.endsWith(ABZ_FILE_METADATA)) {
                p.isValid(true);
                foundMetadataFile = true;
                if (this.parseMetadataFile(zipFile, ze, format)) {
                    if (format.getMetadatum("internalPathPlaylist") != null) {
                        foundPlaylist = true;
                    }
                    if (format.getMetadatum("internalPathCover") != null) {
                        foundCover = true;
                    }
                }
            } // end if metadata
        } // end while
        zipFile.close();

        // set cover
        if ((!foundCover) && (zeCover != null)) {
            format.addMetadatum("internalPathCover", zeCover);
        }

        // default playlist found?
        if ((!foundPlaylist) && (zePlaylist != null)) {
            format.addMetadatum("internalPathPlaylist", zePlaylist);
        }

        // set number of assets
        format.addMetadatum("numberOfAssets", "" + assets.size());

    } catch (Exception e) {
        // invalidate publication, so it will not be added to library
        p.isValid(false);
    } // end try

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:com.heliosdecompiler.helios.LoadedFile.java

private void readDataQuick() {
    // This code should run as fast as possible
    byte[] data = null;
    try (FileInputStream inputStream = new FileInputStream(file)) {
        data = IOUtils.toByteArray(inputStream);
    } catch (IOException ex) {
        ExceptionHandler.handle(new RuntimeException("Error while reading file", ex));
        return;//from ww w .java2s . c  o m
    }
    // And now we can take our time. The file has been unlocked (unless something went seriously wrong)
    this.files = new HashMap<>();
    try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(data))) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            this.files.put(entry.getName(), IOUtils.toByteArray(zipInputStream));
        }
    } catch (Throwable ex) {
        // This should never happen
        ExceptionHandler.handle(new RuntimeException("Error while parsing file (!)", ex));
        return;
    }
    // If files is still empty, then it's not a zip file (or something weird happened)
    if (this.files.size() == 0) {
        this.files.put(file.getName(), data);
    }
    // Lock the map
    this.files = Collections.unmodifiableMap(this.files);
}

From source file:it.digitalhumanities.dhcpublisher.DHCPublisher.java

private void unzipFile(int counter, File file, File targetDir) throws IOException {

    String subDirName = counter + "_" + file.getName().substring(0, file.getName().length() - 4);
    if (subDirName.length() > 60) {
        subDirName = subDirName.substring(0, 60);
    }/* w w  w .j a v a 2s.c  om*/
    ;

    File subDir = new File(targetDir, subDirName);
    if (!subDir.exists()) {
        subDir.mkdirs();
    }

    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(file))) {

        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            File targetFile = new File(subDir, ze.getName());
            targetFile.getParentFile().mkdirs();

            try (FileOutputStream fos = new FileOutputStream(targetFile)) {
                IOUtils.copy(zis, fos);
            }

            ze = zis.getNextEntry();
        }
    }
}