Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:edu.umd.cs.marmoset.modelClasses.Project.java

public void exportProject(Connection conn, OutputStream out) throws SQLException, IOException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(out);

    TestSetup testSetup = TestSetup.lookupByTestSetupPK(getTestSetupPK(), conn);
    if (testSetup != null) {

        // Test-setup
        zipOutputStream.putNextEntry(new ZipEntry(getProjectNumber() + "-test-setup.zip"));
        zipOutputStream.write(testSetup.downloadArchive(conn));

        // Canonical
        Submission canonical = Submission.lookupBySubmissionPK(
                (TestRun.lookupByTestRunPK(testSetup.getTestRunPK(), conn)).getSubmissionPK(), conn);
        zipOutputStream.putNextEntry(new ZipEntry(getProjectNumber() + "-canonical.zip"));
        zipOutputStream.write(canonical.downloadArchive(conn));
    }//from  ww w .  j  a  va2s. c om

    // Serialize the project object itself and include it
    zipOutputStream.putNextEntry(new ZipEntry(getProjectNumber() + "-project.out"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(baos);
    objectOutputStream.writeObject(this);
    objectOutputStream.flush();
    objectOutputStream.close();
    zipOutputStream.write(baos.toByteArray());

    // project starter files, if any
    if (getArchivePK() != null) {
        zipOutputStream.putNextEntry(new ZipEntry(getProjectNumber() + "-project-starter-files.zip"));
        zipOutputStream.write(getBaselineZip(conn));
    }

    zipOutputStream.close();
}

From source file:com.orange.mmp.widget.WidgetManager.java

/**
 * Add branch ID to a widget Manifest before deploying it
 * @param widgetFile//w  ww  .ja  v a2  s  .  c o  m
 * @param branchId
 * @return a Widget instance
 * @throws IOException 
 * @throws MMPException 
 */
public Widget deployWidget(File widgetFile, String branchId) throws MMPException {
    Widget widget = new Widget();
    ZipInputStream zin = null;
    ZipOutputStream zout = null;

    try {
        JarFile jarFile = new JarFile(new File(widgetFile.toURI()));
        Manifest manifest = jarFile.getManifest();

        String tmpWidgetId = manifest.getMainAttributes()
                .getValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER);
        widget.setBranchId(branchId);

        if (tmpWidgetId != null) {
            widget.setName(manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_NAME_HEADER));
            widget.setId(tmpWidgetId + com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN + branchId);
            manifest.getMainAttributes().putValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER,
                    widget.getId());

            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".jar");

            zin = new ZipInputStream(new FileInputStream(widgetFile));
            zout = new ZipOutputStream(new FileOutputStream(tempFile));

            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                zout.putNextEntry(new ZipEntry(name));
                if (!name.equals(com.orange.mmp.midlet.Constants.JAR_MANIFEST_ENTRY)) {
                    IOUtils.copy(zin, zout);
                } else {
                    manifest.write(zout);
                }
                entry = zin.getNextEntry();
            }

            widget.setLocation(tempFile.toURI());
            widget.setId(tmpWidgetId);
            widget.setLastModified(tempFile.lastModified());
            widget.setCategory(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET);
            widget.setVersion(new Version(
                    manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_VERSION_HEADER)));
        } else {
            throw new MMPException("Invalid module archive, missing "
                    + FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER + " header");
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy widget", ioe);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException ioe) {
                //NOP
            }
        }
        if (zout != null)
            try {
                zout.close();
            } catch (IOException ioe) {
                //NOP
            }
    }

    MMPOSGiContainer moduleContainer = (MMPOSGiContainer) ModuleContainerFactory.getInstance()
            .getModuleContainer();
    moduleContainer.deployModule(new File(widget.getLocation()));

    return widget;
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * fetch data from a given url./*  w w  w  .j av  a  2s.  com*/
 * 
 * @param url
 * @return byte[]
 * @throws SourceNotAvailableException
 * @throws RuntimeException
 * @throws AccessException
 */
public byte[] fetchMetadatafromURL(URL url)
        throws SourceNotAvailableException, RuntimeException, AccessException {
    byte[] input = null;
    URLConnection conn = null;
    Date retryAfter = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    try {
        conn = ProxyHelper.openConnection(url);
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            String retryAfterHeader = conn.getHeaderField("Retry-After");
            if (retryAfterHeader != null) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
                retryAfter = dateFormat.parse(retryAfterHeader);
                this.logger.debug("Source responded with 503, retry after " + retryAfter + ".");
                throw new SourceNotAvailableException(retryAfter);
            }
            break;
        case 302:
            String alternativeLocation = conn.getHeaderField("Location");
            return fetchMetadatafromURL(new URL(alternativeLocation));
        case 200:
            this.logger.info("Source responded with 200.");
            // Fetch file
            GetMethod method = new GetMethod(url.toString());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            // Create zip file with fetched file
            ZipEntry ze = new ZipEntry("unapi");
            ze.setSize(input.length);
            ze.setTime(this.currentDate());
            CRC32 crc321 = new CRC32();
            crc321.update(input);
            ze.setCrc(crc321.getValue());
            zos.putNextEntry(ze);
            zos.write(input);
            zos.flush();
            zos.closeEntry();
            zos.close();
            this.setContentType("application/zip");
            this.setFileEnding(".zip");
            break;
        case 403:
            throw new AccessException("Access to url " + url + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage() + ".");
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        throw new AccessException(url.toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:eu.esdihumboldt.hale.common.core.io.project.impl.ArchiveProjectWriter.java

/**
 * Creates the project archive.//w w  w  . ja va  2s .c o m
 * 
 * @param target {@link OutputStream} to write the archive to
 * @param reporter the reporter to use for the execution report
 * @param progress the progress indicator
 * @return the execution report
 * @throws IOException if an I/O operation fails
 * @throws IOProviderConfigurationException if the I/O provider was not
 *             configured properly
 */
public IOReport createProjectArchive(OutputStream target, IOReporter reporter, ProgressIndicator progress)
        throws IOException, IOProviderConfigurationException {

    ZipOutputStream zip = new ZipOutputStream(target);

    // all files related to the project are copied into a temporary
    // directory first and then packed into a zip file

    // create temporary directory and project file
    File tempDir = Files.createTempDir();
    File baseFile = new File(tempDir, "project.halex");

    // mark the temporary directory for clean-up if the project is closed
    CleanupService clean = HalePlatform.getService(CleanupService.class);
    if (clean != null) {
        clean.addTemporaryFiles(CleanupContext.PROJECT, tempDir);
    }

    LocatableOutputSupplier<OutputStream> out = new FileIOSupplier(baseFile);

    // false is correct if getParameter is null because false is default
    boolean includeWebresources = getParameter(INCLUDE_WEB_RESOURCES).as(Boolean.class, false);
    SubtaskProgressIndicator subtask = new SubtaskProgressIndicator(progress);

    // save old IO configurations
    List<IOConfiguration> oldResources = new ArrayList<IOConfiguration>();
    for (int i = 0; i < getProject().getResources().size(); i++) {
        // clone all IO configurations to work on different objects
        oldResources.add(getProject().getResources().get(i).clone());
    }
    IOConfiguration config = getProject().getSaveConfiguration();
    if (config == null) {
        config = new IOConfiguration();
    }
    IOConfiguration oldSaveConfig = config.clone();

    // copy resources to the temp directory and update xml schemas
    updateResources(tempDir, includeWebresources, subtask, reporter);

    // update target save configuration of the project
    config.getProviderConfiguration().put(PARAM_TARGET, Value.of(baseFile.toURI().toString()));

    // write project file via XMLProjectWriter
    XMLProjectWriter writer = new XMLProjectWriter();
    writer.setTarget(out);
    writer.setProject(getProject());
    writer.setProjectFiles(getProjectFiles());
    IOReport report = writer.execute(progress, reporter);

    // now after the project with its project files is written, look for the
    // alignment file and update it
    ProjectFileInfo newAlignmentInfo = getAlignmentFile(getProject());
    if (newAlignmentInfo != null) {
        URI newAlignment = tempDir.toURI().resolve(newAlignmentInfo.getLocation());
        XMLAlignmentUpdater.update(new File(newAlignment), newAlignment, includeWebresources, reporter);
    }

    // put the complete temp directory into a zip file
    IOUtils.zipDirectory(tempDir, zip);
    zip.close();

    // the files may not be deleted now as they will be needed if the
    // project is saved again w/o loading it first

    // update the relative resource locations
    LocationUpdater updater = new LocationUpdater(getProject(), out.getLocation());
    // resources are made absolute (else they can't be found afterwards),
    // e.g. when saving the project again before loading it
    updater.updateProject(false);

    // reset the save configurations that has been overridden by the XML
    // project writer
    getProject().setSaveConfiguration(oldSaveConfig);

    if (clean == null) {
        // if no clean service is available, assume the directory is not
        // needed anymore
        FileUtils.deleteDirectory(tempDir);
    }

    return report;
}

From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.java

@Override
public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]";

    try {/*  w  ww  .  j  a  v  a  2  s  .  c  om*/
        this.log.info("Esecuzione " + methodName + " in corso...");
        this.darsService.getOperatoreByPrincipal(bd);

        Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita);
        boolean eseguiRicerca = !setDomini.isEmpty();
        FrBD frBD = new FrBD(bd);
        FrFilter filter = frBD.newFilter();
        List<String> idDomini = new ArrayList<String>();
        List<Long> idsToExport = new ArrayList<Long>();
        idsToExport.add(idToExport);

        if (!setDomini.contains(-1L)) {
            List<Long> lstCodDomini = new ArrayList<Long>();
            lstCodDomini.addAll(setDomini);
            idDomini.addAll(this.toListCodDomini(lstCodDomini, bd));
            filter.setCodDominio(idDomini);

            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
            if (eseguiRicerca) {
                filter.setIdFr(idsToExport);
                eseguiRicerca = eseguiRicerca && frBD.count(filter) > 0;
            }
        }
        String fileName = "Rendicontazione.zip";

        if (eseguiRicerca) {
            Fr fr = frBD.getFr(idToExport);
            fileName = "Rendicontazione_" + fr.getIur() + ".zip";
            ZipEntry frXml = new ZipEntry("fr.xml");
            zout.putNextEntry(frXml);
            zout.write(fr.getXml());
            zout.closeEntry();
        } else {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sui flussi selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java

/**
 * @param expFile//from   ww w. j  a  v  a2 s .  c om
 * @param data
 * @param appRes
 * @throws IOException
 * 
 * writes the contents of a report resource to a zip file. 
 * Currently creates 3 entries: 1) AppResource, 2) AppResource data,
 * and if present, 3)SpReport, SpQuery, SpQueryFields.
 * 
 */
//XXX implement support for subreports
protected void writeSpReportResToZipFile(final File expFile, final String data, final AppResourceIFace appRes)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(expFile));

    //the appResource name and metadata
    sb.append("<reportresource name=\"" + appRes.getName() + "\">\r\n");
    sb.append("<metadata > <![CDATA[");
    sb.append(appRes.getMetaData());
    sb.append("]]>");
    sb.append("</metadata>\r\n");
    sb.append("<mimetype > <![CDATA[");
    sb.append(appRes.getMimeType());
    sb.append("]]>");
    sb.append("</mimetype>\r\n");
    sb.append("\r\n</reportresource>\r\n");

    zout.putNextEntry(new ZipEntry("app.xml"));
    byte[] bytes = sb.toString().getBytes();
    zout.write(bytes, 0, bytes.length);
    zout.closeEntry();

    //the data
    zout.putNextEntry(new ZipEntry("data.xml"));
    bytes = data.getBytes();
    zout.write(bytes, 0, bytes.length);
    zout.closeEntry();

    //the spReport
    sb.setLength(0);
    DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
    try {
        SpReport spRep = (SpReport) session
                .getData("from SpReport where appResourceId = " + ((SpAppResource) appRes).getId());
        if (spRep != null) {
            spRep.forceLoad();
            spRep.toXML(sb);
            bytes = sb.toString().getBytes();
            zout.putNextEntry(new ZipEntry("SpReport.xml"));
            zout.write(bytes, 0, bytes.length);
            zout.closeEntry();
        }
    } finally {
        session.close();
    }
    zout.close();
}

From source file:com.hichinaschool.flashcards.async.Connection.java

private Payload doInBackgroundUpgradeDecks(Payload data) {
    // Enable http request canceller
    mCancelCallback = new CancelCallback();

    String path = (String) data.data[0];
    File ankiDir = new File(path);
    if (!ankiDir.isDirectory()) {
        data.success = false;//from w w w.j  a  v  a2  s.  co  m
        data.data = new Object[] { "wrong anki directory" };
        return data;
    }

    // step 1: gather all .anki files into a zip, without media.
    // we must store them as 1.anki, 2.anki and provide a map so we don't run into
    // encoding issues with the zip file.
    File[] fileList = ankiDir.listFiles(new OldAnkiDeckFilter());
    List<String> corruptFiles = new ArrayList<String>();
    JSONObject map = new JSONObject();
    byte[] buf = new byte[1024];
    String zipFilename = path + "/upload.zip";
    String colFilename = path + AnkiDroidApp.COLLECTION_PATH;
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename));
        int n = 1;
        for (File f : fileList) {
            String deckPath = f.getAbsolutePath();
            // set journal mode to delete
            try {
                AnkiDb d = AnkiDatabaseManager.getDatabase(deckPath);
            } catch (SQLiteDatabaseCorruptException e) {
                // ignore invalid .anki files
                corruptFiles.add(f.getName());
                continue;
            } finally {
                AnkiDatabaseManager.closeDatabase(deckPath);
            }
            // zip file
            String tmpName = n + ".anki";
            FileInputStream in = new FileInputStream(deckPath);
            ZipEntry ze = new ZipEntry(tmpName);
            zos.putNextEntry(ze);
            int len;
            while ((len = in.read(buf)) >= 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            map.put(tmpName, f.getName());
            n++;
        }
        // if all .anki files were found corrupted, abort
        if (fileList.length == corruptFiles.size()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        ZipEntry ze = new ZipEntry("map.json");
        zos.putNextEntry(ze);
        InputStream in = new ByteArrayInputStream(Utils.jsonToString(map).getBytes("UTF-8"));
        int len;
        while ((len = in.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    File zipFile = new File(zipFilename);
    // step 1.1: if it's over 50MB compressed, it must be upgraded by the user
    if (zipFile.length() > 50 * 1024 * 1024) {
        data.success = false;
        data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_exceeds) };
        return data;
    }
    // step 2: upload zip file to upgrade service and get token
    BasicHttpSyncer h = new BasicHttpSyncer(null, null);
    // note: server doesn't expect it to be gzip compressed, because the zip file is compressed
    // enable cancelling
    publishProgress(R.string.upgrade_decks_upload, null, true);
    try {
        HttpResponse resp = h.req("upgrade/upload", new FileInputStream(zipFile), 0, false, null,
                mCancelCallback);
        if (resp == null && !isCancelled()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        String result;
        String key = null;
        if (!isCancelled()) {
            result = h.stream2String(resp.getEntity().getContent());
            if (result != null && result.startsWith("ok:")) {
                key = result.split(":")[1];
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
        }
        while (!isCancelled()) {
            result = h.stream2String(h.req("upgrade/status?key=" + key).getEntity().getContent());
            if (result.equals("error")) {
                data.success = false;
                data.data = new Object[] { "error" };
                return data;
            } else if (result.startsWith("waiting:")) {
                publishProgress(R.string.upgrade_decks_upload, result.split(":")[1]);
            } else if (result.equals("upgrading")) {
                publishProgress(new Object[] { R.string.upgrade_decks_upgrade_started });
            } else if (result.equals("ready")) {
                break;
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
            Thread.sleep(1000);
        }
        // step 4: fetch upgraded file. this will return the .anki2 file directly, with
        // gzip compression if the client says it can handle it
        if (!isCancelled()) {
            publishProgress(new Object[] { R.string.upgrade_decks_downloading });
            resp = h.req("upgrade/download?key=" + key, null, 6, true, null, mCancelCallback);
            // uploads/downloads have finished so disable cancelling
        }
        publishProgress(R.string.upgrade_decks_downloading, null, false);
        if (isCancelled()) {
            return null;
        }
        if (resp == null) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        // step 5: check the received file is valid
        InputStream cont = resp.getEntity().getContent();
        if (!h.writeToFile(cont, colFilename)) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_sdcard,
                    new File(colFilename).length() / 1048576 + 1) };
            (new File(colFilename)).delete();
            return data;
        }
        // check the received file is ok
        publishProgress(new Object[] { R.string.sync_check_download_file });
        publishProgress(R.string.sync_check_download_file);
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colFilename);
            if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
                data.success = false;
                data.data = new Object[] { sContext.getResources() };
                return data;
            }
        } finally {
            AnkiDatabaseManager.closeDatabase(colFilename);
        }
        Collection col = AnkiDroidApp.openCollection(colFilename);
        ArrayList<String> decks = col.getDecks().allNames(false);
        ArrayList<String> failed = new ArrayList<String>();
        ArrayList<File> mediaDirs = new ArrayList<File>();
        for (File f : fileList) {
            String name = f.getName().replaceFirst("\\.anki$", "");
            if (!decks.contains(name)) {
                failed.add(name);
            } else {
                mediaDirs.add(new File(f.getAbsolutePath().replaceFirst("\\.anki$", ".media")));
            }
        }
        File newMediaDir = new File(col.getMedia().getDir());

        // step 6. move media files to new media directory
        publishProgress(new Object[] { R.string.upgrade_decks_media });
        ArrayList<String> failedMedia = new ArrayList<String>();
        File curMediaDir = null;
        for (File mediaDir : mediaDirs) {
            curMediaDir = mediaDir;
            // Check if media directory exists and is local
            if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                // If not try finding it in dropbox 1.2.x
                curMediaDir = new File(AnkiDroidApp.getDropboxDir(), mediaDir.getName());
                if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                    // No media for this deck
                    continue;
                }
            }
            // Found media dir, copy files
            for (File m : curMediaDir.listFiles()) {
                try {
                    Utils.copyFile(m, new File(newMediaDir, m.getName()));
                } catch (IOException e) {
                    failedMedia.add(curMediaDir.getName().replaceFirst("\\.media$", ".anki"));
                    break;
                }
            }
        }

        data.data = new Object[] { failed, failedMedia, newMediaDir.getAbsolutePath() };
        data.success = true;
        return data;
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        (new File(zipFilename)).delete();
    }
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String[] exportSelectedMappings(String[] selectedMappings) {
    String[] cleanedSelectedMappings = cleanSelectedMappings(selectedMappings);
    String msg = "";
    String[] returnStr = new String[2];
    String path = null;/*from   www  . j  a v a2s. c  o m*/

    try {
        byte[] buffer = new byte[1024];
        String sourceDirectory = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER
                + File.separator;
        String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
                + File.separator;
        String suffix = ".mapping.json";
        String zipFile = tempFolderName + "exported-mappings_" + (new Date()).getTime() + ".zip";

        (new File(tempFolderName)).mkdirs();

        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);
        File dir = new File(sourceDirectory);

        if (!dir.isDirectory()) {
            System.out.println(sourceDirectory + " is not a directory");
        } else {
            File[] files = dir.listFiles();
            String mappings = "";

            if (files.length == 0) {
                msg = Context.getMessageSourceService()
                        .getMessage("dhisconnector.exportMapping.noMappingsFound");
            } else {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith(suffix)) {
                        FileInputStream fin = new FileInputStream(files[i]);

                        mappings += files[i].getName() + "<:::>";
                        System.out.println("Compressing " + files[i].getName());
                        if (cleanedSelectedMappings.length == 0) {
                            copyToZip(buffer, zout, files, i, fin);
                        } else {
                            if (selectedMappingsIncludes(cleanedSelectedMappings, files[i].getName())) {
                                copyToZip(buffer, zout, files, i, fin);
                            }
                        }
                        msg = Context.getMessageSourceService()
                                .getMessage("dhisconnector.exportMapping.success");
                        zout.closeEntry();
                        fin.close();
                    }
                }
                if (mappings.split("<:::>").length == 0) {
                    msg = Context.getMessageSourceService()
                            .getMessage("dhisconnector.exportMapping.noMappingsFound");
                }
                path = zipFile;
            }
        }
        zout.close();
        System.out.println("Zip file has been created!");
    } catch (IOException e) {
        e.printStackTrace();
    }
    returnStr[0] = msg;
    returnStr[1] = path;
    return returnStr;
}

From source file:au.org.ala.biocache.service.DownloadService.java

/**
 * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc.
 * //w  w w . ja  v  a  2s.c om
 * @param dd
 * @param requestParams
 * @param ip
 * @param out
 * @param includeSensitive
 * @param fromIndex
 * @throws Exception
 */
private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip,
        OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception {

    String filename = requestParams.getFile();
    String originalParams = requestParams.toString();
    //Use a zip output stream to include the data and citation together in the download
    ZipOutputStream zop = new ZipOutputStream(out);
    String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType();
    zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix));
    //put the facets
    if ("all".equals(requestParams.getQa())) {
        requestParams.setFacets(new String[] { "assertions", "data_resource_uid" });
    } else {
        requestParams.setFacets(new String[] { "data_resource_uid" });
    }
    Map<String, Integer> uidStats = null;
    try {
        if (fromIndex)
            uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit);
        else
            uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        unregisterDownload(dd);
    }
    zop.closeEntry();

    //add the Readme for the data field descriptions
    zop.putNextEntry(new java.util.zip.ZipEntry("README.html"));
    zop.write(("For more information about the fields that are being downloaded please consult <a href='"
            + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes());

    //add the readme for the Shape file header mappings if necessary
    if (dd.getHeaderMap() != null) {
        zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html"));
        zop.write(
                ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:")
                        .getBytes());
        zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes());
        for (String key : dd.getHeaderMap().keySet()) {
            zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes());
        }
        zop.write(("</table>").getBytes());
        //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd));
    }

    //Add the data citation to the download
    if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) {
        //add the citations for the supplied uids
        zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv"));
        try {
            getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        zop.closeEntry();
    } else {
        logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats);
    }
    zop.flush();
    zop.close();

    //now construct the sourceUrl for the log event
    String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString()
            : webservicesRoot + "?" + originalParams;

    //logger.debug("UID stats : " + uidStats);
    //log the stats to ala logger        
    LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(),
            requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl);
    logger.log(RestLevel.REMOTE, vo);
}

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

/** Called when the activity is first created. */
@Override/* w w  w.ja  v  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);
}