Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

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

/**
 * This method takes a zip file and reads out the entries.
 * /*from www. j a va  2  s.co  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//from  ww w .j av  a  2 s  .  c  o m
 * @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:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

private void extractJSEmbedding(final JSEmbeddingItemTO packet)
        throws BrandingFailureException, NoSuchAlgorithmException, FileNotFoundException, IOException {
    File brandingCache = getJSEmbeddingPacketFile(packet.name);
    if (!brandingCache.exists())
        throw new BrandingFailureException("Javascript package not found!");

    File jsRootDir = getJSEmbeddingRootDirectory();
    if (!(jsRootDir.exists() || jsRootDir.mkdir()))
        throw new BrandingFailureException("Could not create private javascript dir!");

    File jsPacketDir = getJSEmbeddingPacketDirectory(packet.name);
    if (jsPacketDir.exists() && !SystemUtils.deleteDir(jsPacketDir))
        throw new BrandingFailureException("Could not delete existing javascript dir");
    if (!jsPacketDir.mkdir())
        throw new BrandingFailureException("Could not create javascript dir");

    MessageDigest digester = MessageDigest.getInstance("SHA256");
    DigestInputStream dis = new DigestInputStream(new BufferedInputStream(new FileInputStream(brandingCache)),
            digester);/*from w  w  w.j av  a2s .co m*/
    try {
        ZipInputStream zis = new ZipInputStream(dis);
        try {
            byte data[] = new byte[BUFFER_SIZE];
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                L.d("Extracting: " + entry);
                int count = 0;
                if (entry.isDirectory()) {
                    L.d("Skipping javascript dir " + entry.getName());
                    continue;
                }
                File destination = new File(jsPacketDir, entry.getName());
                destination.getParentFile().mkdirs();
                final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination),
                        BUFFER_SIZE);
                try {
                    while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                        fos.write(data, 0, count);
                    }
                } finally {
                    fos.close();
                }
            }
            while (dis.read(data) >= 0)
                ;
        } finally {
            zis.close();
        }
    } finally {
        dis.close();
    }
}

From source file:org.geoserver.wps.gs.download.DownloadProcessTest.java

/**
 * Private method for decoding a Shapefile
 * //from  w w w.  j  av  a  2  s  .  c  o  m
 * @param input the input shp
 * @return the object a {@link SimpleFeatureCollection} object related to the shp file.
 * @throws Exception the exception
 */
private Object decodeShape(InputStream input) throws Exception {
    // create the temp directory and register it as a temporary resource
    File tempDir = IOUtils.createRandomDirectory(IOUtils.createTempDirectory("shpziptemp").getAbsolutePath(),
            "download-process", "download-services");

    // unzip to the temporary directory
    ZipInputStream zis = null;
    File shapeFile = null;
    File zipFile = null;

    // extract shp-zip file
    try {
        zis = new ZipInputStream(input);
        ZipEntry entry = null;

        // Cycle on all the entries and copies the input shape in the target directory
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();
            File file = new File(tempDir, entry.getName());
            if (entry.isDirectory()) {
                file.mkdir();
            } else {

                if (file.getName().toLowerCase().endsWith(".shp")) {
                    shapeFile = file;
                } else if (file.getName().toLowerCase().endsWith(".zip")) {
                    zipFile = file;
                }

                int count;
                byte data[] = new byte[4096];
                // write the files to the disk
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    while ((count = zis.read(data)) != -1) {
                        fos.write(data, 0, count);
                    }
                    fos.flush();
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }

            }
            zis.closeEntry();
        }
    } finally {
        if (zis != null) {
            zis.close();
        }
    }

    // Read the shapefile
    if (shapeFile == null) {
        if (zipFile != null)
            return decodeShape(new FileInputStream(zipFile));
        else {
            FileUtils.deleteDirectory(tempDir);
            throw new IOException("Could not find any file with .shp extension in the zip file");
        }
    } else {
        ShapefileDataStore store = new ShapefileDataStore(DataUtilities.fileToURL(shapeFile));
        return store.getFeatureSource().getFeatures();
    }
}

From source file:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Gets a list of all the locally cached genome archive files that
 * IGV knows about./* ww w  . ja  v  a  2s  .c o m*/
 *
 * @return LinkedHashSet<GenomeListItem>
 * @throws IOException
 * @see GenomeListItem
 */
private List<GenomeListItem> getCachedGenomeArchiveList() throws IOException {

    if (cachedGenomeArchiveList == null) {
        cachedGenomeArchiveList = new LinkedList<GenomeListItem>();

        if (!DirectoryManager.getGenomeCacheDirectory().exists()) {
            return cachedGenomeArchiveList;
        }

        File[] files = DirectoryManager.getGenomeCacheDirectory().listFiles();
        for (File file : files) {

            if (file.isDirectory()) {
                continue;
            }

            if (!file.getName().toLowerCase().endsWith(Globals.GENOME_FILE_EXTENSION)) {
                continue;
            }

            ZipFile zipFile = null;
            FileInputStream fis = null;
            ZipInputStream zipInputStream = null;
            try {

                zipFile = new ZipFile(file);
                fis = new FileInputStream(file);
                zipInputStream = new ZipInputStream(new BufferedInputStream(fis));

                ZipEntry zipEntry = zipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                if (zipEntry == null) {
                    continue; // Should never happen
                }

                InputStream inputStream = zipFile.getInputStream(zipEntry);
                Properties properties = new Properties();
                properties.load(inputStream);

                int version = 0;
                if (properties.containsKey(Globals.GENOME_ARCHIVE_VERSION_KEY)) {
                    try {
                        version = Integer.parseInt(properties.getProperty(Globals.GENOME_ARCHIVE_VERSION_KEY));
                    } catch (Exception e) {
                        log.error("Error parsing genome version: " + version, e);
                    }
                }

                GenomeListItem item = new GenomeListItem(
                        properties.getProperty(Globals.GENOME_ARCHIVE_NAME_KEY), file.getAbsolutePath(),
                        properties.getProperty(Globals.GENOME_ARCHIVE_ID_KEY));
                cachedGenomeArchiveList.add(item);
            } catch (ZipException ex) {
                log.error("\nZip error unzipping cached genome.", ex);
                try {
                    file.delete();
                    zipInputStream.close();
                } catch (Exception e) {
                    //ignore exception when trying to delete file
                }
            } catch (IOException ex) {
                log.warn("\nIO error unzipping cached genome.", ex);
                try {
                    file.delete();
                } catch (Exception e) {
                    //ignore exception when trying to delete file
                }
            } finally {
                try {
                    if (zipInputStream != null) {
                        zipInputStream.close();
                    }
                    if (zipFile != null) {
                        zipFile.close();
                    }
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException ex) {
                    log.warn("Error closing genome zip stream!", ex);
                }
            }
        }
    }
    return cachedGenomeArchiveList;
}

From source file:net.cbtltd.rest.interhome.A_Handler.java

/**
 * Get unzipped input stream for file name.
 *
 * @param fn the file name./*from  w  w w  .j a va2  s  .  c  o  m*/
 * @return the input stream.
 * @throws Throwable the exception that can be thrown.
 */
private final synchronized FileInputStream ftp(String fn) throws Throwable {
    URL url = new URL("ftp://ihxmlpartner:S13oPjEu@ftp.interhome.com/" + fn + ".zip;type=i");
    URLConnection urlc = url.openConnection();

    byte[] buf = new byte[1024];
    ZipInputStream zinstream = new ZipInputStream(new BufferedInputStream(urlc.getInputStream()));
    ZipEntry zentry = zinstream.getNextEntry();
    String entryName = zentry.getName();
    FileOutputStream outstream = new FileOutputStream(entryName);
    int n;
    while ((n = zinstream.read(buf, 0, 1024)) > -1) {
        outstream.write(buf, 0, n);
    }
    outstream.close();
    zinstream.closeEntry();
    zinstream.close();
    return new FileInputStream(entryName);
}

From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java

/**
 * Imports a report resource from a zip file (see writeReportResToZipFile())
 * //from  w  ww  . j  av a  2  s  . c om
 * If resource contains an SpReport, the SpReport's data source query will be imported
 * as well if an equivalent query does not exist in the database.
 *  
 * @param file
 * @param appRes
 * @param dirArg
 * @param newResName
 * @return
 */
protected SpAppResource importSpReportZipResource(final File file, final SpAppResource appRes,
        final SpAppResourceDir dirArg, final String newResName) {
    SpAppResourceDir dir = dirArg;

    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(file));

        //Assuming they come out in the order they were put in.
        ZipEntry entry = zin.getNextEntry();
        if (entry == null) {
            throw new Exception(getResourceString("RIE_ReportImportFileError"));
        }
        String app = readZipEntryToString(zin, entry);
        zin.closeEntry();

        entry = zin.getNextEntry();
        if (entry == null) {
            throw new Exception(getResourceString("RIE_ReportImportFileError"));
        }
        String data = readZipEntryToString(zin, entry);
        zin.closeEntry();

        Element appRoot = XMLHelper.readStrToDOM4J(app);
        Node metadata = appRoot.selectSingleNode("metadata");
        String metadataStr = metadata.getStringValue();
        if (!metadataStr.endsWith(";")) {
            metadataStr += ";";
        }
        Node mimeTypeNode = appRoot.selectSingleNode("mimetype");
        String mimeTypeStr = mimeTypeNode != null ? mimeTypeNode.getStringValue().trim() : null;

        entry = zin.getNextEntry();
        if (entry != null) {
            appRes.setDataAsString(data);
            appRes.setMetaData(metadataStr.trim());

            String repType = appRes.getMetaDataMap().getProperty("reporttype");
            String mimeType = mimeTypeStr != null ? mimeTypeStr
                    : repType != null && repType.equalsIgnoreCase("label") ? "jrxml/label" : "jrxml/report";

            appRes.setMimeType(mimeType);
            appRes.setLevel((short) 3);//XXX level?????????????????

            String spReport = readZipEntryToString(zin, entry);
            zin.closeEntry();
            zin.close();

            Element repElement = XMLHelper.readStrToDOM4J(spReport);

            SpReport report = new SpReport();
            report.initialize();
            report.setSpecifyUser(contextMgr.getClassObject(SpecifyUser.class));
            report.fromXML(repElement, newResName != null, contextMgr);

            if (newResName != null) {
                report.setName(newResName);
            }
            appRes.setName(report.getName());
            appRes.setDescription(appRes.getName());

            if (newResName != null && report.getQuery() != null) {
                showLocalizedMsg("RIE_ReportNewQueryTitle", "RIE_ReportNewQueryMsg",
                        report.getQuery().getName(), report.getName());
            }

            report.setAppResource((SpAppResource) appRes);
            ((SpAppResource) appRes).getSpReports().add(report);

            DataProviderSessionIFace session = null;
            try {
                session = DataProviderFactory.getInstance().createSession();
                session.beginTransaction();

                if (dir.getId() != null) {
                    dir = session.get(SpAppResourceDir.class, dir.getId());
                }

                dir.getSpPersistedAppResources().add(appRes);
                appRes.setSpAppResourceDir(dir);

                if (report.getReportObject() != null && report.getReportObject().getId() == null) {
                    session.saveOrUpdate(report.getReportObject());
                }
                session.saveOrUpdate(dir);
                session.saveOrUpdate(appRes);
                session.saveOrUpdate(report);

                session.commit();
                completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", file.getName());

            } catch (Exception ex) {
                session.rollback();
                //ex.printStackTrace();
                throw ex;

            } finally {
                if (session != null)
                    session.close();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ResourceImportExportDlg.class, e);
        return null;
    }

    return appRes;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Copies the content of a Jar/Zip archive into the receiver archive.
 * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files
 * to copy over./*ww w . ja  va 2 s.  c  om*/
 *
 * @param input  the {@link InputStream} for the Jar/Zip to copy.
 * @param filter the filter or <code>null</code>
 * @throws IOException
 * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write
 *                                                            must be aborted.
 */
public void writeZip(InputStream input, IZipEntryFilter filter)
        throws IOException, IZipEntryFilter.ZipAbortException {
    ZipInputStream zis = new ZipInputStream(input);

    try {
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();

            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }

            // ignore some of the content in META-INF/ but not all
            if (name.startsWith("META-INF/")) {
                // ignore the manifest file.
                String subName = name.substring(9);
                if ("MANIFEST.MF".equals(subName)) {
                    int count;
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while ((count = zis.read(buffer)) != -1) {
                        out.write(buffer, 0, count);
                    }
                    ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray());
                    Manifest manifest = new Manifest(swapStream);
                    mManifest.getMainAttributes().putAll(manifest.getMainAttributes());
                    continue;
                }

                // special case for Maven meta-data because we really don't care about them in apks.
                if (name.startsWith("META-INF/maven/")) {
                    continue;
                }

                // check for subfolder
                int index = subName.indexOf('/');
                if (index == -1) {
                    // no sub folder, ignores signature files.
                    if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) {
                        continue;
                    }
                }
            }

            // if we have a filter, we check the entry against it
            if (filter != null && !filter.checkEntry(name)) {
                continue;
            }

            JarEntry newEntry;

            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }

            writeEntry(zis, newEntry);

            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator.java

/**
 * @param document//  ww  w. jav  a  2s  . c o  m
 * @return
 * @throws IOException
 */
private static SignedDocumentValidator getInstanceForAsics(DSSDocument document) throws IOException {

    ZipInputStream asics = new ZipInputStream(document.openStream());

    try {

        String dataFileName = "";
        ByteArrayOutputStream dataFile = null;
        ByteArrayOutputStream signatures = null;
        ZipEntry entry;

        boolean cadesSigned = false;
        boolean xadesSigned = false;

        while ((entry = asics.getNextEntry()) != null) {
            if (entry.getName().matches(PATTERN_SIGNATURES_P7S)) {
                if (xadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                cadesSigned = true;
            } else if (entry.getName().matches(PATTERN_SIGNATURES_XML)) {
                if (cadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                xadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(MIMETYPE)) {
                ByteArrayOutputStream mimetype = new ByteArrayOutputStream();
                IOUtils.copy(asics, mimetype);
                mimetype.close();
                // Mime type implementers MAY use
                // "application/vnd.etsi.asic-s+zip" to identify this format
                // or MAY
                // maintain the original mimetype of the signed data object.
            } else if (entry.getName().indexOf("/") == -1) {
                if (dataFile == null) {

                    dataFile = new ByteArrayOutputStream();
                    IOUtils.copy(asics, dataFile);
                    dataFile.close();
                    dataFileName = entry.getName();
                } else {
                    throw new ProfileException("ASiC-S profile support only one data file");
                }
            }
        }

        if (xadesSigned) {
            ASiCXMLDocumentValidator xmlValidator = new ASiCXMLDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()), dataFile.toByteArray(), dataFileName);
            return xmlValidator;
        } else if (cadesSigned) {
            CMSDocumentValidator pdfValidator = new CMSDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()));
            pdfValidator.setExternalContent(new InMemoryDocument(dataFile.toByteArray()));
            return pdfValidator;
        } else {
            throw new RuntimeException("Is not xades nor cades signed");
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            asics.close();
        } catch (IOException e) {
        }
    }

}

From source file:org.fusesource.cloudmix.agent.jbi.JBIInstallerAgent.java

private boolean targetComponentsAvailable(Bundle bundle) {
    File jbiDescFile = null;/*from w w  w.  j  a va 2  s .  c  o  m*/
    ZipInputStream zip = null;
    try {

        URL saUrl = new URL(bundle.getUri());
        LOGGER.info("checking target components for SA bundle " + saUrl);
        zip = new ZipInputStream(SecurityUtils.getInputStream(saUrl));

        boolean foundDescriptor = false;
        ZipEntry ze = zip.getNextEntry();
        while (ze != null) {
            LOGGER.debug("Zip entry " + ze.getName());
            if (!ze.isDirectory() && ze.getName().equals(JBI_DESC_FILE_NAME)) {
                foundDescriptor = true;
                break;
            }
            ze = zip.getNextEntry();
        }

        if (!foundDescriptor) {
            LOGGER.error("cannot find JBI descriptor (" + JBI_DESC_FILE_NAME + ") in bundle " + bundle);
            return false;
        }

        jbiDescFile = File.createTempFile("jbi-agent", ".xml");
        FileOutputStream os = new FileOutputStream(jbiDescFile);
        extractZipEntry(zip, os);

        Descriptor jbiDesc = DescriptorFactory.buildDescriptor(jbiDescFile);
        ServiceAssembly sa = jbiDesc.getServiceAssembly();
        ServiceUnit[] sus = sa.getServiceUnits();

        boolean canDeploy = true;

        int max = getMaxDeployAttempts();
        for (int i = 0; i < max; i++) {
            canDeploy = true;
            for (ServiceUnit su : sus) {
                Target target = su.getTarget();
                if (!checkComponentAvailability(target.getComponentName())) {
                    LOGGER.info("cannot deploy SU " + su.getIdentification().getName() + " to component "
                            + target.getComponentName());
                    canDeploy = false;
                    break;
                } else {
                    LOGGER.info("can deploy SU " + su.getIdentification().getName() + " to component "
                            + target.getComponentName());
                }
            }
            if (!canDeploy) {
                LOGGER.warn(
                        "cannot deploy JBI bundle " + bundle + " as all target components are not available");
                int r = max - i - 1;
                if (r != 0) {
                    int t = getDeployAttemptDelay();
                    LOGGER.info(r + " attempts remaining, sleeping for " + t + " seconds");
                    sleep(t);
                }
            } else {
                break;
            }
        }
        return canDeploy;

    } catch (Exception e) {
        LOGGER.error("Got exception checking availability of target components for bundle " + bundle, e);
        return false;
    } finally {
        if (jbiDescFile != null) {
            LOGGER.info("deleting " + jbiDescFile);
            jbiDescFile.delete();
        }
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                // Complete.
            }
        }
    }
}