List of usage examples for java.util.zip ZipOutputStream closeEntry
public void closeEntry() throws IOException
From source file:cross.io.misc.WorkflowZipper.java
private void addZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer, final File file, final HashSet<String> zipEntries) throws IOException { log.debug("Adding zip entry for file {}", file); if (file.exists() && file.isFile()) { // Use the file name for the ZipEntry name. final ZipEntry zip_entry = new ZipEntry(file.getName()); if (zipEntries.contains(file.getName())) { log.info("Skipping duplicate zip entry {}", file.getName()); return; } else {// w w w. ja v a 2s .c o m zipEntries.add(file.getName()); } zos.putNextEntry(zip_entry); // Create a buffered input stream from the file stream. final FileInputStream in = new FileInputStream(file); // Read from source into buffer and write, thereby compressing // on the fly try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) { // Read from source into buffer and write, thereby compressing // on the fly int len = 0; while ((len = source.read(input_buffer, 0, bufsize)) != -1) { zos.write(input_buffer, 0, len); } zos.flush(); } zos.closeEntry(); } else { log.warn("Skipping nonexistant file or directory {}", file); } }
From source file:com.flexive.core.storage.GenericDivisionExporter.java
/** * Dump a single file to a zip output stream * * @param zip zip output stream/*from w ww . j a va2s . co m*/ * @param file the file to dump * @param path absolute base directory path (will be stripped in the archive from file) * @throws IOException on errors */ private void dumpFile(ZipOutputStream zip, File file, String path) throws IOException { if (file.isDirectory()) { for (File f : file.listFiles()) dumpFile(zip, f, path); return; } ZipEntry ze = new ZipEntry(FOLDER_FS_BINARY + file.getAbsolutePath().substring(path.length())); zip.putNextEntry(ze); FileInputStream fis = null; try { fis = new FileInputStream(file); byte[] buffer = new byte[4096]; int read; while ((read = fis.read(buffer)) != -1) zip.write(buffer, 0, read); } finally { if (fis != null) fis.close(); } zip.closeEntry(); zip.flush(); }
From source file:cross.io.misc.WorkflowZipper.java
private void addRelativeZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer, final String relativePath, final File file, final HashSet<String> zipEntries) throws IOException { log.debug("Adding zip entry for file {}", file); if (file.exists() && file.isFile()) { // Use the file name for the ZipEntry name. final ZipEntry zip_entry = new ZipEntry(relativePath); if (zipEntries.contains(relativePath)) { log.info("Skipping duplicate zip entry {}", relativePath + "/" + file.getName()); return; } else {/*w w w .j a v a 2 s .c om*/ zipEntries.add(relativePath); } zos.putNextEntry(zip_entry); // Create a buffered input stream from the file stream. final FileInputStream in = new FileInputStream(file); // Read from source into buffer and write, thereby compressing // on the fly try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) { // Read from source into buffer and write, thereby compressing // on the fly int len = 0; while ((len = source.read(input_buffer, 0, bufsize)) != -1) { zos.write(input_buffer, 0, len); } zos.flush(); } zos.closeEntry(); } else { log.warn("Skipping nonexistant file or directory {}", file); } }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Publishes a object to the ldap directory. * * @param conn a Ldap connection//from w w w . ja v a 2s . co m * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to publish cert * (null if LDAP publishing is not enabled) * @param object object to publish * (java.security.cert.X509Certificate or, * java.security.cert.X509CRL) */ public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: publish"); try { if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); String name = mDir + File.separator + "cert-" + sno.toString(); if (mDerAttr) { FileOutputStream fos = null; try { String fileName = name + ".der"; fos = new FileOutputStream(fileName); fos.write(cert.getEncoded()); } finally { if (fos != null) fos.close(); } } if (mB64Attr) { String fileName = name + ".b64"; PrintStream ps = null; Base64OutputStream b64 = null; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output))); b64.write(cert.getEncoded()); b64.flush(); ps = new PrintStream(fos); ps.print(output.toString("8859_1")); } finally { if (ps != null) { ps.close(); } if (b64 != null) { b64.close(); } if (fos != null) fos.close(); } } } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); String baseName = mDir + File.separator + namePrefix[0]; String tempFile = baseName + ".temp"; ZipOutputStream zos = null; byte[] encodedArray = null; File destFile = null; String destName = null; File renameFile = null; if (mDerAttr) { FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); encodedArray = crl.getEncoded(); fos.write(encodedArray); } finally { if (fos != null) fos.close(); } if (mZipCRL) { try { zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip")); zos.setLevel(mZipLevel); zos.putNextEntry(new ZipEntry(baseName + ".der")); zos.write(encodedArray, 0, encodedArray.length); zos.closeEntry(); } finally { if (zos != null) zos.close(); } } destName = baseName + ".der"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); if (mLatestCRL) { String linkExt = "."; if (mLinkExt != null && mLinkExt.length() > 0) { linkExt += mLinkExt; } else { linkExt += "der"; } String linkName = mDir + File.separator + namePrefix[1] + linkExt; createLink(linkName, destName); if (mZipCRL) { linkName = mDir + File.separator + namePrefix[1] + ".zip"; createLink(linkName, baseName + ".zip"); } } } // output base64 file if (mB64Attr == true) { if (encodedArray == null) encodedArray = crl.getEncoded(); FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); fos.write(Utils.base64encode(encodedArray, true).getBytes()); } finally { if (fos != null) fos.close(); } destName = baseName + ".b64"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); } purgeExpiredFiles(); purgeExcessFiles(); } } catch (IOException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CertificateEncodingException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CRLException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } }
From source file:com.flexive.core.storage.GenericDivisionExporter.java
/** * Dump a generic table to XML/* w ww. j ava2 s. com*/ * * @param tableName name of the table * @param stmt an open statement * @param out output stream * @param sb an available and valid StringBuilder * @param xmlTag name of the xml tag to write per row * @param idColumn (optional) id column to sort results * @param onlyBinaries process binary fields (else these will be ignored) * @throws SQLException on errors * @throws IOException on errors */ private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag, String idColumn, boolean onlyBinaries) throws SQLException, IOException { ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC")); final ResultSetMetaData md = rs.getMetaData(); String value, att; boolean hasSubTags; while (rs.next()) { hasSubTags = false; if (!onlyBinaries) { sb.setLength(0); sb.append(" <").append(xmlTag); } for (int i = 1; i <= md.getColumnCount(); i++) { value = null; att = md.getColumnName(i).toLowerCase(); switch (md.getColumnType(i)) { case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: case java.sql.Types.BIGINT: if (!onlyBinaries) { value = String.valueOf(rs.getBigDecimal(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: if (!onlyBinaries) { value = String.valueOf(rs.getLong(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (!onlyBinaries) { value = String.valueOf(rs.getDouble(i)); if (rs.wasNull()) value = null; } break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (!onlyBinaries) { final Timestamp ts = rs.getTimestamp(i); if (rs.wasNull()) value = null; else value = FxFormatUtils.getDateTimeFormat().format(ts); } break; case java.sql.Types.BIT: case java.sql.Types.CHAR: case java.sql.Types.BOOLEAN: if (!onlyBinaries) { value = rs.getBoolean(i) ? "1" : "0"; if (rs.wasNull()) value = null; } break; case java.sql.Types.CLOB: case java.sql.Types.BLOB: case java.sql.Types.LONGVARBINARY: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARBINARY: case java.sql.Types.VARCHAR: case java.sql.Types.BINARY: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: hasSubTags = true; break; default: LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]"); } if (value != null && !onlyBinaries) sb.append(' ').append(att).append("=\"").append(value).append("\""); } if (hasSubTags) { if (!onlyBinaries) sb.append(">\n"); for (int i = 1; i <= md.getColumnCount(); i++) { switch (md.getColumnType(i)) { case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: case java.sql.Types.BLOB: case java.sql.Types.BINARY: if (idColumn == null) throw new IllegalArgumentException("Id column required to process binaries!"); String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i + ".blob"; att = md.getColumnName(i).toLowerCase(); if (onlyBinaries) { if (!(out instanceof ZipOutputStream)) throw new IllegalArgumentException( "out has to be a ZipOutputStream to store binaries!"); ZipOutputStream zip = (ZipOutputStream) out; InputStream in = rs.getBinaryStream(i); if (rs.wasNull()) break; ZipEntry ze = new ZipEntry(binFile); zip.putNextEntry(ze); byte[] buffer = new byte[4096]; int read; while ((read = in.read(buffer)) != -1) zip.write(buffer, 0, read); in.close(); zip.closeEntry(); zip.flush(); } else { InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty if (rs.wasNull()) break; in.close(); sb.append(" <").append(att).append(">").append(binFile).append("</").append(att) .append(">\n"); } break; case java.sql.Types.CLOB: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARCHAR: if (!onlyBinaries) { value = rs.getString(i); if (rs.wasNull()) break; att = md.getColumnName(i).toLowerCase(); sb.append(" <").append(att).append('>'); escape(sb, value); sb.append("</").append(att).append(">\n"); } break; } } if (!onlyBinaries) sb.append(" </").append(xmlTag).append(">\n"); } else { if (!onlyBinaries) sb.append("/>\n"); } if (!onlyBinaries) write(out, sb); } }
From source file:com.cdd.bao.importer.ImportControlledVocab.java
private void writeMappedAssays() throws IOException { File f = new File(dstFN); Util.writeln("Writing to: " + f.getCanonicalPath()); ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f)); for (int n = 0; n < srcRows.length(); n++) { JSONObject json = null;//from w w w . ja v a 2 s.c o m try { json = map.createAssay(srcRows.getJSONObject(n), schema, treeCache); } catch (Exception ex) { zip.close(); throw new IOException("Failed to translate assay at row #" + (n + 1), ex); } if (!json.has("uniqueID")) { Util.writeln("** Row#" + (n + 1) + " is missing an identifier: cannot proceed."); break; } String fn = "assay_" + (n + 1) + "_"; for (char ch : json.getString("uniqueID").toCharArray()) { if (ch == ' ') fn += ' '; else if (ch == '_' || ch == ':' || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) fn += ch; else fn += '-'; } zip.putNextEntry(new ZipEntry(fn + ".json")); zip.write(json.toString(2).getBytes()); zip.closeEntry(); } zip.close(); }
From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRGraphServiceImpl.java
private void addZipEntry(RConnection c, ZipOutputStream zout, String inputFileName, String outputFileName) throws IOException { RFileInputStream tmpin = c.openFile(inputFileName); byte[] dataBuffer = new byte[8192]; int i = 0;/*ww w .j av a2 s .com*/ ZipEntry e = new ZipEntry(outputFileName); zout.putNextEntry(e); while ((i = tmpin.read(dataBuffer)) > 0) { zout.write(dataBuffer, 0, i); zout.flush(); } tmpin.close(); zout.closeEntry(); }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private File removeDuplicatesFromJar(File in, List<String> duplicates) { String target = projectOutputDirectory.getAbsolutePath(); File tmp = new File(target, "unpacked-embedded-jars"); tmp.mkdirs();// ww w . j a v a 2s .c om File out = new File(tmp, in.getName()); if (out.exists()) { return out; } else { try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // Create a new Jar file final FileOutputStream fos; final ZipOutputStream jos; try { fos = new FileOutputStream(out); jos = new ZipOutputStream(fos); } catch (FileNotFoundException e1) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found"); return null; } final ZipFile inZip; try { inZip = new ZipFile(in); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if (!duplicates.contains(entry.getName())) { // copy the entry header to jos jos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, jos); currIn.close(); jos.closeEntry(); } } } catch (IOException e) { getLog().error("Cannot removing duplicates : " + e.getMessage()); return null; } try { inZip.close(); jos.close(); fos.close(); } catch (IOException e) { // ignore it. } getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath()); return out; }
From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java
private void copyUnknownFiles(File appDir, ZipOutputStream outputFile, Map<String, String> files) throws IOException { String UNK_DIRNAME = getUNK_DIRNAME(); File unknownFileDir = new File(appDir, UNK_DIRNAME); // loop through unknown files for (Map.Entry<String, String> unknownFileInfo : files.entrySet()) { File inputFile = new File(unknownFileDir, unknownFileInfo.getKey()); if (inputFile.isDirectory()) { continue; }/* w w w . j a va2s . com*/ ZipEntry newEntry = new ZipEntry(unknownFileInfo.getKey()); int method = Integer.valueOf(unknownFileInfo.getValue()); LogHelper.fine( String.format("Copying unknown file %s with method %d", unknownFileInfo.getKey(), method)); if (method == ZipEntry.STORED) { newEntry.setMethod(ZipEntry.STORED); newEntry.setSize(inputFile.length()); newEntry.setCompressedSize(-1); BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(inputFile)); CRC32 crc = calculateCrc(unknownFile); newEntry.setCrc(crc.getValue()); // LogHelper.getLogger().fine("\tsize: " + newEntry.getSize()); } else { newEntry.setMethod(ZipEntry.DEFLATED); } outputFile.putNextEntry(newEntry); BrutIO.copy(inputFile, outputFile); outputFile.closeEntry(); } }