Example usage for java.util.zip ZipFile getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the path name of the ZIP file.

Usage

From source file:org.wso2.carbon.dashboard.migratetool.DSCarFileMigrationTool.java

private void extractCarFile(ZipFile zipFile, File tempDirectory) {
    Enumeration files = zipFile.entries();
    File file;/*from  w  w w .j a  va  2  s .c  o m*/
    FileOutputStream fos = null;

    while (files.hasMoreElements()) {
        try {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead;
            file = new File(tempDirectory.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                file.mkdirs();
                continue;
            } else {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            log.error("Error while extracting the " + zipFile.getName() + ".car File", e);
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    log.error("Error in closing FileOutputStream", e);
                }
            }
        }
    }
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

@Override
public Document extractArticleXml(ZipFile archive) throws ArchiveProcessException {
    try {/*from w w  w.jav a2 s. c  o  m*/
        Document manifest = extractXml(archive, "MANIFEST.xml");
        String xmlFileName = xPathUtil.evaluate(manifest, "//article/@main-entry");
        return extractXml(archive, xmlFileName);
    } catch (Exception e) {
        throw new ArchiveProcessException("Error extracting article xml from archive: " + archive.getName(), e);
    }
}

From source file:org.openhab.ui.cometvisu.internal.util.ClientInstaller.java

/**
 * Extract the content of the zip file to the target folder
 *
 * @param folderName {String} subfolder inside the zip file that should be extracted
 * @param zipFile {ZipFile} zip-file to extract
 * @param destDir {String} destination for the extracted files
 *//*from   ww w .  java 2  s .c o m*/
private void extractFolder(String folderName, ZipFile zipFile, String destDir) {
    for (ZipEntry entry : Collections.list(zipFile.entries())) {
        if (entry.getName().startsWith(folderName)) {
            String target = entry.getName().substring(folderName.length());
            File file = new File(destDir, target);
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                if (file.exists() && file.getPath().matches(".*/config/visu_config.*\\.xml")) {
                    // never ever overwrite existing config files
                    continue;
                }
                new File(file.getParent()).mkdirs();

                try (InputStream is = zipFile.getInputStream(entry);
                        OutputStream os = new FileOutputStream(file);) {
                    for (int len; (len = is.read(buffer)) != -1;) {
                        os.write(buffer, 0, len);
                    }
                    logger.info("extracted zip file {} to folder {}", zipFile.getName(), destDir);
                } catch (IOException e) {
                    logger.error("error extracting file {}", e.getMessage(), e);
                }
            }
        }
    }
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

@Override
public Article processArticle(ZipFile archive, Document articleXml) throws ArchiveProcessException {
    InputStream xsl = null;//from ww  w .j ava 2 s. c om
    try {
        String zipInfo = describeZip(archive);

        Document transformedXml = transformZip(archive, zipInfo, articleXml,
                configuration.getString("ambra.platform.doiUrlPrefix", null));

        Article article = parseTransformedXml(transformedXml);
        String archiveName = archive.getName().contains(File.separator)
                ? archive.getName().substring(archive.getName().lastIndexOf(File.separator) + 1)
                : archive.getName();
        article.setArchiveName(archiveName);

        // Attempt to assign categories to the article based on the taxonomy server.  However,
        // we still want to ingest the article even if this process fails.
        List<String> terms = null;
        try {
            terms = articleClassifier.classifyArticle(articleXml);
        } catch (Exception e) {
            log.warn("Taxonomy server not responding, but ingesting article anyway", e);
        }
        if (terms != null && terms.size() > 0) {
            articleService.setArticleCategories(article, terms);
        } else {
            article.setCategories(new HashSet<Category>());
        }

        Journal journal = new Journal();
        journal.seteIssn(article.geteIssn());
        article.setJournals(new HashSet<Journal>());
        article.getJournals().add(journal);

        article.setStrkImgURI(extractStrikingImageURI(archive));

        return article;
    } catch (IOException e) {
        throw new ArchiveProcessException("Error reading from Zip archive", e);
    } catch (TransformerException e) {
        throw new ArchiveProcessException("Error transforming Article xml", e);
    } catch (ParseException e) {
        throw new ArchiveProcessException("Error parsing a date in the xml", e);
    } catch (XPathExpressionException e) {
        throw new ArchiveProcessException("Error parsing transformed xml", e);
    } catch (URISyntaxException e) {
        throw new ArchiveProcessException("Error malformed uri", e);
    } catch (Exception e) {
        throw new ArchiveProcessException("Error parsing xml", e);
    } finally {
        if (xsl != null) {
            try {
                xsl.close();
            } catch (IOException e) {
                log.warn("Error closing input stream for xsl stylesheet");
            }
        }
    }
}

From source file:org.jvnet.hudson.plugins.thinbackup.backup.BackupSet.java

private boolean initializeFromZipFile() {
    boolean success = true;

    ZipFile zipFile = null;
    try {/*  w  ww . jav a2 s .  com*/
        Utils.waitUntilFileCanBeRead(backupSetzipFile);
        zipFile = new ZipFile(backupSetzipFile);
        final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements() && success) {
            final ZipEntry entry = zipEntries.nextElement();
            String tmpName = entry.getName();
            tmpName = tmpName.substring(0, tmpName.indexOf(File.separator));
            if (tmpName.startsWith(BackupType.FULL.toString())) {
                if ((fullBackupName == null) || fullBackupName.equals(tmpName)) {
                    fullBackupName = tmpName;
                } else {
                    LOGGER.warning(String.format(
                            "Backup set '%s' contains multiple full backups and is therefore not valid.",
                            zipFile.getName()));
                    success = false;
                }
            } else if (tmpName.startsWith(BackupType.DIFF.toString()) && !diffBackupsNames.contains(tmpName)) {
                diffBackupsNames.add(tmpName);
            }
        }
    } catch (final IOException e) {
        LOGGER.log(Level.SEVERE,
                String.format("Cannot initialize BackupSet from ZIP file '%s'.", backupSetzipFile.getName()),
                e);
        success = false;
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, String.format("Cannot close ZIP file '%s'.", backupSetzipFile.getName()),
                    e);
            success = false;
        }
    }

    return success;
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Unpacks a single file from a ZIP archive to a file.
 *
 * @param zf/*w ww  .  j  av  a  2s . co  m*/
 *          ZIP file.
 * @param name
 *          entry name.
 * @param file
 *          target file to be created or overwritten.
 * @return <code>true</code> if the entry was found and unpacked,
 *         <code>false</code> if the entry was not found.
 */
private static boolean doUnpackEntry(ZipFile zf, String name, File file) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("Extracting '" + zf.getName() + "' entry '" + name + "' into '" + file + "'.");
    }

    ZipEntry ze = zf.getEntry(name);
    if (ze == null) {
        return false; // entry not found
    }

    InputStream in = new BufferedInputStream(zf.getInputStream(ze));
    try {
        FileUtil.copy(in, file);
    } finally {
        IOUtils.closeQuietly(in);
    }
    return true;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Get a file from the zip archive/* w  ww. j  a  v a 2s . co m*/
 *
 * @param zip  zip archive containing the file
 * @param file name of the file
 * @return ZipEntry
 * @throws FxNotFoundException if the archive does not contain the file
 */
protected ZipEntry getZipEntry(ZipFile zip, String file) throws FxNotFoundException {
    ZipEntry ze = zip.getEntry(file);
    if (ze == null)
        throw new FxNotFoundException("ex.import.missingFile", file, zip.getName());
    return ze;
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

private RevelationData loadRevelationData(File revelZipFile) throws IOException, ConfigurationException {
    ZipFile zipFile = new ZipFile(revelZipFile);
    InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.REVELATION_DESC));
    if (is == null) {
        logger.warn("Will ignore invalid revelation data archive \"" + zipFile.getName() + "\".");
        return null;
    }/*from  w  w w.j  a  v  a2s  .  c  om*/
    PropertiesConfiguration pc = ConfigUtils.loadConfig(is, "UTF-8");
    zipFile.close();

    RevelationData rd = new RevelationData();

    int len;
    if ("aya".equals(pc.getString("mode", "sura"))) {
        len = QuranPropertiesUtils.QURAN_AYA_COUNT;
        rd.mode = RevelationData.AYA_MODE;
    } else {
        len = 114;
        rd.mode = RevelationData.SURA_MODE;
    }
    rd.suraOrders = new int[len];
    rd.orders = new int[len];
    // rd.years = new int[len]; // not used for now

    rd.version = pc.getString("version");
    String zipFileName = revelZipFile.getName();
    rd.id = zipFileName.substring(0, zipFileName.length() - ApplicationPath.REVEL_PACK_SUFFIX.length());
    rd.archiveFile = revelZipFile;
    rd.delimiter = pc.getString("delimiter", "\n");
    String sig = pc.getString("signature");

    byte[] sigBytes = sig.getBytes("US-ASCII");
    rd.signature = sig == null ? null : Base64.decodeBase64(sigBytes);

    rd.loadLocalizedNames(pc, "name");

    if (StringUtils.isBlank(rd.id) || rd.localizedNameMap.size() == 0 || StringUtils.isBlank(rd.version)) {
        logger.warn("Invalid revelation data package: \"" + rd + "\".");
        return null;
    }
    return rd;
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

public TranslationData loadTranslationData(File transZipFile) throws IOException, ConfigurationException {
    TranslationData td = null;//ww w . ja  v a2s  . c o  m
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(transZipFile);
        InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.TRANSLATION_DESC));
        if (is == null) {
            logger.warn("Will ignore invalid translation archive \"" + zipFile.getName() + "\".");
            return null;
        }
        Reader reader = new InputStreamReader(is, "UTF-8");
        PropertiesConfiguration pc = new PropertiesConfiguration();
        pc.load(reader);
        reader.close();
        is.close();

        td = new TranslationData();
        td.version = pc.getString(VERSION_ATTR);
        td.id = pc.getString(ID_ATTR);
        td.locale = new Locale(pc.getString(LANG_ATTR, "en"), pc.getString(COUNTRY_ATTR, "US"));
        td.encoding = pc.getString(ENCODING_ATTR, "ISO-8859-1");
        td.direction = pc.getString(DIRECTION_ATTR, "ltr");
        td.file = pc.getString(FILE_ATTR);
        td.name = pc.getString(NAME_ATTR);
        td.localizedName = pc.getString(LOCALIZED_NAME_ATTR, td.name);
        td.archiveFile = transZipFile;
        td.delimiter = pc.getString(LINE_DELIMITER_ATTR, "\n");
        String sig = pc.getString(SIGNATURE_ATTR);
        td.signature = sig == null ? null : Base64.decodeBase64(sig.getBytes("US-ASCII"));

        //create a LocalizedInstance for this translation.
        // <patch>
        LocalizedResource localizedResource = new LocalizedResource();
        localizedResource.loadLocalizedNames(pc, NAME_ATTR);
        localizedResource.setLanguage(td.locale.getLanguage());
        td.setLocalizedResource(localizedResource);
        td.setFile(transZipFile);
        // </patch>

        if (StringUtils.isBlank(td.id) || StringUtils.isBlank(td.name) || StringUtils.isBlank(td.file)
                || StringUtils.isBlank(td.version)) {
            logger.warn("Invalid translation: \"" + td + "\".");
            return null;
        }

        if (zipFile.getEntry(td.file) == null) {
            logger.warn("Invalid translation format. File not exists in the archive: " + td.file);
            return null;
        }
    } finally {
        if (zipFile != null) {
            ZipUtils.closeQuietly(zipFile);
        }
    }

    return td;
}

From source file:org.ambraproject.article.service.IngesterImpl.java

/**
 * TODO: Rollback from the filestore if there's a problem storing the files
 *
 * @param archive - the archive to ingest
 * @param force   if true then don't check whether this article already exists but just save this new article.
 * @return the new article/*from w w  w.ja  v  a 2  s .  co m*/
 * @throws DuplicateArticleIdException if an article exists with the same URI as the new article and <var>force</var>
 *                                     is false
 * @throws IngestException             if there's any other problem ingesting the article
 */
@Transactional(rollbackFor = Throwable.class)
@SuppressWarnings("unchecked")
public Article ingest(ZipFile archive, boolean force) throws DuplicateArticleIdException, IngestException {
    Article article = null;
    try {
        final Document articleXml = ingestArchiveProcessor.extractArticleXml(archive);
        article = ingestArchiveProcessor.processArticle(archive, articleXml);
        updateWithExistingJournal(article);

        final String articleDoi = article.getDoi();
        //Check if we already have an article
        Article existingArticle = (Article) hibernateTemplate.execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return (Article) session.createCriteria(Article.class).setFetchMode("journals", FetchMode.JOIN)
                        .add(Restrictions.eq("doi", articleDoi))
                        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).uniqueResult();
            }
        });

        // if the article is in Disabled state, we allow ingest without force
        if (!force && existingArticle != null && existingArticle.getState() != Article.STATE_DISABLED) {
            throw new DuplicateArticleIdException(article.getDoi());
        }

        if (existingArticle != null) {
            updateArticle(article, existingArticle);
            article = existingArticle;
        } else {
            saveArticle(article);
        }

        // For every RelatedArticle object, create a reciprocal link from old Article to this Article.
        addReciprocalRelatedArticleAssociations(article);

        //if this is an image article, update the issues for which this is the image
        if (article.getDoi().contains("image")) {
            updateIssueForImageArticle(article);
        }
        //create syndications
        syndicationService.createSyndications(article.getDoi());

        //Store files to the file store
        storeFiles(archive, article.getDoi());

        return article;
    } catch (ArchiveProcessException e) {
        throw new IngestException(
                "Error processing zip archive to extract article information; archive" + archive.getName(), e);
    } catch (IOException e) {
        throw new IngestException("Error reading entries from zip archive: " + archive.getName(), e);
    } catch (FileStoreException e) {
        throw new IngestException("Error storing blobs to the file store; article: " + article.getDoi()
                + ", archive: " + archive.getName(), e);
    } catch (DataAccessException e) {
        throw new IngestException(
                "Error storing information for article " + article.getDoi() + " to the SQL database", e);
    } catch (HibernateException e) {
        throw new IngestException(
                "Error storing information for article " + article.getDoi() + " to the SQL database", e);
    } catch (NoSuchArticleIdException e) {
        throw new IngestException("Article wasn't stored to the database", e);
    }
}