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 synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

From source file:org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.java

/**
 * //from   w  w  w .  j  av  a  2  s.  c  o m
 * Compress the modified files back into payload.zip
 * @param tempfileName 
 * 
 */
private void zipPayloadFile(String tempfileName) {

    int buffer = 2048;
    BufferedInputStream origin = null;
    ZipOutputStream out = null;

    try {

        FileOutputStream dest = new FileOutputStream(CARBON_HOME + File.separator
                + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfileName + ".zip");
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[buffer];

        File f = new File(
                CARBON_HOME + File.separator + tempfileName + File.separator + AutoscalerConstant.PAYLOAD_DIR);
        String files[] = f.list();

        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(CARBON_HOME + File.separator + tempfileName
                    + File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
            origin = new BufferedInputStream(fi, buffer);
            ZipEntry entry = new ZipEntry(AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
            out.putNextEntry(entry);

            int count;
            while ((count = origin.read(data, 0, buffer)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }

        // delete temp files
        deleteDir(f);
        File fl = new File(CARBON_HOME + File.separator + tempfileName);
        fl.delete();

    } catch (Exception e) {
        log.error("Exception is occurred in zipping payload file after modification. Reason:" + e.getMessage());
        throw new AutoscalerServiceException(e.getMessage(), e);
    } finally {
        closeStream(origin);
        closeStream(out);
    }
}

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>//from   w  ww  .  ja  v a  2 s  . 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:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException /*from  www  .ja  v a2s  .c  o m*/
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }

                zipOutputStream.closeEntry();

                // Close the current file input stream
                in.close();
            }

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:com.esd.ps.EmployerController.java

/**
 * ??,zip/*from   w  w w .  jav a  2  s .  c  om*/
 * 
 * @param list
 * @param zos
 * @param fileType
 */
public void writeInZIP(List<taskWithBLOBs> list, ZipOutputStream zos, String fileType) {
    for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
        try {
            byte[] bufs = new byte[1024 * 10];
            taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
            String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName();
            fileName = fileName.substring(0, fileName.indexOf(Constants.POINT)) + Constants.POINT + fileType;
            // ZIP,,
            ZipEntry zipEntry = new ZipEntry(taskWithBLOBs.getTaskDir() + Constants.SLASH + fileName);
            zos.putNextEntry(zipEntry);
            byte[] data = null;
            if (fileType.equalsIgnoreCase(Constants.WAV)) {
                data = taskWithBLOBs.getTaskWav();
            } else if (fileType.equalsIgnoreCase(Constants.TAG)) {
                data = taskWithBLOBs.getTaskTag();
            } else if (fileType.equalsIgnoreCase(Constants.TEXTGRID)) {
                data = taskWithBLOBs.getTaskTextgrid();
            }
            if (data != null) {
                InputStream is = new ByteArrayInputStream(data);
                // ?
                BufferedInputStream bis = new BufferedInputStream(is, 1024);
                int read;
                while ((read = bis.read(bufs)) > 0) {
                    zos.write(bufs, 0, read);//
                }
                bis.close();
                is.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java

/** Called when the activity is first created. */
@Override/*from www . j  av  a 2  s . co m*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        ExceptionHandler.initialize(context);
        if (ExceptionHandler.needReport()) {
            final String fileName = ExceptionHandler.getBugReportFileAbsolutePath();
            final File file = new File(fileName);
            final File fileZip;
            {
                String strFileZip = file.getAbsolutePath();
                {
                    int index = strFileZip.lastIndexOf('.');
                    if (0 < index) {
                        strFileZip = strFileZip.substring(0, index);
                        strFileZip += ".zip";
                    }
                }
                Log.d(TAG, strFileZip);
                fileZip = new File(strFileZip);
                if (fileZip.exists()) {
                    fileZip.delete();
                }
            }
            if (file.exists()) {
                Log.d(TAG, file.getAbsolutePath());
                InputStream inStream = null;
                ZipOutputStream outStream = null;
                try {
                    inStream = new FileInputStream(file);
                    String strFileName = file.getAbsolutePath();
                    {
                        int index = strFileName.lastIndexOf(File.separatorChar);
                        if (0 < index) {
                            strFileName = strFileName.substring(index + 1);
                        }
                    }
                    Log.d(TAG, strFileName);

                    outStream = new ZipOutputStream(new FileOutputStream(fileZip));
                    byte[] buff = new byte[8124];
                    {
                        ZipEntry entry = new ZipEntry(strFileName);
                        outStream.putNextEntry(entry);

                        int len = 0;
                        while (0 < (len = inStream.read(buff))) {
                            outStream.write(buff, 0, len);
                        }
                        outStream.closeEntry();
                    }
                    outStream.finish();
                    outStream.flush();

                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != outStream) {
                        try {
                            outStream.close();
                        } catch (Exception e) {
                        }
                    }
                    outStream = null;

                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }
                Log.i(TAG, "zip created");
            }

            if (file.exists()) {
                // upload or send e-mail
                InputStream inStream = null;
                StringBuilder sb = new StringBuilder();
                try {
                    inStream = new FileInputStream(file);
                    byte[] buff = new byte[8124];
                    int readed = 0;
                    do {
                        readed = inStream.read(buff);
                        for (int i = 0; i < readed; i++) {
                            sb.append((char) buff[i]);
                        }
                    } while (readed >= 0);

                    final String str = sb.toString();
                    Log.i(TAG, str);
                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                final Locale defaultLocale = Locale.getDefault();

                String title = "";
                String message = "";
                String positive = "";
                String negative = "";

                boolean needDefaultLang = true;
                if (null != defaultLocale) {
                    if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) {
                        title = "";
                        message = "?????????";
                        positive = "?";
                        negative = "";
                        needDefaultLang = false;
                    }
                }
                if (needDefaultLang) {
                    title = "ERROR";
                    message = "Got unexpected error. Do you want to send information of error.";
                    positive = "Send";
                    negative = "Cancel";
                }
                alertDialog.setTitle(title);
                alertDialog.setMessage(message);
                alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderMailClient.upload(context, file,
                                new String[] { "diverKon+sakura@gmail.com" });
                    }
                });
                alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip,
                                "http://kkkon.sakura.ne.jp/android/bug");
                    }
                });
                alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        ExceptionHandler.clearReport();
                    }
                });
                alertDialog.show();
            }
            // TODO separate activity for crash report
            //DefaultCheckerAPK.checkAPK( this, null );
        }
        ExceptionHandler.registHandler();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    Button btn2 = new Button(this);
    btn2.setText("reinstall apk");
    btn2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                if (fileApk.exists()) {
                    foundApk = true;

                    Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                    promptInstall.setDataAndType(Uri.fromFile(fileApk),
                            "application/vnd.android.package-archive");
                    promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(promptInstall);
                }
            }

            if (false == foundApk) {
                for (int i = 0; i < 10; ++i) {
                    File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk");
                    Log.d(TAG, "check apk:" + fileApk.getAbsolutePath());
                    if (fileApk.exists()) {
                        Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath());
                        /*
                         * // require parmission
                        {
                        final String strCmd = "pm install -r " + fileApk.getAbsolutePath();
                        try
                        {
                            Runtime.getRuntime().exec( strCmd );
                        }
                        catch ( IOException e )
                        {
                            Log.e( TAG, "got exception", e );
                        }
                        }
                        */
                        Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                        promptInstall.setDataAndType(Uri.fromFile(fileApk),
                                "application/vnd.android.package-archive");
                        promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(promptInstall);
                        break;
                    }
                }
            }
        }
    });
    layout.addView(btn2);

    Button btn3 = new Button(this);
    btn3.setText("check apk");
    btn3.setOnClickListener(new View.OnClickListener() {
        private boolean checkApk(final File fileApk, final ZipEntryFilter filter) {
            final boolean[] result = new boolean[1];
            result[0] = true;

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    if (fileApk.exists()) {
                        ZipFile zipFile = null;
                        try {
                            zipFile = new ZipFile(fileApk);
                            List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size());
                            for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                                ZipEntry ent = e.nextElement();
                                Log.d(TAG, ent.getName());
                                Log.d(TAG, "" + ent.getSize());
                                final boolean accept = filter.accept(ent);
                                if (accept) {
                                    list.add(ent);
                                }
                            }

                            Log.d(TAG, Build.CPU_ABI); // API 4
                            Log.d(TAG, Build.CPU_ABI2); // API 8

                            final String[] abiArray = { Build.CPU_ABI // API 4
                                    , Build.CPU_ABI2 // API 8
                            };

                            String abiMatched = null;
                            {
                                boolean foundMatched = false;
                                for (final String abi : abiArray) {
                                    if (null == abi) {
                                        continue;
                                    }
                                    if (0 == abi.length()) {
                                        continue;
                                    }

                                    for (final ZipEntry entry : list) {
                                        Log.d(TAG, entry.getName());

                                        final String prefixABI = "lib/" + abi + "/";
                                        if (entry.getName().startsWith(prefixABI)) {
                                            abiMatched = abi;
                                            foundMatched = true;
                                            break;
                                        }
                                    }

                                    if (foundMatched) {
                                        break;
                                    }
                                }
                            }
                            Log.d(TAG, "matchedAbi=" + abiMatched);

                            if (null != abiMatched) {
                                boolean needReInstall = false;

                                for (final ZipEntry entry : list) {
                                    Log.d(TAG, entry.getName());

                                    final String prefixABI = "lib/" + abiMatched + "/";
                                    if (entry.getName().startsWith(prefixABI)) {
                                        final String jniName = entry.getName().substring(prefixABI.length());
                                        Log.d(TAG, "jni=" + jniName);

                                        final String strFileDst = context.getApplicationInfo().nativeLibraryDir
                                                + "/" + jniName;
                                        Log.d(TAG, strFileDst);
                                        final File fileDst = new File(strFileDst);
                                        if (!fileDst.exists()) {
                                            Log.w(TAG, "needReInstall: content missing " + strFileDst);
                                            needReInstall = true;
                                        } else {
                                            assert (entry.getSize() <= Integer.MAX_VALUE);
                                            if (fileDst.length() != entry.getSize()) {
                                                Log.w(TAG, "needReInstall: size broken " + strFileDst);
                                                needReInstall = true;
                                            } else {
                                                //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) );

                                                final int size = (int) entry.getSize();
                                                byte[] buffSrc = new byte[size];

                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = zipFile.getInputStream(entry);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffSrc, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }
                                                byte[] buffDst = new byte[(int) fileDst.length()];
                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = new FileInputStream(fileDst);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffDst, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }

                                                if (Arrays.equals(buffSrc, buffDst)) {
                                                    Log.d(TAG, " content equal " + strFileDst);
                                                    // OK
                                                } else {
                                                    Log.w(TAG, "needReInstall: content broken " + strFileDst);
                                                    needReInstall = true;
                                                }
                                            }

                                        }

                                    }
                                } // for ZipEntry

                                if (needReInstall) {
                                    // need call INSTALL APK
                                    Log.w(TAG, "needReInstall apk");
                                    result[0] = false;
                                } else {
                                    Log.d(TAG, "no need ReInstall apk");
                                }
                            }

                        } catch (IOException e) {
                            Log.d(TAG, "got exception", e);
                        } finally {
                            if (null != zipFile) {
                                try {
                                    zipFile.close();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

            });
            thread.setName("check jni so");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now checking installation. Cancel check?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            try {
                thread.join();
            } catch (InterruptedException e) {
                Log.d(TAG, "got exception", e);
            }

            return result[0];
        }

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                this.checkApk(fileApk, new ZipEntryFilter() {
                    @Override
                    public boolean accept(ZipEntry entry) {
                        if (entry.isDirectory()) {
                            return false;
                        }

                        final String filename = entry.getName();
                        if (filename.startsWith("lib/")) {
                            return true;
                        }

                        return false;
                    }
                });
            }

        }
    });
    layout.addView(btn3);

    Button btn4 = new Button(this);
    btn4.setText("print dir and path");
    btn4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            {
                final File file = context.getCacheDir();
                Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile());
            }
            {
                final File file = context.getExternalCacheDir(); // API 8
                if (null == file) {
                    // no permission
                    Log.d(TAG, "Ctx.ExternalCacheDir=");
                } else {
                    Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath());
                }
            }
            {
                final File file = context.getFilesDir();
                Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath());
            }
            {
                final String value = context.getPackageResourcePath();
                Log.d(TAG, "Ctx.PackageResourcePath=" + value);
            }
            {
                final String[] files = context.fileList();
                if (null == files) {
                    Log.d(TAG, "Ctx.fileList=" + files);
                } else {
                    for (final String filename : files) {
                        Log.d(TAG, "Ctx.fileList=" + filename);
                    }
                }
            }

            {
                final File file = Environment.getDataDirectory();
                Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getDownloadCacheDirectory();
                Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getExternalStorageDirectory();
                Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getRootDirectory();
                Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath());
            }
            {
                final ApplicationInfo appInfo = context.getApplicationInfo();
                Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir);
                Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9
                Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir);
                {
                    final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles;
                    if (null == sharedLibraryFiles) {
                        Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles);
                    } else {
                        for (final String fileName : sharedLibraryFiles) {
                            Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName);
                        }
                    }
                }
                Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir);
            }
            {
                Log.d(TAG, "System.Properties start");
                final Properties properties = System.getProperties();
                if (null != properties) {
                    for (final Object key : properties.keySet()) {
                        String value = properties.getProperty((String) key);
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.Properties end");
            }
            {
                Log.d(TAG, "System.getenv start");
                final Map<String, String> mapEnv = System.getenv();
                if (null != mapEnv) {
                    for (final Map.Entry<String, String> entry : mapEnv.entrySet()) {
                        final String key = entry.getKey();
                        final String value = entry.getValue();
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.getenv end");
            }
        }
    });
    layout.addView(btn4);

    Button btn5 = new Button(this);
    btn5.setText("check INSTALL_NON_MARKET_APPS");
    btn5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            SettingsCompat.initialize(context);
            if (SettingsCompat.isAllowedNonMarketApps()) {
                Log.d(TAG, "isAllowdNonMarketApps=true");
            } else {
                Log.d(TAG, "isAllowdNonMarketApps=false");
            }
        }
    });
    layout.addView(btn5);

    Button btn6 = new Button(this);
    btn6.setText("send email");
    btn6.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent mailto = new Intent();
            mailto.setAction(Intent.ACTION_SENDTO);
            mailto.setType("message/rfc822");
            mailto.setData(Uri.parse("mailto:"));
            mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
            mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName());
            mailto.putExtra(Intent.EXTRA_TEXT, "body text");
            //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
            //context.startActivity( mailto );
            Intent intent = Intent.createChooser(mailto, "Send Email");
            if (null != intent) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    context.startActivity(intent);
                } catch (android.content.ActivityNotFoundException e) {
                    Log.d(TAG, "got Exception", e);
                }
            }
        }
    });
    layout.addView(btn6);

    Button btn7 = new Button(this);
    btn7.setText("upload http thread");
    btn7.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Log.d(TAG, "brd=" + Build.BRAND);
            Log.d(TAG, "prd=" + Build.PRODUCT);

            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
            Log.d(TAG, "fng=" + Build.FINGERPRINT);
            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    Log.d(TAG, "upload thread tid=" + android.os.Process.myTid());
                    try {
                        HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug");
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                    }
                    Log.d(TAG, "upload finish");
                }
            });
            thread.setName("upload crash");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now uploading error information. Cancel upload?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            /*
            try
            {
            thread.join(); // must call. leak handle...
            }
            catch ( InterruptedException e )
            {
            Log.d( TAG, "got Exception", e );
            }
            */
        }
    });
    layout.addView(btn7);

    Button btn8 = new Button(this);
    btn8.setText("upload http AsyncTask");
    btn8.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                @Override
                protected Boolean doInBackground(String... paramss) {
                    Boolean result = true;
                    Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                    try {
                        //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                        Log.d(TAG, "fng=" + Build.FINGERPRINT);
                        final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                        list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                        HttpPost httpPost = new HttpPost(paramss[0]);
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                        result = false;
                    }
                    Log.d(TAG, "upload finish");
                    return result;
                }

            };

            asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
            asyncTask.isCancelled();
        }
    });
    layout.addView(btn8);

    Button btn9 = new Button(this);
    btn9.setText("call checkAPK");
    btn9.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null);
            Log.i(TAG, "checkAPK result=" + result);
        }
    });
    layout.addView(btn9);

    setContentView(layout);
}

From source file:lu.fisch.moenagade.model.Project.java

private void addToZip(ZipOutputStream zo, String baseDir, File directory)
        throws FileNotFoundException, IOException {
    // get all files
    File[] files = directory.listFiles();
    if (files != null)
        for (int f = 0; f < files.length; f++) {
            if (files[f].isDirectory()) {
                String entry = files[f].getAbsolutePath();
                entry = entry.substring(directory.getAbsolutePath().length() + 1);
                addToZip(zo, baseDir + entry + "/", files[f]);
            } else {
                //System.out.println("File = "+files[f].getAbsolutePath());
                //System.out.println("List = "+Arraysv.deepToString(excludeExtention));
                //System.out.println("We got = "+getExtension(files[f]));
                FileInputStream bi = new FileInputStream(files[f]);

                String entry = files[f].getAbsolutePath();
                entry = entry.substring(directory.getAbsolutePath().length() + 1);
                entry = baseDir + entry;
                ZipEntry ze = new ZipEntry(entry);
                zo.putNextEntry(ze);//from w  ww  .  j  a v  a 2s  .  c om
                byte[] buf = new byte[1024];
                int anz;
                while ((anz = bi.read(buf)) != -1) {
                    zo.write(buf, 0, anz);
                }
                zo.closeEntry();
                bi.close();
            }
        }
}

From source file:com.jtschohl.androidfirewall.MainActivity.java

/**
 * Zip error reports//from   w  ww.j  a v  a2 s .  c  om
 */

public void zipFiles() {
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/af_error_reports/");
    String filename = "af_error_reports.zip";
    String[] reports = { dir + "/iptables.txt", dir + "/logcat.txt", dir + "/interfaces.txt" };
    File file = new File(dir, filename);

    try {
        BufferedInputStream origin = null;
        FileOutputStream dest = new FileOutputStream(file);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[2048];

        for (int i = 0; i < reports.length; i++) {
            Log.v(TAG, "Compressing folder: " + reports[i]);
            FileInputStream fi = new FileInputStream(reports[i]);
            origin = new BufferedInputStream(fi, 2048);
            ZipEntry entry = new ZipEntry(reports[i].substring(reports[i].lastIndexOf("/") + 1));
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, 2048)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
        Toast.makeText(MainActivity.this, R.string.generate_zip, Toast.LENGTH_SHORT).show();
        emailErrorReports();
    } catch (Exception e) {
        Log.e(TAG, "Error zipping folder");
        e.printStackTrace();
    }
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

private void convertOutputZip(String userId, String workflowId, String jobId, String fileName, InputStream is,
        OutputStream os) throws IOException {

    InputStream exactFile = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;/*from  w  ww  .  j av a 2 s .c  om*/
    String runtimeID = getRuntimeID(userId, workflowId);
    ZipOutputStream zos = new ZipOutputStream(os);
    while ((entry = zis.getNextEntry()) != null) {

        if (jobId == null || (entry.getName().contains(jobId + "/outputs/" + runtimeID + "/")
                && (fileName == null || (fileName != null && entry.getName().endsWith(fileName))))) {
            int size;
            byte[] buffer = new byte[2048];

            String parentDir = entry.getName().split("/")[entry.getName().split("/").length - 2];
            String fileNameInZip = parentDir + "/"
                    + entry.getName().split("/")[entry.getName().split("/").length - 1];
            ZipEntry newFile = new ZipEntry(fileNameInZip);
            zos.putNextEntry(newFile);

            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {

                zos.write(buffer, 0, size);
            }
            zos.closeEntry();

        }
    }
    zis.close();
    zos.close();

}

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from   w w w. ja va  2  s.c o m*/
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

                Pattern pattern = null;
                if (!Const.isEmpty(realWildcard)) {
                    pattern = Pattern.compile(realWildcard);

                }
                Pattern patternexclude = null;
                if (!Const.isEmpty(realWildcardExclude)) {
                    patternexclude = Pattern.compile(realWildcardExclude);

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

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

                // Set the compression level
                if (compressionrate == 0) {
                    out.setLevel(Deflater.NO_COMPRESSION);
                } else if (compressionrate == 1) {
                    out.setLevel(Deflater.DEFAULT_COMPRESSION);
                }
                if (compressionrate == 2) {
                    out.setLevel(Deflater.BEST_COMPRESSION);
                }
                if (compressionrate == 3) {
                    out.setLevel(Deflater.BEST_SPEED);
                }

                // Specify Zipped files (After that we will move,delete them...)
                String[] ZippedFiles = new String[filelist.length];
                int FileNum = 0;

                // Get the files in the list...
                for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

                        int len;
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }

                        out.closeEntry();

                        // Close the current file input stream
                        in.close();

                        // Get Zipped File
                        ZippedFiles[FileNum] = filelist[i];
                        FileNum = FileNum + 1;
                    }
                }

                // Close the ZipOutPutStream
                out.close();

                //-----Get the list of Zipped Files and Move or Delete Them
                if (afterzip == 1 || afterzip == 2) {
                    // iterate through the array of Zipped files
                    for (int i = 0; i < ZippedFiles.length; i++) {
                        if (ZippedFiles[i] != null) {
                            // Delete File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

From source file:org.eclipse.che.vfs.impl.fs.FSMountPoint.java

ContentStream zip(VirtualFileImpl virtualFile, VirtualFileFilter filter)
        throws ForbiddenException, ServerException {
    if (!virtualFile.isFolder()) {
        throw new ForbiddenException(
                String.format("Unable export to zip. Item '%s' is not a folder. ", virtualFile.getPath()));
    }//from ww w  .j  a v  a2 s.co m
    java.io.File zipFile = null;
    FileOutputStream out = null;
    try {
        zipFile = java.io.File.createTempFile("export", ".zip");
        out = new FileOutputStream(zipFile);
        final ZipOutputStream zipOut = new ZipOutputStream(out);
        final LinkedList<VirtualFile> q = new LinkedList<>();
        q.add(virtualFile);
        final int zipEntryNameTrim = virtualFile.getVirtualFilePath().length();
        final byte[] buff = new byte[COPY_BUFFER_SIZE];
        while (!q.isEmpty()) {
            for (VirtualFile current : doGetChildren((VirtualFileImpl) q.pop(), SERVICE_GIT_DIR_FILTER)) {
                // (1) Check filter.
                // (2) Check permission directly for current file only.
                // We already know parent accessible for current user otherwise we should not be here.
                // Ignore item if don't have permission to read it.
                if (filter.accept(current)
                        && hasPermission((VirtualFileImpl) current, BasicPermissions.READ.value(), false)) {
                    final String zipEntryName = current.getVirtualFilePath().subPath(zipEntryNameTrim)
                            .toString().substring(1);
                    if (current.isFile()) {
                        final ZipEntry zipEntry = new ZipEntry(zipEntryName);
                        zipOut.putNextEntry(zipEntry);
                        InputStream in = null;
                        final PathLockFactory.PathLock lock = pathLockFactory
                                .getLock(current.getVirtualFilePath(), false).acquire(LOCK_FILE_TIMEOUT);
                        try {
                            zipEntry.setTime(virtualFile.getLastModificationDate());
                            in = new FileInputStream(((VirtualFileImpl) current).getIoFile());
                            int r;
                            while ((r = in.read(buff)) != -1) {
                                zipOut.write(buff, 0, r);
                            }
                        } finally {
                            closeQuietly(in);
                            lock.release();
                        }
                        zipOut.closeEntry();
                    } else if (current.isFolder()) {
                        final ZipEntry zipEntry = new ZipEntry(zipEntryName + '/');
                        zipEntry.setTime(0);
                        zipOut.putNextEntry(zipEntry);
                        q.add(current);
                        zipOut.closeEntry();
                    }
                }
            }
        }
        closeQuietly(zipOut);
        final String name = virtualFile.getName() + ".zip";
        return new ContentStream(name, new DeleteOnCloseFileInputStream(zipFile), ExtMediaType.APPLICATION_ZIP,
                zipFile.length(), new Date());
    } catch (IOException | RuntimeException ioe) {
        if (zipFile != null) {
            zipFile.delete();
        }
        throw new ServerException(ioe.getMessage(), ioe);
    } finally {
        closeQuietly(out);
    }
}