Example usage for java.util.zip ZipOutputStream setMethod

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

Introduction

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

Prototype

public void setMethod(int method) 

Source Link

Document

Sets the default compression method for subsequent entries.

Usage

From source file:org.n52.ifgicopter.spf.output.kml.KmlOutputPlugin.java

/**
 * http://java.sun.com/developer/technicalArticles/Programming/compression/
 * /*from  ww  w.j av  a  2  s. c om*/
 * TODO see if zipping solves referencing problem:
 * https://developers.google.com/kml/documentation/kmzarchives
 */
private void zipAllFiles() {
    if (!this.createKMZ) {
        return;
    }

    // saveDocumentInFile(this.kmlStaticRoot, this.outputPath + this.kmlStaticRootFileName);

    int buffer = 2048;
    try {
        BufferedInputStream origin = null;
        FileOutputStream dest = new FileOutputStream(
                this.outputFolder + File.separator + this.filePrefix + "." + KmlConstants.KMZ_FILE_EXTENSION);
        if (log.isDebugEnabled())
            log.debug("Saving KML files to zip file " + dest);

        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
        out.setMethod(ZipOutputStream.DEFLATED);

        byte data[] = new byte[buffer];

        File f = new File(this.outputFolder);
        File files[] = f.listFiles(onlyKmlFiles);

        for (int i = 0; i < files.length; i++) {
            if (log.isDebugEnabled())
                log.debug("Zipping " + files[i]);

            FileInputStream fi = new FileInputStream(files[i].getAbsolutePath());
            origin = new BufferedInputStream(fi, buffer);
            ZipEntry entry = new ZipEntry(files[i].getName());
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, buffer)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
    } catch (Exception e) {
        log.error(e);
    }
}

From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

@Override
public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException {

    String userName = AuthenticationUtil.getFullyAuthenticatedUser();

    PersonService personService = services.getPersonService();

    NodeRef userNodeRef = personService.getPerson(userName);

    MimetypeService mimetypeService = services.getMimetypeService();
    FileFolderService fileFolderService = services.getFileFolderService();

    Charset archiveEncoding = Charset.forName("ISO-8859-1");

    String encoding = request.getParameter("encoding");

    if (StringUtils.isNotEmpty(encoding)) {
        archiveEncoding = Charset.forName(encoding);
    }//w ww. jav a2 s.  c om

    ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding);
    String folderName = "mon_panier";
    try {

        String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP);

        res.setContentType(MimetypeMap.MIMETYPE_ZIP);

        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        fileZip.setMethod(ZipOutputStream.DEFLATED);
        fileZip.setLevel(Deflater.BEST_COMPRESSION);

        String archiveRootPath = folderName + "/";

        List<NodeRef> list = smilePanierService.getSelection(userNodeRef);
        List<FileInfo> filesInfos = new ArrayList<FileInfo>();
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i));
            filesInfos.add(fileInfo);
        }

        for (FileInfo file : filesInfos) {
            addEntry(file, fileZip, archiveRootPath);
        }
        fileZip.closeEntry();

    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e);
    } finally {
        fileZip.close();
    }

}

From source file:com.ichi2.libanki.Media.java

/**
 * Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing
 * potentially large files in memory which is not feasible with Android's limited heap space.
 * <p>/*w  w  w . ja v a 2s  .c  om*/
 * Notes:
 * <p>
 * - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this
 * limit, only that file (in full) will be zipped to be sent to the server.
 * <p>
 * - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB)
 * to send.
 * <p>
 * - Since AnkiDroid avoids scanning the media folder on every sync, it is possible for a file to be marked as a
 * new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file
 * and mark it as removed in the database. (This behaviour differs from the desktop client).
 * <p>
 */
public Pair<File, List<String>> mediaChangesZip() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));
    Cursor cur = null;
    try {
        ZipOutputStream z = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        z.setMethod(ZipOutputStream.DEFLATED);

        List<String> fnames = new ArrayList<String>();
        // meta is a list of (fname, zipname), where zipname of null is a deleted file
        // NOTE: In python, meta is a list of tuples that then gets serialized into json and added
        // to the zip as a string. In our version, we use JSON objects from the start to avoid the
        // serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays.
        JSONArray meta = new JSONArray();
        int sz = 0;
        byte buffer[] = new byte[2048];
        cur = mDb.getDatabase()
                .rawQuery("select fname, csum from media where dirty=1 limit " + Consts.SYNC_ZIP_COUNT, null);

        for (int c = 0; cur.moveToNext(); c++) {
            String fname = cur.getString(0);
            String csum = cur.getString(1);
            fnames.add(fname);
            String normname = HtmlUtil.nfcNormalized(fname);

            if (!TextUtils.isEmpty(csum)) {
                try {
                    mCol.log("+media zip " + fname);
                    File file = new File(dir(), fname);
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
                    z.putNextEntry(new ZipEntry(Integer.toString(c)));
                    int count = 0;
                    while ((count = bis.read(buffer, 0, 2048)) != -1) {
                        z.write(buffer, 0, count);
                    }
                    z.closeEntry();
                    bis.close();
                    meta.put(new JSONArray().put(normname).put(Integer.toString(c)));
                    sz += file.length();
                } catch (FileNotFoundException e) {
                    // A file has been marked as added but no longer exists in the media directory.
                    // Skip over it and mark it as removed in the db.
                    removeFile(fname);
                }
            } else {
                mCol.log("-media zip " + fname);
                meta.put(new JSONArray().put(normname).put(""));
            }
            if (sz >= Consts.SYNC_ZIP_SIZE) {
                break;
            }
        }

        z.putNextEntry(new ZipEntry("_meta"));
        z.write(Utils.jsonToString(meta).getBytes());
        z.closeEntry();
        z.close();
        // Don't leave lingering temp files if the VM terminates.
        f.deleteOnExit();
        return new Pair<File, List<String>>(f, fnames);
    } catch (IOException e) {
        Timber.e("Failed to create media changes zip", e);
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}

From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

@Restrict("#{s:hasPermission('trust', 'access')}")
public String downloadConfiguration() {
    Shibboleth2ConfService shibboleth2ConfService = Shibboleth2ConfService.instance();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(16384);
    ZipOutputStream zos = ResponseHelper.createZipStream(bos, "Shibboleth2 configuration files");
    try {//w w w .  java2 s  .co m
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        // Add files
        String idpMetadataFilePath = shibboleth2ConfService.getIdpMetadataFilePath();
        if (!ResponseHelper.addFileToZip(idpMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_IDP_METADATA_FILE)) {
            log.error("Failed to add " + idpMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        if (this.trustRelationship.getSpMetaDataFN() == null) {
            log.error("SpMetaDataFN is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spMetadataFilePath = shibboleth2ConfService
                .getSpMetadataFilePath(this.trustRelationship.getSpMetaDataFN());
        if (!ResponseHelper.addFileToZip(spMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_SP_METADATA_FILE)) {
            log.error("Failed to add " + spMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String sslDirFN = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator
                + TrustService.GENERATED_SSL_ARTIFACTS_DIR + File.separator;
        String spKeyFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".key");
        if (!ResponseHelper.addFileToZip(spKeyFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_KEY_FILE)) {
            log.error("Failed to add " + spKeyFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }
        String spCertFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".crt");
        if (!ResponseHelper.addFileToZip(spCertFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_CERT_FILE)) {
            log.error("Failed to add " + spCertFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }

        String spAttributeMap = shibboleth2ConfService.generateSpAttributeMapFile(this.trustRelationship);
        if (spAttributeMap == null) {
            log.error("spAttributeMap is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        if (!ResponseHelper.addFileContentToZip(spAttributeMap, zos,
                Shibboleth2ConfService.SHIB2_SP_ATTRIBUTE_MAP)) {
            log.error("Failed to add " + spAttributeMap + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spShibboleth2FilePath = shibboleth2ConfService.getSpShibboleth2FilePath();
        VelocityContext context = new VelocityContext();
        context.put("spUrl", trustRelationship.getUrl());
        String gluuSPEntityId = trustRelationship.getEntityId();
        context.put("gluuSPEntityId", gluuSPEntityId);
        String spHost = trustRelationship.getUrl().replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("spHost", spHost);
        String idpUrl = applicationConfiguration.getIdpUrl();
        context.put("idpUrl", idpUrl);
        String idpHost = idpUrl.replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("idpHost", idpHost);
        context.put("orgInum",
                StringHelper.removePunctuation(OrganizationService.instance().getOrganizationInum()));
        context.put("orgSupportEmail", applicationConfiguration.getOrgSupportEmail());
        String shibConfig = templateService.generateConfFile(Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2,
                context);
        if (!ResponseHelper.addFileContentToZip(shibConfig, zos, Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2)) {
            log.error("Failed to add " + spShibboleth2FilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spReadMeResourceName = shibboleth2ConfService.getSpReadMeResourceName();
        String fileName = (new File(spReadMeResourceName)).getName();
        InputStream is = resourceLoader.getResourceAsStream(spReadMeResourceName);
        //InputStream is = this.getClass().getClassLoader().getResourceAsStream(spReadMeResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spReadMeWindowsResourceName = shibboleth2ConfService.getSpReadMeWindowsResourceName();
        fileName = (new File(spReadMeWindowsResourceName)).getName();
        is = resourceLoader.getResourceAsStream(spReadMeWindowsResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeWindowsResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(bos);
    }

    boolean result = ResponseHelper.downloadFile("shibboleth2-configuration.zip",
            OxTrustConstants.CONTENT_TYPE_APPLICATION_ZIP, bos.toByteArray(), facesContext);

    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}

From source file:brut.androlib.res.AndrolibResources.java

public void installFramework(File frameFile, String tag) throws AndrolibException {
    InputStream in = null;/*www.java 2 s. co m*/
    ZipOutputStream out = null;
    try {
        ZipFile zip = new ZipFile(frameFile);
        ZipEntry entry = zip.getEntry("resources.arsc");

        if (entry == null) {
            throw new AndrolibException("Can't find resources.arsc file");
        }

        in = zip.getInputStream(entry);
        byte[] data = IOUtils.toByteArray(in);

        ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true);
        publicizeResources(data, arsc.getFlagsOffsets());

        File outFile = new File(getFrameworkDir(),
                String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk");

        out = new ZipOutputStream(new FileOutputStream(outFile));
        out.setMethod(ZipOutputStream.STORED);
        CRC32 crc = new CRC32();
        crc.update(data);
        entry = new ZipEntry("resources.arsc");
        entry.setSize(data.length);
        entry.setCrc(crc.getValue());
        out.putNextEntry(entry);
        out.write(data);
        zip.close();
        LOGGER.info("Framework installed to: " + outFile);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

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

protected void doUpload() {
    DbAdapter dba = new DbAdapter(this);
    dba.open();/*from w ww .  ja  v  a2  s .  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.pentaho.di.trans.steps.zipfile.ZipFile.java

private void zipFile() throws KettleException {

    String localrealZipfilename = KettleVFS.getFilename(data.zipFile);
    boolean updateZip = false;

    byte[] buffer = null;
    OutputStream dest = null;//from  w  w  w  . ja  v  a 2  s  .  co m
    BufferedOutputStream buff = null;
    ZipOutputStream out = null;
    InputStream in = null;
    ZipInputStream zin = null;
    ZipEntry entry = null;
    File tempFile = null;
    HashSet<String> fileSet = new HashSet<String>();

    try {

        updateZip = (data.zipFile.exists() && meta.isOverwriteZipEntry());

        if (updateZip) {
            // the Zipfile exists
            // and we weed to update entries
            // Let's create a temp file
            File fileZip = getFile(localrealZipfilename);
            tempFile = File.createTempFile(fileZip.getName(), null);
            // delete it, otherwise we cannot rename existing zip to it.
            tempFile.delete();

            updateZip = fileZip.renameTo(tempFile);
        }

        // Prepare Zip File
        buffer = new byte[18024];
        dest = KettleVFS.getOutputStream(localrealZipfilename, false);
        buff = new BufferedOutputStream(dest);
        out = new ZipOutputStream(buff);

        if (updateZip) {
            // User want to append files to existing Zip file
            // The idea is to rename the existing zip file to a temporary file
            // and then adds all entries in the existing zip along with the new files,
            // excluding the zip entries that have the same name as one of the new files.

            zin = new ZipInputStream(new FileInputStream(tempFile));
            entry = zin.getNextEntry();

            while (entry != null) {
                String name = entry.getName();

                if (!fileSet.contains(name)) {

                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(name));
                    // Transfer bytes from the ZIP file to the output file
                    int len;
                    while ((len = zin.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }

                    fileSet.add(name);
                }
                entry = zin.getNextEntry();
            }
            // Close the streams
            zin.close();
        }

        // Set the method
        out.setMethod(ZipOutputStream.DEFLATED);
        out.setLevel(Deflater.BEST_COMPRESSION);

        // Associate a file input stream for the current file
        in = KettleVFS.getInputStream(data.sourceFile);

        // Add ZIP entry to output stream.
        //
        String relativeName = data.sourceFile.getName().getBaseName();

        if (meta.isKeepSouceFolder()) {
            // Get full filename
            relativeName = KettleVFS.getFilename(data.sourceFile);

            if (data.baseFolder != null) {
                // Remove base folder
                data.baseFolder += Const.FILE_SEPARATOR;
                relativeName = relativeName.replace(data.baseFolder, "");
            }
        }
        if (!fileSet.contains(relativeName)) {
            out.putNextEntry(new ZipEntry(relativeName));

            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "ZipFile.ErrorCreatingZip"), e);
    } finally {
        try {
            if (in != null) {
                // Close the current file input stream
                in.close();
            }
            if (out != null) {
                // Close the ZipOutPutStream
                out.flush();
                out.closeEntry();
                out.close();
            }
            if (buff != null) {
                buff.close();
            }
            if (dest != null) {
                dest.close();
            }
            // Delete Temp File
            if (tempFile != null) {
                tempFile.delete();
            }
            fileSet = null;

        } catch (Exception e) { /* Ignore */
        }
    }

}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Zip(String zipFileName, String srcName) {
    String fixedZipFileName = fixFileName(zipFileName);
    String fixedSrcName = fixFileName(srcName);
    String sRet = "";

    try {//from   w w  w  .  j av  a2s.c  o  m
        FileOutputStream dest = new FileOutputStream(fixedZipFileName);
        CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum));
        out.setMethod(ZipOutputStream.DEFLATED);

        sRet += AddFilesToZip(out, fixedSrcName, "");

        out.close();
        System.out.println("checksum:                   " + checksum.getChecksum().getValue());
        sRet += "checksum:                   " + checksum.getChecksum().getValue();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (sRet);
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {/*  w ww.  j  a va2 s .c o m*/
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}