List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(File f, String encoding) throws IOException
From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java
/** * zip/*from w w w. j a v a 2 s .co m*/ * * @param zipFile * @param targetDirPath */ public static void upZip(File zipFile, String targetDirPath, String filenameEncoding) { if (!zipFile.exists()) return; File targetDir = FileUtil.ensureDirExists(targetDirPath); ZipFile zipfile = null; try { zipfile = new ZipFile(zipFile, filenameEncoding); ZipArchiveEntry zipEntry = null; InputStream fileIn = null; Enumeration<? extends ZipArchiveEntry> enumer = zipfile.getEntries();// zipfile.entries(); while (enumer.hasMoreElements()) { zipEntry = enumer.nextElement(); if (zipEntry.isDirectory()) { FileUtil.ensureChildDirExists(targetDir, zipEntry.getName()); } else { logger.info("unzip file" + zipEntry.getName()); fileIn = zipfile.getInputStream(zipEntry); File file2 = FileUtil.ensureFileExists(targetDirPath, zipEntry.getName()); FileUtil.copyInputStreamToFile(fileIn, file2); fileIn.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { // ignore it } } } logger.info("?"); }
From source file:com.hw.util.CompressUtils.java
private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) { ZipFile zipFile = null;/*ww w. j av a2 s .com*/ try { zipFile = new ZipFile(uncompressFile, "GBK"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); name = name.replace("\\", "/"); File currentFile = new File(descPathFile, name); //? if (currentFile.isFile() && currentFile.exists() && !override) { continue; } if (name.endsWith("/")) { currentFile.mkdirs(); continue; } else { currentFile.getParentFile().mkdirs(); } FileOutputStream fos = null; try { fos = new FileOutputStream(currentFile); InputStream is = zipFile.getInputStream(zipEntry); IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(fos); } } } catch (IOException e) { throw new RuntimeException("", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } }
From source file:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java
@SuppressWarnings("unchecked") private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) { ZipFile zipFile = null;/*from w w w . j a v a2s .c om*/ try { zipFile = new ZipFile(uncompressFile, "GBK"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); name = name.replace("\\", "/"); File currentFile = new File(descPathFile, name); //? if (currentFile.isFile() && currentFile.exists() && !override) { continue; } if (name.endsWith("/")) { currentFile.mkdirs(); continue; } else { currentFile.getParentFile().mkdirs(); } FileOutputStream fos = null; try { fos = new FileOutputStream(currentFile); InputStream is = zipFile.getInputStream(zipEntry); IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(fos); } } } catch (IOException e) { throw new RuntimeException("", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } }
From source file:com.silverpeas.util.ZipManagerTest.java
/** * Test of compressPathToZip method, of class ZipManager. * * @throws Exception//from w ww. j a v a 2s .co m */ @Test public void testCompressPathToZip() throws Exception { String path = PathTestUtil.TARGET_DIR + "test-classes" + separatorChar + "ZipSample"; String outfilename = PathTestUtil.TARGET_DIR + "temp" + separatorChar + "testCompressPathToZip.zip"; ZipManager.compressPathToZip(path, outfilename); ZipFile zipFile = new ZipFile(new File(outfilename), CharEncoding.UTF_8); try { Enumeration<? extends ZipEntry> entries = zipFile.getEntries(); assertThat(zipFile.getEncoding(), is(CharEncoding.UTF_8)); int nbEntries = 0; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); nbEntries++; } assertThat(nbEntries, is(5)); assertThat(zipFile.getEntry("ZipSample/simple.txt"), is(notNullValue())); assertThat(zipFile.getEntry("ZipSample/level1/simple.txt"), is(notNullValue())); assertThat(zipFile.getEntry("ZipSample/level1/level2b/simple.txt"), is(notNullValue())); assertThat(zipFile.getEntry("ZipSample/level1/level2a/simple.txt"), is(notNullValue())); ZipEntry accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/s\u00efmplifi\u00e9.txt"); if (accentuatedEntry == null) { accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/" + new String("smplifi.txt".getBytes("UTF-8"), Charset.defaultCharset())); } assertThat(accentuatedEntry, is(notNullValue())); assertThat(zipFile.getEntry("ZipSample/level1/level2c/"), is(nullValue())); } finally { zipFile.close(); } }
From source file:com.naryx.tagfusion.expression.function.file.ZipList.java
private cfQueryResultData performZiplist(cfSession session, File zipfile, String charset) throws IOException { ZipFile zFile = null;/*from w w w.j ava2 s . c o m*/ try { cfQueryResultData filesQuery = new cfQueryResultData(new String[] { "name", "type", "compressedsize", "size", "compressedpercent", "datelastmodified", "comment" }, "CFZIP"); zFile = new ZipFile(zipfile, charset); List<Map<String, cfData>> allResultRows = new ArrayList<Map<String, cfData>>(); Map<String, cfData> resultRow; Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries(); ZipArchiveEntry nextEntry = null; long size; double compressed; while (files.hasMoreElements()) { nextEntry = (ZipArchiveEntry) files.nextElement(); resultRow = new FastMap<String, cfData>(8); resultRow.put("name", new cfStringData(nextEntry.getName())); resultRow.put("comment", new cfStringData(nextEntry.getComment())); resultRow.put("datelastmodified", new cfDateData(nextEntry.getTime())); if (nextEntry.isDirectory()) { resultRow.put("compressedsize", new cfNumberData(0)); resultRow.put("size", new cfNumberData(0)); resultRow.put("type", new cfStringData("Dir")); resultRow.put("compressedpercent", new cfNumberData(0)); } else { size = nextEntry.getSize(); resultRow.put("compressedsize", new cfStringData(String.valueOf(nextEntry.getCompressedSize()))); resultRow.put("size", new cfStringData(String.valueOf(size))); resultRow.put("type", new cfStringData("File")); if (size != 0) { compressed = ((float) nextEntry.getCompressedSize() / (float) size); resultRow.put("compressedpercent", new cfStringData(String.valueOf(100 - (int) (compressed * 100)))); } else { resultRow.put("compressedpercent", new cfStringData("0")); } } allResultRows.add(resultRow); } filesQuery.populateQuery(allResultRows); return filesQuery; } finally { try { zFile.close(); } catch (IOException ignored) { } } }
From source file:info.magnolia.ui.framework.command.ImportZipCommand.java
@Override public boolean execute(Context context) throws Exception { this.context = context; File tmpFile = null;//from w w w . j a v a 2 s . c om FileOutputStream tmpStream = null; try { tmpFile = File.createTempFile(ZIP_TMP_FILE_PREFIX, ZIP_TMP_FILE_SUFFIX); tmpStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, tmpStream); } catch (IOException e) { log.error("Failed to dump zip file to temp file: ", e); throw e; } finally { IOUtils.closeQuietly(tmpStream); IOUtils.closeQuietly(inputStream); } if (isValid(tmpFile)) { ZipFile zip = new ZipFile(tmpFile, getEncoding()); // We use the ant-1.6.5 zip package to workaround encoding issues of the sun implementation (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499) // For some reason, entries are not in the opposite order as how they appear in most tools - reversing here. // Note that java.util.zip does not show this behaviour, and ant-1.7.1 seems to enumerate entries in alphabetical or random order. // Another alternative might be http://truezip.dev.java.net final List zipEntries = EnumerationUtils.toList(zip.getEntries()); Collections.sort(zipEntries, new Comparator() { @Override public int compare(Object first, Object second) { ZipArchiveEntry firstEntry = ((ZipArchiveEntry) first); ZipArchiveEntry secondEntry = ((ZipArchiveEntry) second); if (firstEntry.isDirectory() != secondEntry.isDirectory()) { // order folders first return Boolean.compare(secondEntry.isDirectory(), firstEntry.isDirectory()); } // order alphabetically return firstEntry.getName().compareTo(secondEntry.getName()); } }); final Iterator it = zipEntries.iterator(); while (it.hasNext()) { ZipArchiveEntry entry = (ZipArchiveEntry) it.next(); processEntry(zip, entry); } context.getJCRSession(getRepository()).save(); } return false; }
From source file:com.naryx.tagfusion.expression.function.file.Unzip.java
private void performUnzip(cfSession _session, File _zipfile, File _destination, String charset, boolean _flatten, boolean overwrite) throws cfmRunTimeException { ZipFile zFile = null;/*from w w w .j a v a 2 s. com*/ try { zFile = new ZipFile(_zipfile, charset); } catch (IOException ze) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } BufferedInputStream in = null; InputStream zIn = null; FileOutputStream fout = null; File nextFile = null; String destinationFilename; byte[] buffer = new byte[4096]; int read; try { Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries(); if (files == null) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } ZipArchiveEntry nextEntry; // while unzip stuff goes here while (files.hasMoreElements()) { nextEntry = files.nextElement(); destinationFilename = nextEntry.getName(); File checkFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); if (checkFile.exists() && !overwrite) { throwException(_session, "File already exist"); } else { if (!nextEntry.isDirectory()) { if (_flatten) { int pathEnd = destinationFilename.lastIndexOf('/'); if (pathEnd != -1) destinationFilename = destinationFilename.substring(pathEnd + 1); } nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { } // use original nextFile if getCanonicalFile() fails File parent = nextFile.getParentFile(); if (parent != null) { parent.mkdirs(); // create the parent directory structure if needed } try { zIn = zFile.getInputStream(nextEntry); in = new BufferedInputStream(zIn); fout = new FileOutputStream(nextFile, false); while ((read = in.read(buffer)) != -1) { fout.write(buffer, 0, read); } fout.flush(); } catch (IOException ioe) { throwException(_session, "Failed to extract entry [" + nextEntry.getName() + "] from zip file to " + nextFile.getAbsolutePath() + ". Check the permissions are suitable to allow this file to be written."); } finally { StreamUtil.closeStream(in); StreamUtil.closeStream(zIn); StreamUtil.closeStream(fout); } } else if (!_flatten) { destinationFilename = nextEntry.getName(); nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { // use original nextFile if getCanonicalFile() fails } nextFile.mkdirs(); } } } } finally { try { zFile.close(); } catch (IOException ignored) { } } }
From source file:com.fujitsu.dc.core.bar.BarFileInstaller.java
/** * bar?????./*from w w w . j a v a2 s . c om*/ * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryNames.toString()); } return entryCount; } catch (DcCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw DcCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (DcCoreException e) { throw e; } catch (RuntimeException e) { throw DcCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:io.personium.core.bar.BarFileInstaller.java
/** * bar?????./*from ww w . ja v a 2s . c o m*/ * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES .params(entryNames.toString()); } return entryCount; } catch (PersoniumCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (PersoniumCoreException e) { throw e; } catch (RuntimeException e) { throw PersoniumCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java
/** * Reads in a DigiDoc file. One of fname or isSdoc must be given. * @param fname signed doc filename// w ww. j av a 2 s. c o m * @param isSdoc opened stream with DigiDoc data * The user must open and close it. * @param errs list of errors to fill with parsing errors. If given * then attempt is made to continue parsing on errors and return them in this list. * If not given (null) then the first error found will be thrown. * @return signed document object if successfully parsed */ private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs) throws DigiDocException { // Use an instance of ourselves as the SAX event handler SAXDigiDocFactory handler = this; m_errs = errs; DigiDocVerifyFactory.initProvider(); SAXParserFactory factory = SAXParserFactory.newInstance(); if (m_logger.isDebugEnabled()) m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream") + " bdoc: " + isBdoc); if (fname == null && isSdoc == null) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null); } if (fname != null) { File inFile = new File(fname); if (!inFile.canRead() || inFile.length() == 0) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null); } } ZipFile zf = null; ZipArchiveInputStream zis = null; ZipArchiveEntry ze = null; InputStream isEntry = null; File fTmp = null; try { factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); if (isBdoc) { // bdoc parsing // must be a bdoc document ? m_doc = new SignedDoc(); m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0); m_doc.setFormat(SignedDoc.FORMAT_BDOC); Enumeration eFiles = null; if (fname != null) { zf = new ZipFile(fname, "UTF-8"); eFiles = zf.getEntries(); } else if (isSdoc != null) { zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true); } ArrayList lSigFnames = new ArrayList(); ArrayList lDataFnames = new ArrayList(); // read all entries boolean bHasMimetype = false, bManifest1 = false; int nFil = 0; while ((zf != null && eFiles.hasMoreElements()) || (zis != null && ((ze = zis.getNextZipEntry()) != null))) { nFil++; // read entry if (zf != null) { // ZipFile ze = (ZipArchiveEntry) eFiles.nextElement(); isEntry = zf.getInputStream(ze); } else { // ZipArchiveInputStream int n = 0, nTot = 0; if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST) || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml"))) || (nMaxBdocFilCached <= 0 || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { bos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip"); data = bos.toByteArray(); bos = null; isEntry = new ByteArrayInputStream(data); } else { File fCacheDir = new File(ConfigManager.instance().getStringProperty( "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir"))); fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir); FileOutputStream fos = new FileOutputStream(fTmp); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { fos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath()); fos.close(); isEntry = new FileInputStream(fTmp); } } if (m_logger.isDebugEnabled()) m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: " + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: " + ze.getCompressedSize()); // mimetype file if (ze.getName().equals(FILE_MIMETYPE)) { if (m_logger.isDebugEnabled()) m_logger.debug("Check mimetype!"); checkBdocMimetype(isEntry); bHasMimetype = true; m_doc.setComment(ze.getComment()); if (nFil != 1) { m_logger.error("mimetype file is " + nFil + " file but must be first"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "mimetype file is not first zip entry", null)); } } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file if (m_logger.isDebugEnabled()) m_logger.debug("Read manifest"); if (!bManifest1 && isEntry != null) { bManifest1 = true; BdocManifestParser mfparser = new BdocManifestParser(m_doc); mfparser.readManifest(isEntry); } else { m_logger.error("Found multiple manifest.xml files!"); throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES, "Found multiple manifest.xml files!", null); } } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature m_fileName = ze.getName(); if (m_logger.isDebugEnabled()) m_logger.debug("Reading bdoc siganture: " + m_fileName); boolean bExists = false; for (int j = 0; j < lSigFnames.size(); j++) { String s1 = (String) lSigFnames.get(j); if (s1.equals(m_fileName)) bExists = true; } if (bExists) { m_logger.error("Duplicate signature filename: " + m_fileName); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate signature filename: " + m_fileName, null)); } else lSigFnames.add(m_fileName); SAXParser saxParser = factory.newSAXParser(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int n = 0; byte[] data = new byte[2048]; while ((n = isEntry.read(data)) > 0) bos.write(data, 0, n); data = bos.toByteArray(); bos = null; if (m_logger.isDebugEnabled()) m_logger.debug( "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0)); saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this); if (m_logger.isDebugEnabled()) m_logger.debug("Parsed bdoc: " + m_fileName); Signature sig1 = m_doc.getLastSignature(); m_sigComment = ze.getComment(); if (sig1 != null) { sig1.setPath(m_fileName); sig1.setComment(ze.getComment()); } } else { // probably a data file if (m_logger.isDebugEnabled()) m_logger.debug("Read data file: " + ze.getName()); if (!ze.isDirectory()) { boolean bExists = false; for (int j = 0; j < lDataFnames.size(); j++) { String s1 = (String) lDataFnames.get(j); if (s1.equals(ze.getName())) bExists = true; } if (bExists) { m_logger.error("Duplicate datafile filename: " + ze.getName()); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate datafile filename: " + ze.getName(), null)); } else lDataFnames.add(ze.getName()); DataFile df = m_doc.findDataFileById(ze.getName()); if (df != null) { if (ze.getSize() > 0) df.setSize(ze.getSize()); df.setContentType(DataFile.CONTENT_BINARY); df.setFileName(ze.getName()); } else { df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(), "application/binary", m_doc); if (m_doc.getDataFiles() == null) m_doc.setDataFiles(new ArrayList()); m_doc.getDataFiles().add(df); //m_doc.addDataFile(df); // this does some intiailization work unnecessary here } // enable caching if requested if (isEntry != null) df.setOrCacheBodyAndCalcHashes(isEntry); df.setComment(ze.getComment()); df.setLastModDt(new Date(ze.getTime())); // fix mime type according to DataObjectFormat Signature sig1 = m_doc.getLastSignature(); if (sig1 != null) { Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df); if (dRef != null) { DataObjectFormat dof = sig1.getSignedInfo() .getDataObjectFormatForReference(dRef); if (dof != null) { df.setMimeType(dof.getMimeType()); } } } } } if (fTmp != null) { fTmp.delete(); fTmp = null; } } // while zip entries if (!bHasMimetype) { m_logger.error("No mimetype file"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Not a BDOC format file! No mimetype file!", null)); } // if no signatures exist then copy mime-type from manifest.xml to DataFile -s if (m_doc.countSignatures() == 0) { for (int i = 0; i < m_doc.countDataFiles(); i++) { DataFile df = m_doc.getDataFile(i); if (m_doc.getManifest() != null) { for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) { ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j); if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) { df.setMimeType(mfe.getMediaType()); } // if fullpath } // for } // if } // for i } } else { // ddoc parsing if (m_logger.isDebugEnabled()) m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName); m_fileName = fname; SAXParser saxParser = factory.newSAXParser(); if (fname != null) saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this); else if (isSdoc != null) saxParser.parse(isSdoc, this); } } catch (org.xml.sax.SAXParseException ex) { m_logger.error("SAX Error: " + ex); handleError(ex); } catch (Exception ex) { m_logger.error("Error reading3: " + ex); ex.printStackTrace(); /*if(ex instanceof DigiDocException){ DigiDocException dex = (DigiDocException)ex; m_logger.error("Dex: " + ex); if(dex.getNestedException() != null) { dex.getNestedException().printStackTrace(); m_logger.error("Trace: "); } }*/ handleError(ex); } finally { // cleanup try { if (isEntry != null) { isEntry.close(); isEntry = null; } if (zis != null) zis.close(); if (zf != null) zf.close(); if (fTmp != null) { fTmp.delete(); fTmp = null; } } catch (Exception ex) { m_logger.error("Error closing streams and files: " + ex); } } // compare Manifest and DataFiles boolean bErrList = (errs != null); if (errs == null) errs = new ArrayList(); boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs); if (m_doc == null) { m_logger.error("Error reading4: doc == null"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "This document is not in ddoc or bdoc format", null)); } if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once DigiDocException ex = (DigiDocException) errs.get(0); throw ex; } return m_doc; }