Example usage for java.util.zip ZipInputStream closeEntry

List of usage examples for java.util.zip ZipInputStream closeEntry

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:com.adobe.phonegap.contentsync.Sync.java

private boolean unzipSync(File targetFile, String outputDirectory, ProgressEvent progress,
        CallbackContext callbackContext) {
    Log.d(LOG_TAG, "unzipSync called");
    Log.d(LOG_TAG, "zip = " + targetFile.getAbsolutePath());
    InputStream inputStream = null;
    ZipFile zip = null;/*  w  w w  .java 2 s  .c  o m*/
    boolean anyEntries = false;
    try {
        synchronized (progress) {
            if (progress.isAborted()) {
                return false;
            }
        }

        zip = new ZipFile(targetFile);

        // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
        // Accept a path or a URI for the source zip.
        Uri zipUri = getUriForArg(targetFile.getAbsolutePath());
        Uri outputUri = getUriForArg(outputDirectory);

        CordovaResourceApi resourceApi = webView.getResourceApi();

        File tempFile = resourceApi.mapUriToFile(zipUri);
        if (tempFile == null || !tempFile.exists()) {
            sendErrorMessage("Zip file does not exist", UNZIP_ERROR, callbackContext);
        }

        File outputDir = resourceApi.mapUriToFile(outputUri);
        outputDirectory = outputDir.getAbsolutePath();
        outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
        if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
            sendErrorMessage("Could not create output directory", UNZIP_ERROR, callbackContext);
        }

        OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
        progress.setStatus(STATUS_EXTRACTING);
        progress.setLoaded(0);
        progress.setTotal(zip.size());
        Log.d(LOG_TAG, "zip file len = " + zip.size());

        inputStream = new BufferedInputStream(zipFile.inputStream);
        inputStream.mark(10);
        int magic = readInt(inputStream);

        if (magic != 875721283) { // CRX identifier
            inputStream.reset();
        } else {
            // CRX files contain a header. This header consists of:
            //  * 4 bytes of magic number
            //  * 4 bytes of CRX format version,
            //  * 4 bytes of public key length
            //  * 4 bytes of signature length
            //  * the public key
            //  * the signature
            // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.
            readInt(inputStream); // version == 2.
            int pubkeyLength = readInt(inputStream);
            int signatureLength = readInt(inputStream);

            inputStream.skip(pubkeyLength + signatureLength);
        }

        // The inputstream is now pointing at the start of the actual zip file content.
        ZipInputStream zis = new ZipInputStream(inputStream);
        inputStream = zis;

        ZipEntry ze;
        byte[] buffer = new byte[32 * 1024];

        while ((ze = zis.getNextEntry()) != null) {
            synchronized (progress) {
                if (progress.isAborted()) {
                    return false;
                }
            }

            anyEntries = true;
            String compressedName = ze.getName();

            if (ze.getSize() > getFreeSpace()) {
                return false;
            }

            if (ze.isDirectory()) {
                File dir = new File(outputDirectory + compressedName);
                dir.mkdirs();
            } else {
                File file = new File(outputDirectory + compressedName);
                file.getParentFile().mkdirs();
                if (file.exists() || file.createNewFile()) {
                    Log.w(LOG_TAG, "extracting: " + file.getPath());
                    FileOutputStream fout = new FileOutputStream(file);
                    int count;
                    while ((count = zis.read(buffer)) != -1) {
                        fout.write(buffer, 0, count);
                    }
                    fout.close();
                }

            }
            progress.addLoaded(1);
            updateProgress(callbackContext, progress);
            zis.closeEntry();
        }
    } catch (Exception e) {
        String errorMessage = "An error occurred while unzipping.";
        sendErrorMessage(errorMessage, UNZIP_ERROR, callbackContext);
        Log.e(LOG_TAG, errorMessage, e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
            }
        }
    }

    if (anyEntries)
        return true;
    else
        return false;
}

From source file:org.jahia.services.importexport.ImportExportBaseService.java

private void importSiteZip(ZipInputStream zis2, final String uri, final Resource fileImport,
        JCRSessionWrapper session) throws IOException {
    ZipEntry z;//from  www  .  java2s .  co  m
    final Properties infos = new Properties();
    while ((z = zis2.getNextEntry()) != null) {
        if ("site.properties".equals(z.getName())) {
            infos.load(zis2);
            zis2.closeEntry();

            boolean siteKeyEx = false;
            boolean serverNameEx = false;
            try {
                siteKeyEx = "".equals(infos.get("sitekey"))
                        || sitesService.siteExists((String) infos.get("sitekey"), session);
                String serverName = (String) infos.get("siteservername");
                serverNameEx = "".equals(serverName) || (!Url.isLocalhost(serverName)
                        && sitesService.getSiteByServerName(serverName, session) != null);
            } catch (RepositoryException e) {
                logger.error("Error when getting site", e);
            }

            if (!siteKeyEx && !serverNameEx) {
                // site import
                String tpl = (String) infos.get("templatePackageName");
                if ("".equals(tpl)) {
                    tpl = null;
                }
                try {
                    Locale locale = null;
                    if (infos.getProperty("defaultLanguage") != null) {
                        locale = LanguageCodeConverters
                                .languageCodeToLocale(infos.getProperty("defaultLanguage"));
                    } else {
                        for (Object obj : infos.keySet()) {
                            String s = (String) obj;
                            if (s.startsWith("language.") && s.endsWith(".rank")) {
                                String code = s.substring(s.indexOf('.') + 1, s.lastIndexOf('.'));
                                String rank = infos.getProperty(s);
                                if (rank.equals("1")) {
                                    locale = LanguageCodeConverters.languageCodeToLocale(code);
                                }
                            }
                        }
                    }
                    final Locale finalLocale = locale;
                    final String finalTpl = tpl;
                    try {
                        JCRObservationManager.doWithOperationType(session, JCRObservationManager.IMPORT,
                                new JCRCallback<Object>() {

                                    @Override
                                    public Object doInJCR(JCRSessionWrapper session)
                                            throws RepositoryException {
                                        try {
                                            JahiaSite site = sitesService.addSite(
                                                    JCRSessionFactory.getInstance().getCurrentUser(),
                                                    infos.getProperty("sitetitle"),
                                                    infos.getProperty("siteservername"),
                                                    infos.getProperty("sitekey"),
                                                    infos.getProperty("description"), finalLocale, finalTpl,
                                                    null,
                                                    fileImport != null ? "fileImport" : "importRepositoryFile",
                                                    fileImport, uri, true, false,
                                                    infos.getProperty("originatingJahiaRelease"), null, null,
                                                    session);
                                            importSiteProperties(site, infos, session);
                                        } catch (JahiaException e) {
                                            throw new RepositoryException(e);
                                        } catch (IOException e) {
                                            throw new RepositoryException(e);
                                        }
                                        return null;
                                    }
                                });
                    } catch (RepositoryException e) {
                        if (e.getCause() != null && (e.getCause() instanceof JahiaException
                                || e.getCause() instanceof IOException)) {
                            throw (Exception) e.getCause();
                        }
                    }
                } catch (Exception e) {
                    logger.error("Cannot create site " + infos.get("sitetitle"), e);
                }
            }
        }
    }
}

From source file:org.openbravo.erpCommon.modules.ImportModule.java

/**
 * Installs or updates the modules in the obx file
 * //from w ww  . j  a  va  2s .  c o  m
 * @param obx
 * @param moduleID
 *          The ID for the current module to install
 * @throws Exception
 */
private void installModule(InputStream obx, String moduleID, Vector<DynaBean> dModulesToInstall,
        Vector<DynaBean> dDependencies, Vector<DynaBean> dDBprefix) throws Exception {

    // For local installations modules are temporary unzipped in tmp/localInstall directory, because
    // it is possible this version in obx is not going to be installed, in any case it must be
    // unzipped looking for other obx files inside it.
    String fileDestination = installLocally && !"0".equals(moduleID) ? obDir + "/tmp/localInstall" : obDir;

    if (!(new File(fileDestination + "/modules").canWrite())) {
        addLog("@CannotWriteDirectory@ " + fileDestination + "/modules. ", MSG_ERROR);
        throw new PermissionException("Cannot write on directory: " + fileDestination + "/modules");
    }

    final ZipInputStream obxInputStream = new ZipInputStream(obx);
    ZipEntry entry = null;
    while ((entry = obxInputStream.getNextEntry()) != null) {
        if (entry.getName().endsWith(".obx")) { // If it is a new module
            // install it
            if (installLocally) {
                final ByteArrayInputStream ba = new ByteArrayInputStream(
                        getBytesCurrentEntryStream(obxInputStream));

                installModule(ba, moduleID, dModulesToInstall, dDependencies, dDBprefix);
            } // If install remotely it is no necessary to install the .obx
              // because it will be get from CR
            obxInputStream.closeEntry();
        } else {
            // Unzip the contents
            final String fileName = fileDestination + (moduleID.equals("0") ? "/" : "/modules/")
                    + entry.getName().replace("\\", "/");
            final File entryFile = new File(fileName);
            // Check whether the directory exists, if not create

            File dir = null;
            if (entryFile.getParent() != null)
                dir = new File(entryFile.getParent());
            if (entry.isDirectory())
                dir = entryFile;

            if (entry.isDirectory() || entryFile.getParent() != null) {
                if (!dir.exists()) {
                    log4j.debug("Created dir: " + dir.getAbsolutePath());
                    dir.mkdirs();
                }
            }

            if (!entry.isDirectory()) {
                // It is a file
                byte[] entryBytes = null;
                boolean found = false;
                // Read the xml file to obtain module info
                if (entry.getName().replace("\\", "/").endsWith("src-db/database/sourcedata/AD_MODULE.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> module = getEntryDynaBeans(entryBytes);
                    moduleID = (String) module.get(0).get("AD_MODULE_ID");
                    if (installingModule(moduleID)) {
                        dModulesToInstall.addAll(module);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                } else if (entry.getName().replace("\\", "/")
                        .endsWith("src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> dep = getEntryDynaBeans(entryBytes);
                    if (installingModule((String) dep.get(0).get("AD_MODULE_ID"))) {
                        dDependencies.addAll(dep);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                } else if (entry.getName().replace("\\", "/")
                        .endsWith("src-db/database/sourcedata/AD_MODULE_DBPREFIX.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> dbp = getEntryDynaBeans(entryBytes);
                    if (installingModule((String) dbp.get(0).get("AD_MODULE_ID"))) {
                        dDBprefix.addAll(dbp);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                }

                // Unzip the file
                log4j.debug("Installing " + fileName);

                final FileOutputStream fout = new FileOutputStream(entryFile);

                if (found) {
                    // the entry is already read as a byte[]
                    fout.write(entryBytes);
                } else {
                    final byte[] buf = new byte[4096];
                    int len;
                    while ((len = obxInputStream.read(buf)) > 0) {
                        fout.write(buf, 0, len);
                    }
                }

                fout.close();
            }

            obxInputStream.closeEntry();
        }
    }
    obxInputStream.close();
}

From source file:hudson.FilePath.java

private void unzip(File dir, InputStream in) throws IOException {
    dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail
    ZipInputStream zip = new ZipInputStream(new BufferedInputStream(in));
    java.util.zip.ZipEntry e;/*from  w  ww . ja v  a2 s.c  o m*/

    try {
        while ((e = zip.getNextEntry()) != null) {
            File f = new File(dir, e.getName());
            if (e.isDirectory()) {
                f.mkdirs();
            } else {
                File p = f.getParentFile();
                if (p != null)
                    p.mkdirs();
                FileOutputStream out = new FileOutputStream(f);
                try {
                    IOUtils.copy(zip, out);
                } finally {
                    out.close();
                }
                f.setLastModified(e.getTime());
                zip.closeEntry();
            }
        }
    } finally {
        zip.close();
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionImportService.java

protected Model readZipFile(InputStream inputStream, Map<String, String> formMap,
        Map<String, String> decisionTableMap, Map<String, String> bpmnModelMap,
        Map<String, String> cmmnModelMap, Map<String, byte[]> thumbnailMap) {

    Model appDefinitionModel = null;/*  w w w  .  ja  v a 2  s .c  o  m*/
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String zipEntryName = zipEntry.getName();
            if (zipEntryName.endsWith("json") || zipEntryName.endsWith("png")) {

                String modelFileName = null;
                if (zipEntryName.contains("/")) {
                    modelFileName = zipEntryName.substring(zipEntryName.indexOf('/') + 1);
                } else {
                    modelFileName = zipEntryName;
                }

                if (modelFileName.endsWith(".png")) {
                    thumbnailMap.put(modelFileName.replace(".png", ""), IOUtils.toByteArray(zipInputStream));

                } else {
                    modelFileName = modelFileName.replace(".json", "");
                    String json = IOUtils.toString(zipInputStream, "utf-8");

                    if (zipEntryName.startsWith("bpmn-models/")) {
                        bpmnModelMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("cmmn-models/")) {
                        cmmnModelMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("form-models/")) {
                        formMap.put(modelFileName, json);

                    } else if (zipEntryName.startsWith("decision-table-models/")) {
                        decisionTableMap.put(modelFileName, json);

                    } else if (!zipEntryName.contains("/")) {
                        appDefinitionModel = createModelObject(json, Model.MODEL_TYPE_APP);
                    }
                }
            }

            zipEntry = zipInputStream.getNextEntry();
        }
    } catch (Exception e) {
        LOGGER.error("Error reading app definition zip file", e);
        throw new InternalServerErrorException("Error reading app definition zip file");

    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.closeEntry();
            } catch (Exception e) {
            }

            try {
                zipInputStream.close();
            } catch (Exception e) {
            }
        }
    }

    return appDefinitionModel;
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

public void importFromZipStep1(InputStream is) throws WPBIOException {
    ZipInputStream zis = new ZipInputStream(is);
    // we need to stop the notifications during import
    dataStorage.stopNotifications();/*w  ww .  j  av a 2 s.com*/
    try {
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (name.indexOf(PATH_URIS) >= 0) {
                if (name.indexOf("/parameters/") >= 0 && name.indexOf("metadata.xml") >= 0) {
                    importParameter(zis);
                } else if (name.indexOf("metadata.xml") >= 0) {
                    // this is a web site url
                    importUri(zis);
                }
            } else if (name.indexOf(PATH_GLOBALS) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importParameter(zis);
                }
            } else if (name.indexOf(PATH_SITE_PAGES) >= 0) {
                if (name.indexOf("/parameters/") >= 0 && name.indexOf("metadata.xml") >= 0) {
                    importParameter(zis);
                } else if (name.indexOf("metadata.xml") >= 0) {
                    importWebPage(zis);
                }
            } else if (name.indexOf(PATH_SITE_PAGES_MODULES) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importPageModule(zis);
                }
            } else if (name.indexOf(PATH_ARTICLES) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importArticle(zis);
                }
            } else if (name.indexOf(PATH_MESSAGES) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importMessage(zis);
                }
            } else if (name.indexOf(PATH_FILES) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importFile(zis);
                }
            } else if (name.indexOf(PATH_LOCALES) >= 0) {
                if (name.indexOf("metadata.xml") >= 0) {
                    importProject(zis);
                }
            }
            zis.closeEntry();
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("cannot import from  zip step 1", e);
    }
}

From source file:org.jahia.services.importexport.ImportExportBaseService.java

private void importFilesAcl(JahiaSite site, Resource file, InputStream is, DefinitionsMapping mapping,
        List<String> fileList) {
    Map<String, File> filePath = new HashMap<String, File>();
    File temp = null;//from w  w  w . j  a v a 2s .c o m
    try {
        Path tempPath = Files.createTempDirectory("migration");
        temp = tempPath.toFile();
        ZipInputStream zis = getZipInputStream(file);
        try {
            ZipEntry zipentry;
            while ((zipentry = zis.getNextEntry()) != null) {
                String fileName = zipentry.getName();
                if (!zipentry.isDirectory()) {
                    fileName = fileName.replace('\\', '/');
                    File newFile = new File(temp, fileName);
                    newFile.getParentFile().mkdirs();
                    FileUtils.copyInputStreamToFile(zis, newFile);
                    filePath.put("/" + fileName, newFile);
                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }

        handleImport(is, new FilesAclImportHandler(site, mapping, file, fileList, filePath),
                file.getFilename());
    } catch (IOException e) {
        logger.error("Cannot extract zip", e);
    } finally {
        FileUtils.deleteQuietly(temp);
    }
}

From source file:org.sakaiproject.metaobj.shared.mgt.impl.StructuredArtifactDefinitionManagerImpl.java

public StructuredArtifactDefinitionBean readSADfromZip(ZipInputStream zis, String worksite, boolean publish)
        throws IOException {
    StructuredArtifactDefinitionBean bean = new StructuredArtifactDefinitionBean();
    boolean hasXML = false, hasXSD = false;

    bean.setCreated(new Date(System.currentTimeMillis()));
    bean.setModified(bean.getCreated());

    bean.setOwner(getAuthManager().getAgent());
    bean.setSiteId(worksite);// w  w  w  .  j  a v a  2  s.  c  om
    bean.setSiteState(publish ? StructuredArtifactDefinitionBean.STATE_PUBLISHED
            : StructuredArtifactDefinitionBean.STATE_UNPUBLISHED);

    if (isGlobal(worksite)) {
        bean.setGlobalState(publish ? StructuredArtifactDefinitionBean.STATE_PUBLISHED
                : StructuredArtifactDefinitionBean.STATE_UNPUBLISHED);
        bean.setSiteId(null);
    }

    ZipEntry currentEntry = zis.getNextEntry();

    if (currentEntry == null) {
        return null;
    }

    // If the zip was opened and re-zipped, then the directory was
    //    compressed with the files.  we need to deal with 
    //    the directory
    if (currentEntry.getName().endsWith("/")) {
        zis.closeEntry();
        currentEntry = zis.getNextEntry();
    }

    try {
        Hashtable<Id, Id> fileMap = new Hashtable<Id, Id>();
        String tempDirName = getIdManager().createId().getValue();
        ContentCollectionEdit fileParent = getExpandedFileDir(tempDirName);
        boolean gotFile = false;

        while (currentEntry != null) {
            logger.debug("current entry name: " + currentEntry.getName());

            File entryFile = new File(currentEntry.getName());

            if (entryFile.getName().startsWith(".")) {
                logger.warn(".readSADfromZip skipping control file: " + currentEntry.getName());
            } else if (currentEntry.getName().endsWith("xml")) {
                readSADfromXML(bean, zis);
                hasXML = true;
            } else if (currentEntry.getName().endsWith("xsd")) {
                readSADSchemaFromXML(bean, zis);
                hasXSD = true;
            } else if (!currentEntry.isDirectory()) {
                gotFile = true;
                processFile(currentEntry, zis, fileMap, fileParent);

            }

            zis.closeEntry();
            currentEntry = zis.getNextEntry();
        }

        if (gotFile) {
            fileParent.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME,
                    bean.getDescription());
            getContentHosting().commitCollection(fileParent);
        } else {
            getContentHosting().cancelCollection(fileParent);
        }

        if (bean.getAlternateCreateXslt() != null)
            bean.setAlternateCreateXslt((Id) fileMap.get(bean.getAlternateCreateXslt()));

        if (bean.getAlternateViewXslt() != null)
            bean.setAlternateViewXslt((Id) fileMap.get(bean.getAlternateViewXslt()));

    } catch (Exception exp) {
        logger.error(".readSADFromZip", exp);
        return null;
    }

    bean.setSchemaHash(calculateSchemaHash(bean));
    return bean;
}

From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java

/**
 * This method takes a zip file and reads out the entries.
 * //from  w  ww  .jav  a2s.c o  m
 * @param in
 * @throws TechnicalException
 * @throws NamingException
 * @throws SWORDContentTypeException
 */
public PubItemVO readZipFile(InputStream in, AccountUserVO user)
        throws ItemInvalidException, ContentStreamNotFoundException, Exception {
    String item = null;
    List<FileVO> attachements = new ArrayList<FileVO>();
    // List<String> attachementsNames = new ArrayList< String>();
    PubItemVO pubItem = null;
    final int bufLength = 1024;
    char[] buffer = new char[bufLength];
    int readReturn;
    int count = 0;

    try {
        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);
        // ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            this.logger.debug("Processing zip entry file: " + zipentry.getName());

            String name = URLDecoder.decode(zipentry.getName(), "UTF-8");
            name = name.replaceAll("/", "_slsh_");
            this.filenames.add(name);
            boolean metadata = false;

            // check if the file is a metadata file
            for (int i = 0; i < this.fileEndings.length; i++) {

                String ending = this.fileEndings[i];
                if (name.endsWith(ending)) {
                    metadata = true;
                    // Retrieve the metadata

                    StringWriter sw = new StringWriter();
                    Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

                    while ((readReturn = reader.read(buffer)) != -1) {
                        sw.write(buffer, 0, readReturn);
                    }

                    item = new String(sw.toString());
                    this.depositXml = item;
                    this.depositXmlFileName = name;
                    pubItem = createItem(item, user);

                    // if not escidoc format, add as component
                    if (!this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) {
                        attachements.add(convertToFileAndAdd(new ByteArrayInputStream(item.getBytes("UTF-8")),
                                name, user, zipentry));
                    }
                }
            }

            if (!metadata) {
                attachements.add(convertToFileAndAdd(zipinputstream, name, user, zipentry));
            }

            zipinputstream.closeEntry();
        }
        zipinputstream.close();

        // Now add the components to the Pub Item (if they do not exist. If they exist, use the
        // existing component metadata and just change the content)
        for (FileVO newFile : attachements) {
            boolean existing = false;
            for (FileVO existingFile : pubItem.getFiles()) {
                if (existingFile.getName().replaceAll("/", "_slsh_").equals(newFile.getName())) {
                    // file already exists, replace content
                    existingFile.setContent(newFile.getContent());
                    existingFile.getDefaultMetadata().setSize(newFile.getDefaultMetadata().getSize());
                    existing = true;
                }
            }

            if (!existing) {
                pubItem.getFiles().add(newFile);
            }

        }

        // If peer format, add additional copyright information to component. They are read from the
        // TEI metadata.
        if (this.currentDeposit.getFormatNamespace().equals(this.mdFormatPeerTEI)) {
            // Copyright information are imported from metadata file
            InitialContext initialContext = new InitialContext();
            XmlTransformingBean xmlTransforming = new XmlTransformingBean();
            Transformation transformer = new TransformationBean();
            Format teiFormat = new Format("peer_tei", "application/xml", "UTF-8");
            Format escidocComponentFormat = new Format("eSciDoc-publication-component", "application/xml",
                    "UTF-8");
            String fileXml = new String(transformer.transform(this.depositXml.getBytes(), teiFormat,
                    escidocComponentFormat, "escidoc"), "UTF-8");
            try {
                FileVO transformdedFileVO = xmlTransforming.transformToFileVO(fileXml);
                for (FileVO pubItemFile : pubItem.getFiles()) {
                    pubItemFile.getDefaultMetadata()
                            .setRights(transformdedFileVO.getDefaultMetadata().getRights());
                    pubItemFile.getDefaultMetadata()
                            .setCopyrightDate(transformdedFileVO.getDefaultMetadata().getCopyrightDate());
                }
            } catch (TechnicalException e) {
                this.logger.error("File Xml could not be transformed into FileVO. ", e);
            }
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (count == 0) {
        this.logger.info("No zip file was provided.");
        this.depositServlet.setError("No zip file was provided.");
        throw new SWORDContentTypeException();
    }

    // pubItem = this.processFiles(item, attachements, attachementsNames, user);

    return pubItem;
}

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

/**
 * This method takes a zip file and reads out the entries.
 * @param in/*ww w.j  av  a  2s  .  c  om*/
 * @throws TechnicalException
 * @throws NamingException
 * @throws SWORDContentTypeException
 */
public PubItemVO readZipFile(InputStream in, AccountUserVO user)
        throws ItemInvalidException, ContentStreamNotFoundException, Exception {
    String item = null;
    List<FileVO> attachements = new ArrayList<FileVO>();
    //List<String> attachementsNames = new ArrayList< String>();
    PubItemVO pubItem = null;
    final int bufLength = 1024;
    char[] buffer = new char[bufLength];
    int readReturn;
    int count = 0;

    try {
        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);
        //ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            this.logger.debug("Processing zip entry file: " + zipentry.getName());

            String name = URLDecoder.decode(zipentry.getName(), "UTF-8");
            name = name.replaceAll("/", "_slsh_");
            this.filenames.add(name);
            boolean metadata = false;

            //check if the file is a metadata file
            for (int i = 0; i < this.fileEndings.length; i++) {

                String ending = this.fileEndings[i];
                if (name.endsWith(ending)) {
                    metadata = true;
                    //Retrieve the metadata

                    StringWriter sw = new StringWriter();
                    Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

                    while ((readReturn = reader.read(buffer)) != -1) {
                        sw.write(buffer, 0, readReturn);
                    }

                    item = new String(sw.toString());
                    this.depositXml = item;
                    this.depositXmlFileName = name;
                    pubItem = createItem(item, user);

                    //if not escidoc format, add as component
                    if (!this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) {
                        attachements.add(convertToFileAndAdd(new ByteArrayInputStream(item.getBytes("UTF-8")),
                                name, user, zipentry));
                    }
                }
            }

            if (!metadata) {
                attachements.add(convertToFileAndAdd(zipinputstream, name, user, zipentry));
            }

            zipinputstream.closeEntry();
        }
        zipinputstream.close();

        // Now add the components to the Pub Item (if they do not exist. If they exist, use the existing component metadata and just change the content)
        for (FileVO newFile : attachements) {
            boolean existing = false;
            for (FileVO existingFile : pubItem.getFiles()) {
                if (existingFile.getName().replaceAll("/", "_slsh_").equals(newFile.getName())) {
                    //file already exists, replace content
                    existingFile.setContent(newFile.getContent());
                    existingFile.getDefaultMetadata().setSize(newFile.getDefaultMetadata().getSize());
                    existing = true;
                }
            }

            if (!existing) {
                pubItem.getFiles().add(newFile);
            }

        }

        //If peer format, add additional copyright information to component. They are read from the TEI metadata.
        if (this.currentDeposit.getFormatNamespace().equals(this.mdFormatPeerTEI)) {
            //Copyright information are imported from metadata file
            InitialContext initialContext = new InitialContext();
            XmlTransformingBean xmlTransforming = new XmlTransformingBean();
            Transformation transformer = new TransformationBean();
            Format teiFormat = new Format("peer_tei", "application/xml", "UTF-8");
            Format escidocComponentFormat = new Format("eSciDoc-publication-component", "application/xml",
                    "UTF-8");
            String fileXml = new String(transformer.transform(this.depositXml.getBytes(), teiFormat,
                    escidocComponentFormat, "escidoc"), "UTF-8");
            try {
                FileVO transformdedFileVO = xmlTransforming.transformToFileVO(fileXml);
                for (FileVO pubItemFile : pubItem.getFiles()) {
                    pubItemFile.getDefaultMetadata()
                            .setRights(transformdedFileVO.getDefaultMetadata().getRights());
                    pubItemFile.getDefaultMetadata()
                            .setCopyrightDate(transformdedFileVO.getDefaultMetadata().getCopyrightDate());
                }
            } catch (TechnicalException e) {
                this.logger.error("File Xml could not be transformed into FileVO. ", e);
            }
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (count == 0) {
        this.logger.info("No zip file was provided.");
        this.depositServlet.setError("No zip file was provided.");
        throw new SWORDContentTypeException();
    }

    //pubItem = this.processFiles(item, attachements, attachementsNames, user);

    return pubItem;
}