Example usage for java.util.zip ZipOutputStream write

List of usage examples for java.util.zip ZipOutputStream write

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Add rendered document to ZIP stream./*from  w w w  .  j a va  2 s.  c  o  m*/
 * 
 * @param pageName the name (used with {@link com.xpn.xwiki.XWiki#getDocument(String, XWikiContext)}) of the page to
 *            render.
 * @param zos the ZIP output stream.
 * @param context the XWiki context.
 * @param vcontext the Velocity context.
 * @throws XWikiException error when rendering document.
 * @throws IOException error when rendering document.
 */
private void renderDocument(String pageName, ZipOutputStream zos, XWikiContext context,
        VelocityContext vcontext) throws XWikiException, IOException {
    @SuppressWarnings("unchecked")
    EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.class);
    DocumentReference docReference = new DocumentReference(resolver.resolve(pageName, EntityType.DOCUMENT));
    XWikiDocument doc = context.getWiki().getDocument(docReference, context);

    String zipname = doc.getDocumentReference().getWikiReference().getName();
    for (EntityReference space : doc.getDocumentReference().getSpaceReferences()) {
        zipname += POINT + space.getName();
    }
    zipname += POINT + doc.getDocumentReference().getName();
    String language = doc.getLanguage();
    if (language != null && language.length() != 0) {
        zipname += POINT + language;
    }

    zipname += ".html";

    ZipEntry zipentry = new ZipEntry(zipname);
    zos.putNextEntry(zipentry);

    String originalDatabase = context.getDatabase();
    try {
        context.setDatabase(doc.getDocumentReference().getWikiReference().getName());
        context.setDoc(doc);
        vcontext.put(VCONTEXT_DOC, doc.newDocument(context));
        vcontext.put(VCONTEXT_CDOC, vcontext.get(VCONTEXT_DOC));

        XWikiDocument tdoc = doc.getTranslatedDocument(context);
        context.put(CONTEXT_TDOC, tdoc);
        vcontext.put(VCONTEXT_TDOC, tdoc.newDocument(context));

        String content = context.getWiki().evaluateTemplate("view.vm", context);

        zos.write(content.getBytes(context.getWiki().getEncoding()));
        zos.closeEntry();
    } finally {
        context.setDatabase(originalDatabase);
    }
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected void doUpload() {
    DbAdapter dba = new DbAdapter(this);
    dba.open();/*ww  w  .  j ava  2s  .  c  o m*/
    Cursor allLogs = dba.fetchAll();
    StringBuilder sb = new StringBuilder();
    allLogs.moveToFirst();
    sb.append("DateTime");
    sb.append(",");
    sb.append("Process");
    sb.append(",");
    sb.append("Type");
    sb.append(",");
    sb.append("Component");
    sb.append(",");
    sb.append("ActionString");
    sb.append(",");
    sb.append("Category");
    sb.append("\n");
    while (!allLogs.isAfterLast()) {
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4)));
        sb.append("\n");
        allLogs.moveToNext();
    }
    dba.close();
    File appDir = getDir("toUpload", MODE_PRIVATE);
    UUID uuid;
    uuid = MainScreen.getOrCreateUUID(this);
    long time = System.currentTimeMillis();
    String basename = uuid.toString() + "_AT_" + time;
    String filename = basename + ".zip.enc";
    File file = new File(appDir, filename);
    FileOutputStream out = null;
    ZipOutputStream outzip = null;
    CipherOutputStream outcipher = null;
    Cipher datac = null;

    File keyfile = new File(appDir, basename + ".key.enc");
    //Log.i("sb length", Integer.toString(sb.length()));
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String email = prefs.getString(MainScreen.EMAIL_KEY, "");
    String emailFilename = "email.txt";
    String csvFilename = "mouflon_log_" + time + ".csv";
    try {
        SecretKey aeskey = generateAESKey();
        //Log.i("secret key", bytearrToString(aeskey.getEncoded()));
        encryptAndWriteAESKey(aeskey, keyfile);
        datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        byte[] ivbytes = genIV();
        IvParameterSpec iv = new IvParameterSpec(ivbytes);
        datac.init(Cipher.ENCRYPT_MODE, aeskey, iv);
        out = new FileOutputStream(file);
        out.write(ivbytes);
        //Log.i("iv bytes", bytearrToString(ivbytes));
        outcipher = new CipherOutputStream(out, datac);
        outzip = new ZipOutputStream(outcipher);
        outzip.setMethod(ZipOutputStream.DEFLATED);
        //write the first file (e-mail address)
        String androidVersion = android.os.Build.VERSION.RELEASE;
        String deviceName = android.os.Build.MODEL;
        ZipEntry infoEntry = new ZipEntry("info.txt");
        outzip.putNextEntry(infoEntry);
        outzip.write((androidVersion + "\n" + deviceName).getBytes());
        outzip.closeEntry();
        ZipEntry emailEntry = new ZipEntry(emailFilename);
        outzip.putNextEntry(emailEntry);
        outzip.write(email.getBytes());
        outzip.closeEntry();
        ZipEntry csvEntry = new ZipEntry(csvFilename);
        outzip.putNextEntry(csvEntry);
        outzip.write(sb.toString().getBytes());
        outzip.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outzip.close();
            outcipher.close();
            out.close();
        } catch (IOException e) {
            //ignore
        } catch (NullPointerException ne) {
            //ignore
        }
    }
    //here we actually upload the files 
    String containerFilename = basename + "_container.zip";
    File containerFile = new File(appDir, containerFilename);
    zipUp(containerFile, new File[] { file, keyfile });
    boolean success = uploadFile(containerFile);
    containerFile.delete();
    file.delete();
    keyfile.delete();
    if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) {
        DbAdapter dba2 = new DbAdapter(this);
        dba2.open();
        dba2.clearDB();
        dba2.close();
    }
    if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) {
        Editor e = prefs.edit();
        e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails
        e.commit();
    }
    String s = success ? "Upload complete. Thanks!" : "Upload Failed";
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this)
            .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s)
            .setAutoCancel(true).setOngoing(false);

    if (mManual) { //only show a notification if we manually upload the file.
        Intent toLaunch = new Intent(UploadFile.this, MainScreen.class);
        //The notification has to go somewhere.
        PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, mBuilder.build());
    }
    stopSelf();
}

From source file:org.csml.tommo.sugar.modules.QualityHeatMapsPerTileAndBase.java

private void writeCSVFile(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration, ResultsTableModel model) throws IOException {

    String flowCell = laneCoordinates.getFlowCell();
    Integer lane = laneCoordinates.getLane();

    ZipOutputStream zip = report.zipFile();

    Double[][] result = new Double[model.getRowCount()][model.getColumnCount()];

    for (int r = 0; r < model.getRowCount(); r++) {
        int bp = model.getBasePosition(r);

        for (int c = 0; c < model.getColumnCount(); c++) {
            TileBPCoordinates tileBPCoordinate = model.getCoordinateAt(r, c);
            MeanQualityMatrix matrix = getMeanQualityMatrix(tileBPCoordinate);

            if (matrix != null) {
                result[r][c] = matrix.getMeanRatio();
            } else {
                result[r][c] = -1.0;/*from w  w w .  ja  va2  s .  c om*/
            }

        }
    }

    String csvFileName = "mean_lowq_reads_ratio_" + flowCell + "_" + lane + ".txt";
    zip.putNextEntry(new ZipEntry(report.folderName() + "/" + csvFileName));

    String LINE_SEPARATOR = System.getProperty("line.separator");
    String COLUMN_SEPARATOR = "\t";

    // write column header
    for (int c = 0; c < model.getColumnCount(); c++) {

        if (c == 0) {
            String s = "Tiles:" + COLUMN_SEPARATOR;
            zip.write(s.getBytes());
        }

        String s = model.getTile(c) + COLUMN_SEPARATOR;
        zip.write(s.getBytes());
    }

    zip.write(LINE_SEPARATOR.getBytes());

    for (int r = 0; r < result.length; r++) {
        String s = model.getBasePosition(r) + COLUMN_SEPARATOR;
        zip.write(s.getBytes());

        for (int c = 0; c < model.getColumnCount(); c++) {
            s = result[r][c].toString() + COLUMN_SEPARATOR;
            zip.write(s.getBytes());
        }

        zip.write(LINE_SEPARATOR.getBytes());

    }

}

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

/**
 * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal
 * the specified {@code newSequencePath}. Works by creating a temp file and renaming
 *
 * @param targetFile      A .genome file, in zip format
 * @param newSequencePath/*from w  ww .ja va2  s .  c  o  m*/
 * @return boolean indicating success or failure.
 * @throws IOException
 */
static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException {

    ZipFile targetZipFile = new ZipFile(targetFile);
    boolean success = false;

    File tmpZipFile = File.createTempFile("tmpGenome", ".zip");
    ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);

    InputStream propertyInputStream = null;
    ZipOutputStream zipOutputStream = null;
    Properties inputProperties = new Properties();

    try {
        propertyInputStream = targetZipFile.getInputStream(propEntry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream));

        //Copy over property.txt, only replacing a few properties
        inputProperties.load(reader);
        inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath);
        inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString());

        ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
        PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));

        inputProperties.store(propertyFileWriter, null);

        propertyFileWriter.flush();
        byte[] newPropertyBytes = propertyBytes.toByteArray();

        Enumeration<? extends ZipEntry> entries = targetZipFile.entries();
        zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile));
        while (entries.hasMoreElements()) {
            ZipEntry curEntry = entries.nextElement();
            ZipEntry writeEntry = null;

            if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                writeEntry.setSize(newPropertyBytes.length);
                zipOutputStream.putNextEntry(writeEntry);
                zipOutputStream.write(newPropertyBytes);
                continue;
            } else {
                //Because the compressed size can vary,
                //we generate a new ZipEntry and copy some attributes
                writeEntry = new ZipEntry(curEntry.getName());
                writeEntry.setSize(curEntry.getSize());
                writeEntry.setComment(curEntry.getComment());
                writeEntry.setTime(curEntry.getTime());
            }

            zipOutputStream.putNextEntry(writeEntry);
            InputStream tmpIS = null;
            try {
                tmpIS = targetZipFile.getInputStream(writeEntry);
                int bytes = IOUtils.copy(tmpIS, zipOutputStream);
                log.debug(bytes + " bytes written to " + targetFile);
            } finally {
                if (tmpIS != null)
                    tmpIS.close();
            }

        }
    } catch (Exception e) {
        tmpZipFile.delete();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (propertyInputStream != null)
            propertyInputStream.close();
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.finish();
            zipOutputStream.close();
        }
        zipOutputStream = null;
        System.gc();
        success = true;
    }

    //This is a hack. I don't know why it's necessary,
    //but for some reason the output zip file seems to be corrupt
    //at least when called from GenomeManager.refreshArchive
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        //
    }

    //Rename tmp file
    if (success) {
        targetFile.delete();
        FileUtils.copyFile(tmpZipFile, targetFile);
        success = targetFile.exists();
        tmpZipFile.delete();
    }
    return success;
}

From source file:mergedoc.core.MergeManager.java

/**
 * ????Java ???/*from   w  w  w . ja v a  2s .co m*/
 * API ???????????? ZIP
 * ??????
 *
 * @param  in  
 * @param  out ZIP 
 * @throws MergeDocException ??????
 * @throws SAXException SAX ????
 * @throws IOException ????
 */
private void merge(ArchiveInputStream in, ZipOutputStream out)
        throws MergeDocException, SAXException, IOException {
    Merger merger = new Merger(pref.getDocDirectory());
    merger.setDocEncoding(pref.getDocEncoding());

    ArchiveInputStream.Entry inEntry = null;
    while ((inEntry = in.getNextEntry()) != null) {

        if (workingState.isCanceled()) {
            return;
        }
        String entryName = inEntry.getName();
        out.putNextEntry(new ZipEntry(entryName));
        workingState.changeWorkingText(entryName);

        //debug ?
        //if (!entryName.equals("java/lang/String.java")) continue;
        //if (!entryName.endsWith("/SuppressWarnings.java")) continue;
        //if (!entryName.endsWith("/System.java")) continue;

        if (entryName.endsWith(".java") && !entryName.endsWith("/package-info.java")) {

            // Java ??
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copyStream(in, baos);
            String source = baos.toString(pref.getInputEncoding());
            source = FastStringUtils.optimizeLineSeparator(source);
            source = FastStringUtils.untabify(source);

            // Java  API ?
            Pattern classPat = PatternCache.getPattern(".*/(.*)\\.java");
            Matcher classMat = classPat.matcher(entryName);
            if (classMat.find()) {
                String result = merger.merge(source, classMat.group(1));
                String className = merger.getMergedClassName();
                if (className != null) {
                    result = doFilter(className, result);
                }
                byte[] resultBuf = result.getBytes(pref.getOutputEncoding());
                out.write(resultBuf);
            } else {
                copyStream(in, out);
            }
        } else {
            // Java ??
            copyStream(in, out);
        }
    }
}

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

protected void exportFiles(ZipOutputStream zos, String path) throws WPBIOException {
    try {/*www. java 2s  .c om*/
        List<WPBFile> files = dataStorage.getAllRecords(WPBFile.class);
        for (WPBFile file : files) {
            String fileXmlPath = path + file.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(file, map);
            ZipEntry metadataZe = new ZipEntry(fileXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
            String contentPath = String.format(PATH_FILE_CONTENT, file.getExternalKey());
            ZipEntry contentZe = new ZipEntry(contentPath);
            zos.putNextEntry(contentZe);
            zos.closeEntry();

            if (file.getDirectoryFlag() == null || file.getDirectoryFlag() != 1) {
                try {
                    String filePath = contentPath + file.getFileName();
                    WPBFilePath cloudFile = new WPBFilePath(PUBLIC_BUCKET, file.getBlobKey());
                    InputStream is = cloudFileStorage.getFileContent(cloudFile);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    IOUtils.copy(is, bos);
                    bos.flush();
                    byte[] content = bos.toByteArray();
                    ZipEntry fileZe = new ZipEntry(filePath);
                    zos.putNextEntry(fileZe);
                    zos.write(content);
                    zos.closeEntry();
                } catch (Exception e) {
                    log.log(Level.SEVERE, " Exporting file :" + file.getExternalKey(), e);
                    // do nothing, we do not abort the export because of a failure, but we need to log this as warning
                }
            }
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export files to Zip", e);
    }
}

From source file:de.innovationgate.wga.model.WGADesignConfigurationModel.java

public void exportDesign(File file, Properties buildProperties)
        throws FileNotFoundException, PersistentKeyException, GeneralSecurityException, IOException {
    ZipOutputStream stream = createZIP(file, false, null);
    ZipEntry buildPropertiesEntry = new ZipEntry("files/system/build.properties");
    stream.putNextEntry(buildPropertiesEntry);
    ByteArrayOutputStream propertiesContent = new ByteArrayOutputStream();
    buildProperties.store(propertiesContent, null);
    stream.write(propertiesContent.toByteArray());
    stream.close();//w ww.j a v a  2  s . c o m
}

From source file:org.etudes.mneme.impl.ExportQtiServiceImpl.java

/**
 * Writes the media file from content resource to the zip package. Its important to push the security advisor before calling this method.
 * /*w  ww . jav  a  2 s  .  c om*/
 * @param zip
 *        The zip package
 * @param id
 *        resource id
 * @param fileName
 *        file name
 */
protected void writeContentResourceToZip(ZipOutputStream zip, String subFolder, String id, String fileName) {
    try {
        // Reference does not know how to make the id from a private docs reference.
        if (id.startsWith("/content/")) {
            id = id.substring("/content".length());
        }

        if (subFolder != null)
            fileName = subFolder + fileName;

        // write attachment to the zip
        id = id.replaceAll("%20", " ");
        ContentResource resource = this.contentHostingService.getResource(id);
        zip.putNextEntry(new ZipEntry(fileName));
        zip.write(resource.getContent());
        zip.closeEntry();
    } catch (Exception e) {
        M_log.warn("ExportQtiService: zipping embed or attachments: " + e.toString());
    }
}

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

public void writeSADtoZip(StructuredArtifactDefinitionBean bean, ZipOutputStream zos, String path)
        throws IOException {
    // if the path is a directory without an end slash, then add one
    if (!path.endsWith("/") && path.length() > 0) {
        path += "/";
    }//from  w w w.  j  a va2  s  .  c om
    ZipEntry definitionFile = new ZipEntry(path + "formDefinition.xml");

    zos.putNextEntry(definitionFile);
    writeSADasXMLtoStream(bean, zos);
    zos.closeEntry();

    ZipEntry schemeFile = new ZipEntry(path + "schema.xsd");

    zos.putNextEntry(schemeFile);
    zos.write(bean.getSchema());
    zos.closeEntry();

    List existingEntries = new ArrayList();
    storeFile(zos, bean.getAlternateCreateXslt(), existingEntries);
    storeFile(zos, bean.getAlternateViewXslt(), existingEntries);

}

From source file:cz.zcu.kiv.eegdatabase.logic.zip.ZipGenerator.java

public File generate(Experiment exp, MetadataCommand mc, Set<DataFile> dataFiles, byte[] licenseFile,
        String licenseFileName) throws Exception, SQLException, IOException {

    ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    File tempZipFile = null;/*from  www  .  j  a v  a 2  s  .  c  o m*/

    try {
        log.debug("creating output stream");
        // create temp zip file
        tempZipFile = File.createTempFile("experimentDownload_", ".zip");
        // open stream to temp zip file
        fileOutputStream = new FileOutputStream(tempZipFile);
        // prepare zip stream
        zipOutputStream = new ZipOutputStream(fileOutputStream);

        log.debug("transforming metadata from database to xml file");
        OutputStream meta = getTransformer().transformElasticToXml(exp);
        Scenario scen = exp.getScenario();
        log.debug("getting scenario file");

        byte[] xmlMetadata = null;
        if (meta instanceof ByteArrayOutputStream) {
            xmlMetadata = ((ByteArrayOutputStream) meta).toByteArray();
        }

        ZipEntry entry;

        if (licenseFileName != null && !licenseFileName.isEmpty()) {
            zipOutputStream.putNextEntry(entry = new ZipEntry("License/" + licenseFileName));
            IOUtils.copyLarge(new ByteArrayInputStream(licenseFile), zipOutputStream);
            zipOutputStream.closeEntry();
        }

        if (mc.isScenFile() && scen.getScenarioFile() != null) {
            try {

                log.debug("saving scenario file (" + scen.getScenarioName() + ") into a zip file");
                entry = new ZipEntry("Scenario/" + scen.getScenarioName());
                zipOutputStream.putNextEntry(entry);
                IOUtils.copyLarge(scen.getScenarioFile().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();

            } catch (Exception ex) {
                log.error(ex);
            }
        }

        if (xmlMetadata != null) {
            log.debug("saving xml file of metadata to zip file");
            entry = new ZipEntry(getMetadata() + ".xml");
            zipOutputStream.putNextEntry(entry);
            zipOutputStream.write(xmlMetadata);
            zipOutputStream.closeEntry();
        }

        for (DataFile dataFile : dataFiles) {
            entry = new ZipEntry(getDataZip() + "/" + dataFile.getFilename());

            if (dataFile.getFileContent().length() > 0) {

                log.debug("saving data file to zip file");

                try {

                    zipOutputStream.putNextEntry(entry);

                } catch (ZipException ex) {

                    String[] partOfName = dataFile.getFilename().split("[.]");
                    String filename;
                    if (partOfName.length < 2) {
                        filename = partOfName[0] + "" + fileCounter;
                    } else {
                        filename = partOfName[0] + "" + fileCounter + "." + partOfName[1];
                    }
                    entry = new ZipEntry(getDataZip() + "/" + filename);
                    zipOutputStream.putNextEntry(entry);
                    fileCounter++;
                }

                IOUtils.copyLarge(dataFile.getFileContent().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();
            }
        }

        log.debug("returning output stream of zip file");
        return tempZipFile;

    } finally {

        zipOutputStream.flush();
        zipOutputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        fileCounter = 0;

    }
}