Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

private void addArchive(File element) throws IOException {
    if (addCached(element)) {
        return;//from  ww w. j  av  a 2s  . c  o  m
    }

    List classes = new ArrayList();
    List resources = new ArrayList();
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(element);
        Enumeration entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                String name = entry.getName();

                if ("class".equals(FilenameUtils.getExtension(name))) {
                    String className = FilenameUtils.removeExtension(name).replace('/', '.').replace('\\', '.');

                    classes.add(className);
                    addClass(className, element);
                } else {
                    String resourcePath = name.replace('\\', File.separatorChar);

                    resources.add(resourcePath);
                    addResource(resourcePath, element);
                }
            }
        }

        CACHED_BY_ELEMENT.put(element, new Cached(classes, resources));
    } finally {
        // IOUtils has no closeQuietly for Closable in the 1.x series.
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ex) {
                // ignored
            }
        }
    }
}

From source file:com.thoughtworks.go.plugin.infra.commons.PluginsZipTest.java

@Test
public void shouldZipTaskPluginsIntoOneZipEveryTime() throws Exception {
    pluginsZip.create();/*from w w w.j av  a 2s  .  co  m*/

    assertThat(expectedZipPath + " should exist", new File(expectedZipPath).exists(), is(true));
    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled-task-1.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled-scm-3.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled-package-material-4.jar"),
            is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external-task-1.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external-scm-3.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external-package-material-4.jar"),
            is(notNullValue()));

    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled-auth-2.jar"), is(nullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external-elastic-agent-2.jar"), is(nullValue()));
}

From source file:com.streamsets.datacollector.bundles.TestSupportBundleManager.java

private ZipFile zipFile(List<String> bundles, BundleType bundleType) throws Exception {
    InputStream bundleStream = manager.generateNewBundle(bundles, bundleType).getInputStream();
    File outputFile = File.createTempFile("test-support-bundle", ".zip");
    outputFile.deleteOnExit();//from   w  w  w . java  2s.  c  o  m

    try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
        IOUtils.copy(bundleStream, outputStream);
    }

    ZipFile zipFile = new ZipFile(outputFile);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    LOG.debug("Archive content:");
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        LOG.debug("Entry {}", entry.getName());
    }

    return zipFile;
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private void extractWarFile() {
    if (webAppBase != null && webAppBase.length() > 0) {
        ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
        URL location = protectionDomain.getCodeSource().getLocation();
        log.info("detected run JAR at " + location);

        if (!location.toExternalForm().startsWith("file:") || !location.toExternalForm().endsWith(".jar"))
            throw new IllegalArgumentException("invalid code location: " + location);

        try {/*from  w  ww  .  java2s  . co m*/
            ZipFile zipFile = new ZipFile(new File(location.toURI()));

            Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
            ZipEntry warEntry = null;
            while (entryEnum.hasMoreElements()) {
                ZipEntry entry = entryEnum.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(webAppBase) && entryName.endsWith(".war")) {
                    warEntry = entry;
                    break;
                }
            }

            if (warEntry == null)
                throw new RuntimeException("can't find JAR entry for " + webAppBase + "*.war");

            log.info("extracting WAR file " + warEntry.getName());

            // extract web app WAR to current directory
            InputStream inputStream = zipFile.getInputStream(warEntry);
            OutputStream outputStream = new FileOutputStream(new File(warEntry.getName()));
            byte buf[] = new byte[1024];
            int nread;
            while ((nread = inputStream.read(buf, 0, 1024)) > 0) {
                outputStream.write(buf, 0, nread);
            }
            outputStream.close();
            inputStream.close();
            zipFile.close();

            String launchContextRoot = contextRoot != null ? contextRoot : webAppBase;
            if (!launchContextRoot.startsWith("/"))
                launchContextRoot = "/" + launchContextRoot;

            log.info("launching WAR file " + warEntry.getName() + " at context root " + launchContextRoot);

            // add web app to Tomcat
            Context context = tomcat.addWebapp(launchContextRoot, warEntry.getName());
            if (context instanceof StandardContext)
                ((StandardContext) context).setUnpackWAR(false);
        } catch (Exception e) {
            throw new RuntimeException("error extracting WAR file", e);
        }
    }
}

From source file:fll.web.admin.UploadSubjectiveData.java

/**
 * Save the data stored in file to the database and update the subjective
 * score totals.//from   w w w.ja v a2 s.c om
 * 
 * @param file the file to read the data from
 * @param connection the database connection to write to
 * @throws SAXException if there is an error parsing the document
 */
public static void saveSubjectiveData(final File file, final int currentTournament,
        final ChallengeDescription challengeDescription, final Connection connection,
        final ServletContext application) throws SQLException, IOException, ParseException, SAXException {
    if (LOGGER.isDebugEnabled()) {
        try {
            LOGGER.debug("Saving uploaded file to ");
            final String baseFilename = "subjective-upload_" + DATE_TIME_FORMAT.get().format(new Date());
            final String filename = application.getRealPath("/WEB-INF/" + baseFilename);

            final File copy = new File(filename);
            FileOutputStream output = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                output = new FileOutputStream(copy);
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        } catch (final IOException e) {
            LOGGER.debug("Error creating copy of subjective datafile", e);
        }
    }
    ZipFile zipfile = null;
    Document scoreDocument = null;
    try {
        try {
            zipfile = new ZipFile(file);

            // read in score data
            final ZipEntry scoreZipEntry = zipfile.getEntry("score.xml");
            if (null == scoreZipEntry) {
                throw new RuntimeException("Zipfile does not contain score.xml as expected");
            }
            final InputStream scoreStream = zipfile.getInputStream(scoreZipEntry);
            scoreDocument = XMLUtils.parseXMLDocument(scoreStream);
            scoreStream.close();
            zipfile.close();

        } catch (final ZipException ze) {
            LOGGER.info("Subjective upload is not a zip file, trying as an XML file");

            // not a zip file, parse as just the XML file
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                scoreDocument = XMLUtils.parseXMLDocument(fis);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

        if (null == scoreDocument) {
            throw new FLLRuntimeException(
                    "Cannot parse input as a compressed subjective data file or an uncompressed XML file");
        }

        saveSubjectiveData(scoreDocument, currentTournament, challengeDescription, connection);
    } finally {
        if (null != zipfile) {
            zipfile.close();
        }
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java

public Errors doImport() {
    Errors errors = new Errors();
    try {/* ww w .j  a  v a2 s  .  c  o  m*/
        ZipFile zipArchive = new ZipFile(fileToImport);
        ZipEntry manifesteEntry = zipArchive.getEntry(MANIFESTE_FILE_NAME);
        archiveManifeste = getManisfesteFromArchive(zipArchive.getInputStream(manifesteEntry));
        archiveManifeste.getRootElement()
                .addAttribute(new Attribute("archive-name", getArchiveName(fileToImport)));
        zipArchive.close();
        HashMap<String, Object> importProperties = extractPropertiesFromArchiveManifeste(archiveManifeste);
        for (String docType : (String[]) importProperties.get("archiveDocumentTypes")) {
            if (!docType.equals("PJ")
                    && !DataLayerManager.getImplementation().canImportDocument(docType, getUser())) {
                errors.addError(Errors.SEVERITY_WARNING, "Impossible d'importer ce type de document (" + docType
                        + "), la base de donne doit d'abord tre mise  jour.");
            }
        }
        importedArchiveManifeste = DataLayerManager.getImplementation()
                .getManifesteFromArchive(importProperties.get("archiveName").toString(), getUser());
        definePropertiesFromImportedManifeste(importedArchiveManifeste, importProperties);
        Element historique = null;
        if (importedArchiveManifeste != null) {
            historique = (Element) importedArchiveManifeste
                    .query("/m:manifeste/m:evenements", getNamespaceCtx()).get(0);
            // pour avoir un lment sans parent et pouvoir l'ajouter o on veut
            historique = new Element(historique);
        } else {
            historique = new Element("evenements");
        }
        archiveManifeste.getRootElement().appendChild(historique);
        boolean sectionApplied = false;
        for (SectionModel section : rules.getSections()) {
            SectionModel theSection = section;
            if (theSection.getPredicat().matches(importProperties)) {
                logger.info("Application de la rgle " + theSection.getName());
                int globalOverwriteRule = OVERWRITE_RULE_UNSET;
                if (theSection.getActions().isUsePreviousSection()) {
                    // alors il y a forcment un manifeste import, et on va aller chercher sa section
                    Element sectionElement = (Element) importedArchiveManifeste
                            .query("/m:manifeste/rul:section", getNamespaceCtx()).get(0);
                    if (sectionElement == null)
                        throw new ImportException(new Errors.Error(Errors.SEVERITY_ERROR, "la section "
                                + theSection.getName()
                                + " impose l'application de la section du prcdente import, mais celui-ci n'a pas t trouv."),
                                null);
                    theSection = new SectionModel(sectionElement);
                    // et on supprime toutes les donnes de l'archive
                    HashMap<String, DocumentModel> docsToDrop = new HashMap<String, DocumentModel>();
                    for (String docId : (String[]) importProperties.get("archiveImportedDocumentTypes")) {
                        docsToDrop.put(docId, documentsModel.getDocumentById(docId));
                    }
                    DataLayerManager.getImplementation().removeArchive(docsToDrop,
                            importProperties.get("archiveName").toString(), getUser());
                    Nodes deleteActions = importedArchiveManifeste.query("/m:manifeste/m:on-delete/m:action",
                            getNamespaceCtx());
                    for (int i = 0; i < deleteActions.size(); i++) {
                        Element action = (Element) deleteActions.get(i);
                        doApplyAction(action);
                    }
                    // a ce stade, aucune mise  jour  faire dans le manifeste, tous les documents sont supprims
                } else {
                    if (importedArchiveManifeste != null) {
                        // il faut reprendre l'historique de chacun des documents
                        Nodes importedDocuments = importedArchiveManifeste.query("//m:document",
                                getNamespaceCtx());
                        for (int i = 0; i < importedDocuments.size(); i++) {
                            Element importedDoc = (Element) importedDocuments.get(i);
                            Element thisDoc = getElement(
                                    archiveManifeste.query("/manifeste/documents/document[@path='"
                                            + importedDoc.getAttributeValue("path") + "']"));
                            if (thisDoc != null) {
                                String __imported = importedDoc.getAttributeValue("imported");
                                thisDoc.addAttribute(new Attribute("imported", __imported));
                                if ("Oui".equals(__imported)) {
                                    Element result = getElement(
                                            importedDoc.query("m:resultatimport", getNamespaceCtx()));
                                    if (result != null)
                                        thisDoc.appendChild(new Element(result));
                                }
                            }
                        }
                    }
                }
                if (theSection.getOverwriteRule() != null) {
                    if (EtatImporteur.OVERWRITE_RULE_ALWAYS.equals(theSection.getOverwriteRule()))
                        globalOverwriteRule = OVERWRITE_RULE_OVERWRITE;
                    else if (EtatImporteur.OVERWRITE_RULE_NEVER.equals(theSection.getOverwriteRule()))
                        globalOverwriteRule = OVERWRITE_RULE_SKIP;
                }
                // on rcupre la liste des documents  importer pour pouvoir contrler qu'ils sont bien disponibles
                List<Element> documentsToImport = theSection.getDocumentsToImport(archiveManifeste,
                        applicationProperties);
                if (documentsToImport.size() > 0) {
                    TreeSet<String> volumesRequired = new TreeSet<String>();
                    for (Element filePlannedToImport : documentsToImport) {
                        volumesRequired.add(filePlannedToImport.getAttributeValue("volume"));
                    }
                    int maxVolumes = Integer.parseInt(volumesRequired.last());
                    File[] volumes = new File[maxVolumes + 1];
                    for (String volume : volumesRequired) {
                        String fichierVolume = archiveManifeste
                                .query("/manifeste/volumes/volume[@num=" + volume + "]/@fichier").get(0)
                                .getValue();
                        File f = new File(fileToImport.getParentFile(), fichierVolume);
                        if (!f.exists()) {
                            errors.addError(Errors.SEVERITY_ERROR, f.getAbsolutePath() + " non trouv");
                        }
                        volumes[Integer.parseInt(volume)] = f;
                    }
                    if (!errors.containsError()) {
                        logger.info("displayProgress(" + (documentsToImport.size() + 1) + ")");
                        // ici, on ouvre une porte pour permettre de faire des modifs dans l'ArchiveImporteur
                        preImport(theSection, archiveManifeste);
                        importServiceProvider.displayProgress(documentsToImport.size() + 1);
                        boolean doImport = false;
                        boolean doDelete = false;
                        // on traite les actions
                        for (XomDefinitionable dd : theSection.getActions().getActions()) {
                            if (dd instanceof ImportModel) {
                                //ImportModel im = (ImportModel)dd;
                                // on a dj dtermin la liste des fichiers  importer, donc on les importe
                                for (Element documentToImport : documentsToImport) {
                                    int vol = Integer.parseInt(documentToImport.getAttributeValue("volume"));
                                    try {
                                        FileInfo fileInfo = doImportDocument(documentToImport, volumes[vol],
                                                importProperties, globalOverwriteRule);
                                        if (fileInfo.getInProcessException() != null)
                                            errors.addError(Errors.SEVERITY_ERROR,
                                                    fileInfo.getInProcessException().getMessage());
                                        if (__fileInfo == null)
                                            __fileInfo = fileInfo;
                                        else
                                            __fileInfo.merge(fileInfo);
                                        if (fileInfo.getGlobalCount() == 0) {
                                            // rien n'a t import, probablement parce que overwrite rule disait
                                            // qu'il ne fallait pas importer. Donc on ne modifie rien.
                                        } else {
                                            Element result = new Element("resultatimport");
                                            result.addAttribute(new Attribute("Duree",
                                                    DateUtils.durationToString(fileInfo.getDurationImport())));
                                            result.addAttribute(new Attribute("Debut", DateUtils
                                                    .formatXsDateTime(new Date(fileInfo.getDebutImport()))));
                                            result.addAttribute(new Attribute("Fin", DateUtils
                                                    .formatXsDateTime(new Date(fileInfo.getFinImport()))));
                                            // on supprime le prcdent rsultat d'import, si il existait...
                                            Nodes previousResults = documentToImport.query(
                                                    "resultatimport | m:resultatimport", getNamespaceCtx());
                                            for (int i = previousResults.size() - 1; i >= 0; i--) {
                                                Element __res = (Element) previousResults.get(i);
                                                documentToImport.removeChild(__res);
                                            }
                                            documentToImport.insertChild(result, 0);
                                            documentToImport.addAttribute(new Attribute("imported", "Oui"));
                                        }
                                        // on applique les ventuelles actions portant sur ce document
                                        Nodes actions = archiveManifeste.query("/manifeste/action[@depends-on='"
                                                + documentToImport.getAttributeValue("path") + "']");
                                        for (int i = 0; i < actions.size(); i++) {
                                            Element action = (Element) actions.get(i);
                                            try {
                                                FileInfo actFileInfo = doApplyAction(action);
                                                if (__fileInfo == null)
                                                    __fileInfo = actFileInfo;
                                                else
                                                    __fileInfo.merge(actFileInfo);
                                            } catch (Exception ex) {
                                                logger.error("while applying " + action.toXML(), ex);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        logger.error(
                                                "while importing " + documentToImport.getAttributeValue("path"),
                                                ex);
                                        documentToImport.addAttribute(
                                                new Attribute("imported", "Erreur: " + ex.getMessage()));
                                    }
                                }
                                doImport = true;
                            } else if (dd instanceof DeleteModel) {
                                importServiceProvider.startLongWait();
                                DeleteModel dm = (DeleteModel) dd;
                                if (dm.getArchive() != null) {
                                    String archiveName = null;
                                    if ("archiveName".equals(dm.getArchive())) {
                                        // on remplace par le nom de l'archive
                                        archiveName = importProperties.get("archiveName").toString();
                                        // pour le moment, on n'autorise pas la suppression d'une autre archive
                                        HashMap<String, DocumentModel> map = new HashMap<String, DocumentModel>();
                                        for (String s : (String[]) importProperties
                                                .get("archiveDocumentTypes")) {
                                            map.put(s, documentsModel.getDocumentById(s));
                                        }
                                        DataLayerManager.getImplementation().removeArchive(map, archiveName,
                                                getUser());
                                        Nodes documents = archiveManifeste
                                                .query("/manifeste/documents/document");
                                        for (int i = 0; i < documents.size(); i++) {
                                            Element doc = (Element) documents.get(i);
                                            Element resultImport = getElement(doc.query(
                                                    "m:resultatimport | resultatimport", getNamespaceCtx()));
                                            if (resultImport != null)
                                                doc.removeChild(resultImport);
                                            doc.addAttribute(new Attribute("imported", "Non"));
                                        }
                                        // on applique toutes les actions, puisqu'on a supprim tous les documents
                                        Nodes actions = archiveManifeste
                                                .query("/manifeste/on-delete/action[@depends-on]");
                                        for (int i = 0; i < actions.size(); i++) {
                                            Element action = (Element) actions.get(i);
                                            try {
                                                FileInfo fileInfo = doApplyAction(action);
                                                if (__fileInfo == null)
                                                    __fileInfo = fileInfo;
                                                else
                                                    __fileInfo.merge(fileInfo);
                                            } catch (Exception ex) {
                                                logger.error("while applying " + action.toXML(), ex);
                                            }
                                        }
                                    } else if (dm.getTypeDoc() != null) {
                                        if (dm.getCollectivite() != null) {
                                            if (dm.getBudget() != null) {
                                                if (dm.getFileName() != null) {
                                                    DataLayerManager.getImplementation().removeDocument(
                                                            documentsModel.getDocumentById(dm.getTypeDoc()),
                                                            new Pair(dm.getCollectivite(),
                                                                    dm.getCollectivite()),
                                                            new Pair(dm.getBudget(), dm.getBudget()),
                                                            dm.getFileName(), user);
                                                    Nodes documents = archiveManifeste
                                                            .query("/manifeste/documents/document[@type='"
                                                                    + dm.getTypeDoc() + "' and @buIdCol='"
                                                                    + dm.getCollectivite() + "' and @buCode='"
                                                                    + dm.getBudget() + "' and ends-with(@path,'"
                                                                    + dm.getFileName() + "')]");
                                                    for (int i = 0; i < documents.size(); i++) {
                                                        Element doc = (Element) documents.get(i);
                                                        Element resultImport = getElement(
                                                                doc.query("m:resultatimport | resultatimport",
                                                                        getNamespaceCtx()));
                                                        if (resultImport != null)
                                                            doc.removeChild(resultImport);
                                                        doc.addAttribute(new Attribute("imported", "Non"));
                                                    }
                                                    // on applique les actions du document
                                                    Nodes actions = archiveManifeste.query(
                                                            "/manifeste/on-delete/action[ends-with(@depends-on,'"
                                                                    + dm.getFileName() + "')]");
                                                    for (int i = 0; i < actions.size(); i++) {
                                                        Element action = (Element) actions.get(i);
                                                        try {
                                                            FileInfo fileInfo = doApplyAction(action);
                                                            if (__fileInfo == null)
                                                                __fileInfo = fileInfo;
                                                            else
                                                                __fileInfo.merge(fileInfo);
                                                        } catch (Exception ex) {
                                                            logger.error("while applying " + action.toXML(),
                                                                    ex);
                                                        }
                                                    }
                                                } else {
                                                    DataLayerManager.getImplementation().removeBudget(
                                                            documentsModel.getDocumentById(dm.getTypeDoc()),
                                                            new Pair(dm.getCollectivite(),
                                                                    dm.getCollectivite()),
                                                            new Pair(dm.getBudget(), dm.getBudget()), user);
                                                    Nodes documents = archiveManifeste
                                                            .query("/manifeste/documents/document[@type='"
                                                                    + dm.getTypeDoc() + "' and @buIdCol='"
                                                                    + dm.getCollectivite() + "' and @buCode='"
                                                                    + dm.getBudget() + "']");
                                                    for (int i = 0; i < documents.size(); i++) {
                                                        Element doc = (Element) documents.get(i);
                                                        Element resultImport = getElement(
                                                                doc.query("m:resultatimport | resultatimport",
                                                                        getNamespaceCtx()));
                                                        if (resultImport != null)
                                                            doc.removeChild(resultImport);
                                                        doc.addAttribute(new Attribute("imported", "Non"));
                                                        // on applique les actions du document
                                                        Nodes actions = archiveManifeste.query(
                                                                "/manifeste/on-delete/action[@depends-on='"
                                                                        + doc.getAttributeValue("path") + "']");
                                                        for (int a = 0; a < actions.size(); a++) {
                                                            Element action = (Element) actions.get(a);
                                                            try {
                                                                FileInfo fileInfo = doApplyAction(action);
                                                                if (__fileInfo == null)
                                                                    __fileInfo = fileInfo;
                                                                else
                                                                    __fileInfo.merge(fileInfo);
                                                            } catch (Exception ex) {
                                                                logger.error("while applying " + action.toXML(),
                                                                        ex);
                                                            }
                                                        }
                                                    }
                                                }
                                            } else {
                                                DataLayerManager.getImplementation().removeCollectivite(
                                                        documentsModel.getDocumentById(dm.getTypeDoc()),
                                                        new Pair(dm.getCollectivite(), dm.getCollectivite()),
                                                        user);
                                                Nodes documents = archiveManifeste
                                                        .query("/manifeste/documents/document[@type='"
                                                                + dm.getTypeDoc() + "' and @buIdCol='"
                                                                + dm.getCollectivite() + "']");
                                                for (int i = 0; i < documents.size(); i++) {
                                                    Element doc = (Element) documents.get(i);
                                                    Element resultImport = getElement(
                                                            doc.query("m:resultatimport | resultatimport",
                                                                    getNamespaceCtx()));
                                                    if (resultImport != null)
                                                        doc.removeChild(resultImport);
                                                    doc.addAttribute(new Attribute("imported", "Non"));
                                                    // on applique les actions du document
                                                    Nodes actions = archiveManifeste
                                                            .query("/manifeste/on-delete/action[@depends-on='"
                                                                    + doc.getAttributeValue("path") + "']");
                                                    for (int a = 0; a < actions.size(); a++) {
                                                        Element action = (Element) actions.get(a);
                                                        try {
                                                            FileInfo fileInfo = doApplyAction(action);
                                                            if (__fileInfo == null)
                                                                __fileInfo = fileInfo;
                                                            else
                                                                __fileInfo.merge(fileInfo);
                                                        } catch (Exception ex) {
                                                            logger.error("while applying " + action.toXML(),
                                                                    ex);
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            DataLayerManager.getImplementation().removeDocumentModel(
                                                    documentsModel.getDocumentById(dm.getTypeDoc()), user);
                                            Nodes documents = archiveManifeste
                                                    .query("/manifeste/documents/document[@type='"
                                                            + dm.getTypeDoc() + "']");
                                            for (int i = 0; i < documents.size(); i++) {
                                                Element doc = (Element) documents.get(i);
                                                Element resultImport = getElement(
                                                        doc.query("m:resultatimport | resultatimport",
                                                                getNamespaceCtx()));
                                                if (resultImport != null)
                                                    doc.removeChild(resultImport);
                                                doc.addAttribute(new Attribute("imported", "Non"));
                                                // on applique les actions du document
                                                Nodes actions = archiveManifeste
                                                        .query("/manifeste/on-delete/action[@depends-on='"
                                                                + doc.getAttributeValue("path") + "']");
                                                for (int a = 0; a < actions.size(); a++) {
                                                    Element action = (Element) actions.get(a);
                                                    try {
                                                        FileInfo fileInfo = doApplyAction(action);
                                                        if (__fileInfo == null)
                                                            __fileInfo = fileInfo;
                                                        else
                                                            __fileInfo.merge(fileInfo);
                                                    } catch (Exception ex) {
                                                        logger.error("while applying " + action.toXML(), ex);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                doDelete = true;
                            }
                            importServiceProvider.endLongWait();
                        }

                        if (doImport) {
                            // Pour compatibilit avec les archives avant 2011, on traite toutes les actions qui ne sont pas on-delete et qui n'ont pas de depends-on
                            Nodes actions = archiveManifeste.query("/manifeste/action[not(@depends-on)]");
                            for (int i = 0; i < actions.size(); i++) {
                                Element action = (Element) actions.get(i);
                                try {
                                    FileInfo fileInfo = doApplyAction(action);
                                    if (__fileInfo == null)
                                        __fileInfo = fileInfo;
                                    else
                                        __fileInfo.merge(fileInfo);
                                } catch (Exception ex) {
                                    logger.error("while applying " + action.toXML(), ex);
                                }
                            }
                        }

                        if (doImport) {
                            // Pour les patchs edmn on applique les actions
                            Nodes actions = archiveManifeste.query("/manifeste/actions/action");
                            for (int i = 0; i < actions.size(); i++) {
                                Element action = (Element) actions.get(i);
                                try {
                                    FileInfo fileInfo = doApplyAction(action);
                                    if (__fileInfo == null)
                                        __fileInfo = fileInfo;
                                    else
                                        __fileInfo.merge(fileInfo);
                                } catch (Exception ex) {
                                    logger.error("while applying " + action.toXML(), ex);
                                }
                            }
                        }

                        if (doDelete) {
                            // Pour compatibilit avec les archives avant 2011, on traite toutes les actions qui ne sont pas on-delete et qui n'ont pas de depends-on
                            Nodes actions = archiveManifeste
                                    .query("/manifeste/on-delete/action[not(@depends-on)]");
                            for (int i = 0; i < actions.size(); i++) {
                                Element action = (Element) actions.get(i);
                                try {
                                    FileInfo fileInfo = doApplyAction(action);
                                    if (__fileInfo == null)
                                        __fileInfo = fileInfo;
                                    else
                                        __fileInfo.merge(fileInfo);
                                } catch (Exception ex) {
                                    logger.error("while applying " + action.toXML(), ex);
                                }
                            }
                        }
                    }
                    // dfinir ici si il y a des donnes ou non
                    if (archiveManifeste.query("/manifeste/documents/document[@imported='Oui']").size() > 0)
                        archiveManifeste.getRootElement()
                                .addAttribute(new Attribute("added:archive", Constants.ADDED_NS_URI, "Oui"));
                    else
                        archiveManifeste.getRootElement()
                                .addAttribute(new Attribute("added:archive", Constants.ADDED_NS_URI, "Non"));
                    // on ajoute les actions que l'on a pratiqu dans le manifeste,
                    // pour savoir quoi refaire plus tard...
                    archiveManifeste.getRootElement().appendChild(theSection.getXomDefinition());
                    sectionApplied = true;
                    break;
                } else {
                    // il n'y avait rien  importer, mais la section a quand mme t importe
                    sectionApplied = true;
                    break;
                }
            }
        }
        if (sectionApplied) {
            // on a trait toutes les sections, peut-tre il ne s'est rien pass...
            boolean somethingHasBeenImported = false;
            Nodes nodes = archiveManifeste.query("//document[@imported]");
            somethingHasBeenImported = nodes.size() > 0;
            // on recherche tous les documents qui n'ont pas t traits, et on positionne un @imported='false'
            nodes = archiveManifeste.query("//document[not(@imported)]");
            for (int i = 0; i < nodes.size(); i++) {
                Element el = (Element) nodes.get(i);
                el.addAttribute(new Attribute("imported", "Non"));
            }
            archiveManifeste.getRootElement()
                    .addAttribute(new Attribute("imported", Boolean.toString(somethingHasBeenImported)));
            Element result = new Element("resultatimport");
            if (result != null) {
                // on sait jamais... en cas de suppression par exemple...
                if (__fileInfo != null) {
                    result.addAttribute(
                            new Attribute("Duree", DateUtils.durationToString(__fileInfo.getDurationImport())));
                    result.addAttribute(new Attribute("Debut",
                            DateUtils.formatXsDateTime(new Date(__fileInfo.getDebutImport()))));
                    result.addAttribute(new Attribute("Fin",
                            DateUtils.formatXsDateTime(new Date(__fileInfo.getFinImport()))));
                    result.addAttribute(new Attribute("User", getUser().getId()));
                    result.addAttribute(new Attribute("LastModify",
                            DateUtils.formatXsDateTime(new Date(__fileInfo.getLastModify()))));
                    result.appendChild(__fileInfo.toXomXml(documentsModel));
                }
            }
            archiveManifeste.getRootElement().appendChild(result);
            // l'historique des imports
            Element event = new Element("evenement");
            event.addAttribute(new Attribute("date", DateUtils.formatXsDateTime(new Date())));
            event.addAttribute(new Attribute("user", getUser().getId()));
            event.addAttribute(new Attribute("section", archiveManifeste
                    .query("/manifeste/rul:section/@name", getNamespaceCtx()).get(0).getValue()));
            String version = archiveManifeste.getRootElement().getAttributeValue("version");
            if (version == null || version.length() == 0)
                version = "1";
            event.addAttribute(new Attribute("version-archive", version));
            historique.insertChild(event, 0);
            doImportManifeste(archiveManifeste, importProperties.get("archiveName").toString());
            DataLayerManager.getImplementation()
                    .declareArchiveImported(importProperties.get("archiveName").toString(), user);
            //                System.out.println(archiveManifeste.toXML());
        } else {
            errors.addError(Errors.SEVERITY_WARNING,
                    "Cette archive ne peut tre importe par aucune des rgles de cette configuration.");
        }
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage(), ex);
        errors.addError(Errors.SEVERITY_ERROR, ex.getMessage());
    } catch (IOException ioEx) {
        logger.error(fileToImport.getAbsolutePath() + ": " + ioEx.getMessage(), ioEx);
        errors.addError(Errors.SEVERITY_ERROR, ioEx.getMessage());
    } catch (ImportException iEx) {
        Errors.Error error = iEx.error;
        errors.addError(error);
    } catch (DataConfigurationException dcEx) {
        logger.error(dcEx.getMessage(), dcEx);
        errors.addError(Errors.SEVERITY_ERROR, dcEx.getMessage());
    } catch (DataAccessException daEx) {
        logger.error(daEx.getMessage(), daEx);
        errors.addError(Errors.SEVERITY_ERROR, daEx.getMessage());
    } catch (UnauthorizedException ex) {
        logger.error(ex.getMessage(), ex);
        errors.addError(Errors.SEVERITY_ERROR, ex.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
        errors.addError(Errors.SEVERITY_ERROR, t.getMessage());
    } finally {
        //            try { zipArchive.close(); } catch(Exception ex) {}
    }
    return errors;
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testResourceZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();//from ww  w.  j  a  va 2  s.  c  o  m
    String outputFileName = outputFile.getAbsolutePath();

    ZipFileWriterSource source = new ZipFileWriterSource();
    source.setResource(new FileSystemResource(outputFileName));

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(source);
    itemWriter.setup(getStepExecution(null));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:com.thruzero.common.core.utils.FileUtilsExt.java

public static final boolean unzipArchive(final File fromFile, final File toDir) throws IOException {
    boolean result = false; // assumes error

    logHelper.logBeginUnzip(fromFile, toDir);

    ZipFile zipFile = new ZipFile(fromFile);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    if (!toDir.exists()) {
        toDir.mkdirs();//  w  w  w . jav  a 2 s.  c o  m
        logHelper.logProgressCreatedToDir(toDir);
    }
    logHelper.logProgressToDirIsWritable(toDir);

    if (toDir.canWrite()) {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                File dir = new File(
                        toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName());

                if (!dir.exists()) {
                    dir.mkdirs();
                    logHelper.logProgressFilePathCreated(dir);
                }
            } else {
                File fosz = new File(
                        toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName());
                logHelper.logProgressCopyEntry(fosz);

                File parent = fosz.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }

                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fosz));
                IOUtils.copy(zipFile.getInputStream(entry), bos);
                bos.flush();
            }
        }
        zipFile.close();
        result = true; // success
    } else {
        logHelper.logFileWriteError(fromFile, null);
        zipFile.close();
    }

    return result;
}

From source file:net.sf.asap.Player.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Uri uri = getIntent().getData();/*from  w w w .j a  va 2s.c om*/
    filename = uri.getLastPathSegment();
    ZipFile zip = null;
    final byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH];
    int moduleLen;
    try {
        InputStream is;
        if (Util.isZip(filename)) {
            zip = new ZipFile(uri.getPath());
            filename = uri.getFragment();
            is = zip.getInputStream(zip.getEntry(filename));
        } else {
            try {
                is = getContentResolver().openInputStream(uri);
            } catch (FileNotFoundException ex) {
                if (uri.getScheme().equals("http"))
                    is = httpGet(uri);
                else
                    throw ex;
            }
        }
        moduleLen = readAndClose(is, module);
    } catch (IOException ex) {
        showError(R.string.error_reading_file);
        return;
    } finally {
        Util.close(zip);
    }
    try {
        asap.load(filename, module, moduleLen);
    } catch (Exception ex) {
        showError(R.string.invalid_file);
        return;
    }
    info = asap.getInfo();

    setTitle(R.string.playing_title);
    setContentView(R.layout.playing);
    setTag(R.id.name, info.getTitleOrFilename());
    setTag(R.id.author, info.getAuthor());
    setTag(R.id.date, info.getDate());
    findViewById(R.id.stop_button).setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    mediaController = new MediaController(this, false);
    mediaController.setAnchorView(getContentView());
    mediaController.setMediaPlayer(new MediaController.MediaPlayerControl() {
        public boolean canPause() {
            return !isPaused();
        }

        public boolean canSeekBackward() {
            return false;
        }

        public boolean canSeekForward() {
            return false;
        }

        public int getBufferPercentage() {
            return 100;
        }

        public int getCurrentPosition() {
            return asap.getPosition();
        }

        public int getDuration() {
            return info.getDuration(song);
        }

        public boolean isPlaying() {
            return !isPaused();
        }

        public void pause() {
            audioTrack.pause();
        }

        public void seekTo(int pos) {
            seek(pos);
        }

        public void start() {
            resume();
        }
    });
    if (info.getSongs() > 1) {
        mediaController.setPrevNextListeners(new OnClickListener() {
            public void onClick(View v) {
                playNextSong();
            }
        }, new OnClickListener() {
            public void onClick(View v) {
                playPreviousSong();
            }
        });
    }
    new Handler().postDelayed(new Runnable() {
        public void run() {
            mediaController.show();
        }
    }, 500);

    stop = false;
    playSong(info.getDefaultSong());
    new Thread(this).start();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ArchiveExpander.java

private void expandZip(final File expandDir, final Archive archive, final QcContext context)
        throws IOException {

    ZipFile zipFile = null;/*  w ww.j  a  v a2 s. com*/
    BufferedOutputStream out = null;
    try {
        zipFile = new ZipFile(archive.fullArchivePathAndName());
        // write each entry to the archive directory
        final Enumeration zipEnum = zipFile.entries();
        boolean foundArchiveDir = false;
        while (zipEnum.hasMoreElements()) {
            final ZipEntry entry = (ZipEntry) zipEnum.nextElement();
            if (!entry.isDirectory()) {
                String entryName = entry.getName();
                final File entryFile = new File(entryName);
                // extract out just the filename of the entry
                if (entryFile.getCanonicalPath().lastIndexOf(File.separator) != -1) {
                    entryName = entryFile.getCanonicalPath()
                            .substring(entryFile.getCanonicalPath().lastIndexOf(File.separator));
                }
                // the file to write is the archive dir plus just the filename
                final File archiveFile = new File(expandDir, entryName);
                InputStream in = zipFile.getInputStream(entry);
                FileOutputStream fout = new FileOutputStream(archiveFile);
                //noinspection IOResourceOpenedButNotSafelyClosed
                out = new BufferedOutputStream(fout);
                copyInputStream(in, out);
                in = null;
                out = null;
                fout.close();
                fout = null;

            } else {
                // if find a directory that isn't the archive name, add warning for weird archive structure
                if (!entry.getName().equals(archive.getArchiveName())
                        && !entry.getName().equals(archive.getArchiveName() + "/")) {
                    context.addWarning(new StringBuilder().append("Archive '")
                            .append("' has a non-standard directory '").append(entry.getName()).append("'.")
                            .append("Archive files should be contained inside a single directory with the archive name as its name.")
                            .toString());
                } else {
                    foundArchiveDir = true;
                }
            }
        }
        if (!foundArchiveDir) {
            context.addWarning(
                    "Archive files should be contained inside a single directory with the archive name as its name.");
        }
    } finally {
        IOUtils.closeQuietly(out);

        if (zipFile != null) {
            zipFile.close();
        }
    }
}