Example usage for java.util.zip ZipFile entries

List of usage examples for java.util.zip ZipFile entries

Introduction

In this page you can find the example usage for java.util.zip ZipFile entries.

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

From source file:fr.certu.chouette.exchange.xml.neptune.importer.XMLNeptuneImportLinePlugin.java

/**
 * import ZipFile//from w ww. j av  a 2 s  . c  om
 * 
 * @param filePath
 *           path to zip File
 * @param validate
 *           process XML and XSD format validation
 * @param importReport
 *           report to fill
 * @param optimizeMemory
 * @param unsharedData
 * @param sharedData
 * @return list of loaded lines
 */
private List<Line> processZipImport(String filePath, boolean validate, Report importReport,
        Report validationReport, boolean optimizeMemory, SharedImportedData sharedData,
        UnsharedImportedData unsharedData) {
    ZipFile zip = null;
    try {
        Charset encoding = FileTool.getZipCharset(filePath);
        if (encoding == null) {
            ReportItem item = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    filePath, "unknown encoding");
            importReport.addItem(item);
            importReport.updateStatus(Report.STATE.ERROR);
            logger.error("zip import failed (unknown encoding)");
            return null;
        }
        zip = new ZipFile(filePath);
    } catch (IOException e) {
        // report for save
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        importReport.addItem(fileErrorItem);
        // log
        logger.error("zip import failed (cannot open zip)" + e.getLocalizedMessage());
        return null;
    }
    List<Line> lines = new ArrayList<Line>();
    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();

        // ignore directory without warning
        if (entry.isDirectory())
            continue;

        String entryName = entry.getName();
        if (!FilenameUtils.getExtension(entryName).toLowerCase().equals("xml")) {
            // report for save
            ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                    Report.STATE.OK, entryName);
            importReport.addItem(fileReportItem);
            // log
            logger.info("zip entry " + entryName + " bypassed ; not a XML file");
            continue;
        }
        logger.info("start import zip entry " + entryName);
        ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE, Report.STATE.OK,
                entryName);
        importReport.addItem(fileReportItem);
        try {
            InputStream stream = zip.getInputStream(entry);
            stream.close();
        } catch (IOException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (get entry)" + e.getLocalizedMessage());
            continue;
        }
        ChouettePTNetworkHolder holder = null;
        try {
            holder = reader.read(zip, entry, validate);
            validationReport.addItem(holder.getReport());
        } catch (ExchangeRuntimeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (read XML)" + e.getLocalizedMessage());
            continue;
        } catch (Exception e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(e.getLocalizedMessage());
            continue;
        }
        try {
            Line line = processImport(holder, validate, fileReportItem, validationReport, entryName, sharedData,
                    unsharedData, optimizeMemory);

            if (line != null) {
                lines.add(line);
            } else {
                logger.error("zip entry " + entryName + " import failed (build model)");
            }

        } catch (ExchangeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(
                    "zip entry " + entryName + " import failed (convert to model)" + e.getLocalizedMessage());
            continue;
        }
        logger.info("zip entry imported");
    }
    try {
        zip.close();
    } catch (IOException e) {
        logger.info("cannot close zip file");
    }
    if (lines.size() == 0) {
        logger.error("zip import failed (no valid entry)");
        return null;
    }
    return lines;
}

From source file:fr.certu.chouette.gui.command.ImportCommand.java

/**
 * @param session//from  www.  j ava2  s .c o m
 * @param save
 * @param savedIds
 * @param manager
 * @param importTask
 * @param format
 * @param inputFile
 * @param suffixes
 * @param values
 * @param importHolder
 * @param validationHolder
 * @throws ChouetteException
 */
private int importZipEntries(EntityManager session, boolean save, List<Long> savedIds,
        INeptuneManager<NeptuneIdentifiedObject> manager, ImportTask importTask, String format,
        String inputFile, List<String> suffixes, List<ParameterValue> values, ReportHolder importHolder,
        ReportHolder validationHolder) throws ChouetteException {
    SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
    values.add(inputFileParam);

    ReportHolder zipHolder = new ReportHolder();
    if (format.equalsIgnoreCase("neptune")) {
        SharedImportedData sharedData = new SharedImportedData();
        UnsharedImportedData unsharedData = new UnsharedImportedData();
        SimpleParameterValue sharedDataParam = new SimpleParameterValue("sharedImportedData");
        sharedDataParam.setObjectValue(sharedData);
        values.add(sharedDataParam);
        SimpleParameterValue unsharedDataParam = new SimpleParameterValue("unsharedImportedData");
        unsharedDataParam.setObjectValue(unsharedData);
        values.add(unsharedDataParam);
    }

    // unzip files , import and save contents
    ZipFile zip = null;
    File temp = null;
    File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importTask.getId());
    if (!tempRep.exists())
        tempRep.mkdirs();
    File zipFile = new File(inputFile);
    ReportItem zipReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_FILE, Report.STATE.OK,
            zipFile.getName());
    try {
        Charset encoding = FileTool.getZipCharset(inputFile);
        if (encoding == null) {
            ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR,
                    Report.STATE.ERROR, "unknown encoding");
            zipReportItem.addItem(fileErrorItem);
            importHolder.getReport().addItem(zipReportItem);
            saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
            return 1;
        }
        zip = new ZipFile(inputFile, encoding);
        zipHolder.setReport(zipReportItem);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                File dir = new File(tempRep, entry.getName());
                dir.mkdirs();
                continue;
            }
            if (!FilenameUtils.isExtension(entry.getName().toLowerCase(), suffixes)) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                        Report.STATE.OK, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.info("entry " + entry.getName() + " ignored, unknown extension");
                continue;
            }
            InputStream stream = null;
            try {
                stream = zip.getInputStream(entry);
            } catch (IOException e) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR,
                        Report.STATE.WARNING, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.error("entry " + entry.getName() + " cannot read", e);
                continue;
            }
            byte[] bytes = new byte[4096];
            int len = stream.read(bytes);
            temp = new File(tempRep.getAbsolutePath() + "/" + entry.getName());
            FileOutputStream fos = new FileOutputStream(temp);
            while (len > 0) {
                fos.write(bytes, 0, len);
                len = stream.read(bytes);
            }
            fos.close();

            // import
            log.info("import file " + entry.getName());
            inputFileParam.setFilepathValue(temp.getAbsolutePath());
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, zipHolder,
                    validationHolder);
            if (beans != null && !beans.isEmpty()) {
                // save
                if (save) {
                    saveBeans(manager, beans, savedIds, importHolder.getReport());
                } else {
                    for (NeptuneIdentifiedObject bean : beans) {
                        GuiReportItem item = new GuiReportItem(GuiReportItem.KEY.NO_SAVE, Report.STATE.OK,
                                bean.getName());
                        importHolder.getReport().addItem(item);
                    }

                }
            }
            temp.delete();
        }
        try {
            zip.close();
        } catch (IOException e) {
            log.info("cannot close zip file");
        }
        importHolder.getReport().addItem(zipReportItem);
    } catch (IOException e) {
        log.error("IO error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } catch (IllegalArgumentException e) {
        log.error("Format error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } finally {
        try {
            FileUtils.deleteDirectory(tempRep);
        } catch (IOException e) {
            log.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
        }
    }
    return 0;
}

From source file:com.htmlhifive.tools.wizard.download.DownloadModule.java

/**
 * ?./*from ww w  . j  a v a  2  s . co  m*/
 * 
 * @param monitor 
 * @param totalTask 
 * @param logger 
 * @param baseProject 
 * @param proj 
 * @throws CoreException 
 */
public void downloadProject(IProgressMonitor monitor, int totalTask, ResultStatus logger,
        BaseProject baseProject, IProject proj) throws CoreException {

    // ??400work.
    int perLibWork = totalTask;

    // SE0063=INFO,ZIP???
    logger.log(Messages.SE0063);

    // ??
    // ?????????.
    defaultOverwriteMode = 1;

    String siteUrl = baseProject.getUrl();
    String path = H5IOUtils.getURLPath(siteUrl);
    if (path == null) {
        logger.log(Messages.SE0082, baseProject.getUrl());
        logger.setSuccess(false);
        throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(),
                Messages.SE0082.format(baseProject.getUrl())));
    }

    final ZipFile zipFile;
    //try {
    //URI uri = new URI(baseProject.getUrl());
    zipFile = download(monitor, totalTask, logger, null, siteUrl);
    //} catch (URISyntaxException e) {
    //throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0013.format(), e));
    //}

    perLibWork = perLibWork - 100;
    if (!lastDownloadStatus) {
        // .
        logger.log(Messages.SE0068);
        logger.setSuccess(false);
        throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0068.format()));
    }

    // SE0064=INFO,ZIP????
    logger.log(Messages.SE0064);

    // .
    //proj.refreshLocal(IResource.DEPTH_ONE, monitor);
    //logger.log(Messages.SE0101);

    // ?
    int perExtractWork = Math.max(1, perLibWork / zipFile.size());
    for (Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); enumeration.hasMoreElements();) {
        final ZipEntry zipEntry = enumeration.nextElement();

        // PI0113=INFO,[{0}]...
        monitor.subTask(Messages.PI0113.format(zipEntry.getName()));

        if (zipEntry.isDirectory()) {
            // 
            IFolder iFolder = proj.getFolder(zipEntry.getName());
            if (!iFolder.exists()) {
                logger.log(Messages.SE0091, iFolder.getFullPath());
                H5IOUtils.createParentFolder(iFolder, null);
                logger.log(Messages.SE0092, iFolder.getFullPath());
            }
        } else {
            // 
            IFile iFile = proj.getFile(zipEntry.getName());

            // ?.
            try {
                updateFile(monitor, 0, logger, iFile, new ZipFileContentsHandler(zipFile, zipEntry));
            } catch (IOException e) {
                throw new CoreException(
                        new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0068.format(), e));
            }
        }
        monitor.worked(perExtractWork);
    }

    // //  ZIP???????.
    // H5StringUtils.log(getShell(), null, Messages.SE0043,
    // Messages.SE0045.format(site.getFile()));

    // ??.
    defaultOverwriteMode = 0;

    logger.log(Messages.SE0070);
}

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

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

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

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

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

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

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

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

        inputProperties.store(propertyFileWriter, null);

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

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

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

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

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

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

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

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Extract zip data.//from   w  w  w  .ja  v  a  2s .c om
 * 
 * @param zipData An input stream that represents a zipped file.
 * @return True if finished.
 */
public boolean syncAdd(File zipData) {
    boolean finished = false;
    ZipFile z = null;
    ArrayList<Object[]> media = new ArrayList<Object[]>();
    long sizecnt = 0;
    JSONObject meta = null;
    int nextUsn = 0;
    try {
        z = new ZipFile(zipData, ZipFile.OPEN_READ);
        // get meta info first
        ZipEntry metaEntry = z.getEntry("_meta");
        // if (metaEntry.getSize() >= 100000) {
        // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")");
        // return false;
        // }
        meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry)));
        ZipEntry usnEntry = z.getEntry("_usn");
        String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry));
        nextUsn = Integer.parseInt(usnstr);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (ZipException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Then loop through all files
    for (ZipEntry zentry : Collections.list(z.entries())) {
        // Check for zip bombs
        sizecnt += zentry.getSize();
        if (sizecnt > 100 * 1024 * 1024) {
            Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping");
            return false;
        }
        if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) {
            // Ignore previously retrieved meta
            continue;
        } else if (zentry.getName().compareTo("_finished") == 0) {
            finished = true;
        } else {
            String name = meta.optString(zentry.getName());
            if (illegal(name)) {
                continue;
            }
            String path = getDir().concat(File.separator).concat(name);
            try {
                Utils.writeToFile(z.getInputStream(zentry), path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String csum = Utils.fileChecksum(path);
            // append db
            media.add(new Object[] { name, csum, _mtime(name) });
            mMediaDb.execute("delete from log where fname = ?", new String[] { name });
        }
    }

    // update media db and note new starting usn
    if (!media.isEmpty()) {
        mMediaDb.executeMany("insert or replace into media values (?,?,?)", media);
    }
    setUsn(nextUsn); // commits
    // if we have finished adding, we need to record the new folder mtime
    // so that we don't trigger a needless scan
    if (finished) {
        syncMod();
    }
    return finished;
}

From source file:org.dspace.app.itemimport.ItemImportServiceImpl.java

@Override
public String unzip(File zipfile, String destDir) throws IOException {
    // 2/*www.  jav  a2 s. c  om*/
    // does the zip file exist and can we write to the temp directory
    if (!zipfile.canRead()) {
        log.error("Zip file '" + zipfile.getAbsolutePath() + "' does not exist, or is not readable.");
    }

    String destinationDir = destDir;
    if (destinationDir == null) {
        destinationDir = tempWorkDir;
    }

    File tempdir = new File(destinationDir);
    if (!tempdir.isDirectory()) {
        log.error("'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir")
                + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg "
                + "is not a valid directory");
    }

    if (!tempdir.exists() && !tempdir.mkdirs()) {
        log.error("Unable to create temporary directory: " + tempdir.getAbsolutePath());
    }
    String sourcedir = destinationDir + System.getProperty("file.separator") + zipfile.getName();
    String zipDir = destinationDir + System.getProperty("file.separator") + zipfile.getName()
            + System.getProperty("file.separator");

    // 3
    String sourceDirForZip = sourcedir;
    ZipFile zf = new ZipFile(zipfile);
    ZipEntry entry;
    Enumeration<? extends ZipEntry> entries = zf.entries();
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        if (entry.isDirectory()) {
            if (!new File(zipDir + entry.getName()).mkdirs()) {
                log.error("Unable to create contents directory: " + zipDir + entry.getName());
            }
        } else {
            System.out.println("Extracting file: " + entry.getName());
            log.info("Extracting file: " + entry.getName());

            int index = entry.getName().lastIndexOf('/');
            if (index == -1) {
                // Was it created on Windows instead?
                index = entry.getName().lastIndexOf('\\');
            }
            if (index > 0) {
                File dir = new File(zipDir + entry.getName().substring(0, index));
                if (!dir.exists() && !dir.mkdirs()) {
                    log.error("Unable to create directory: " + dir.getAbsolutePath());
                }

                //Entries could have too many directories, and we need to adjust the sourcedir
                // file1.zip (SimpleArchiveFormat / item1 / contents|dublin_core|...
                //            SimpleArchiveFormat / item2 / contents|dublin_core|...
                // or
                // file2.zip (item1 / contents|dublin_core|...
                //            item2 / contents|dublin_core|...

                //regex supports either windows or *nix file paths
                String[] entryChunks = entry.getName().split("/|\\\\");
                if (entryChunks.length > 2) {
                    if (StringUtils.equals(sourceDirForZip, sourcedir)) {
                        sourceDirForZip = sourcedir + "/" + entryChunks[0];
                    }
                }

            }
            byte[] buffer = new byte[1024];
            int len;
            InputStream in = zf.getInputStream(entry);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(zipDir + entry.getName()));
            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
        }
    }

    //Close zip file
    zf.close();

    if (!StringUtils.equals(sourceDirForZip, sourcedir)) {
        sourcedir = sourceDirForZip;
        System.out.println("Set sourceDir using path inside of Zip: " + sourcedir);
        log.info("Set sourceDir using path inside of Zip: " + sourcedir);
    }

    return sourcedir;
}

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

/** Called when the activity is first created. */
@Override// w  ww  . j av  a  2  s .c  om
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:com.app.server.WarDeployer.java

/**
 * This method deploys the war in exploded form and configures it.
 * /*from ww w  . j  a v  a2 s.co m*/
 * @param file
 * @param customClassLoader
 * @param warDirectoryPath
 */
public void extractWar(File file, ClassLoader classLoader) {

    StringBuffer classPath = new StringBuffer();
    int numBytes;
    WebClassLoader customClassLoader = null;
    CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>();
    try {
        ConcurrentHashMap jspMap = new ConcurrentHashMap();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        // String fileName=file.getName();
        String directoryName = file.getName();
        directoryName = directoryName.substring(0, directoryName.indexOf('.'));
        try {
            /*ClassLoader classLoader = Thread.currentThread()
                  .getContextClassLoader();*/
            // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
            jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"));
            // new WebServer().addURL(new
            // URL("file://"+warDirectoryPath+"/"),customClassLoader);
        } catch (Exception e) {
            log.error("syntax of the URL is incorrect", e);
            //e1.printStackTrace();
        }
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //log.info("Unzipping " + ze.getName());
            String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //log.info(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jsp")) {
                    jspMap.put(ze.getName(), filePath);
                } else if (ze.getName().endsWith(".jar")) {
                    jarUrls.add(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()));
                    classPath.append(filePath);
                    classPath.append(";");
                }
            }
        }
        zip.close();
        Set jsps = jspMap.keySet();
        Iterator jspIterator = jsps.iterator();
        classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes;");
        jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;"));
        ArrayList<String> jspFiles = new ArrayList();
        // log.info(classPath.toString());
        if (jspIterator.hasNext()) {
            jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"));
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
            while (jspIterator.hasNext()) {
                String filepackageInternal = (String) jspIterator.next();
                String filepackageInternalTmp = filepackageInternal;
                if (filepackageInternal.lastIndexOf('/') == -1) {
                    filepackageInternal = "";
                } else {
                    filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/'))
                            .replace("/", ".");
                    filepackageInternal = "." + filepackageInternal;
                }
                createDirectory(scanDirectory + "/temp/" + directoryName);
                File jspFile = new File((String) jspMap.get(filepackageInternalTmp));
                String fName = jspFile.getName();
                String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp";
                // String fileCreated=new JspCompiler().compileJsp((String)
                // jspMap.get(filepackageInternalTmp),
                // scanDirectory+"/temp/"+fileName,
                // "com.app.server"+filepackageInternal,classPath.toString());
                synchronized (customClassLoader) {
                    String fileNameInWar = filepackageInternalTmp;
                    jspFiles.add(fileNameInWar.replace("/", "\\"));
                    if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                        customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                                "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                        + fileNameWithoutExtension);
                    } else {
                        customClassLoader.addURL("/" + fileNameInWar,
                                "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                        + fileNameWithoutExtension);
                    }
                }
            }
        } else {
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
        }
        String filePath = file.getAbsolutePath();
        // log.info("filePath"+filePath);
        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
        urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader);
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            //Thread.currentThread().setContextClassLoader(customClassLoader);
            String classPathBefore = "";
            try {
                JspCompiler jspc = new JspCompiler();
                jspc.setUriroot(scanDirectory + "/" + directoryName);
                jspc.setAddWebXmlMappings(false);
                jspc.setListErrors(false);
                jspc.setCompile(true);
                jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                jspc.setPackage("com.app.server");
                StringBuffer buffer = new StringBuffer();
                for (String jspFile : jspFiles) {
                    buffer.append(",");
                    buffer.append(jspFile);
                }
                String jsp = buffer.toString();
                jsp = jsp.substring(1, jsp.length());
                //log.info(jsp);
                classPathBefore = System.getProperty("java.class.path");
                System.setProperty("java.class.path",
                        System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\"));
                //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\"));
                jspc.setJspFiles(jsp);
                jspc.initCL(customClassLoader);
                jspc.execute();
                //jspc.closeClassLoader();
                //jspc.closeClassLoader();
            } catch (Throwable je) {
                log.error("Error in compiling the jsp page", je);
                //je.printStackTrace();
            } finally {
                System.setProperty("java.class.path", classPathBefore);
                //Thread.currentThread().setContextClassLoader(oldCL);
            }
            //Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        try {
            File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml");
            if (execxml.exists()) {
                new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml,
                        customClassLoader);
            }
        } catch (Exception e) {
            log.error("error in getting executor services ", e);
            // e.printStackTrace();
        }
        try {
            File messagingxml = new File(
                    scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml");
            if (messagingxml.exists()) {
                new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml,
                        customClassLoader, messagingClassMap);
            }
        } catch (Exception e) {
            log.error("Error in getting the messaging classes ", e);
            // e.printStackTrace();
        }
        webxmldigester.setNamespaceAware(true);
        webxmldigester.setValidating(true);
        // digester.setRules(null);
        FileInputStream webxml = new FileInputStream(
                scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml");
        InputSource is = new InputSource(webxml);
        try {
            //log.info("SCHEMA");
            synchronized (webxmldigester) {
                // webxmldigester.set("config/web-app_2_4.xsd");
                WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is);
                servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig);
            }
            webxml.close();
        } catch (Exception e) {
            log.error("Error in pasrsing the web.xml", e);
            //e.printStackTrace();
        }
        //customClassLoader.close();
        // ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (Exception ex) {
        log.error("Error in Deploying war " + file.getAbsolutePath(), ex);
    }
}

From source file:fr.certu.chouette.gui.command.Command.java

/**
 * import command :  ( -fileFormat utilis si l'extension du fichier n'est pas reprsentative du format)
 * -c import -o line -format XXX -inputFile YYYY [-fileFormat TTT] -importId ZZZ ... 
 * @param manager/*  ww  w.  j  a va2 s  .  com*/
 * @param parameters
 * @return
 */
private int executeImport(INeptuneManager<NeptuneIdentifiedObject> manager,
        Map<String, List<String>> parameters) {
    parameters.put("reportforsave", Arrays.asList(new String[] { "true" }));
    // parameters.put("validate",Arrays.asList(new String[]{"true"})); // force validation if possible

    GuiReport saveReport = new GuiReport("SAVE", Report.STATE.OK);
    Report importReport = null;

    List<Report> reports = new ArrayList<Report>();
    // check if import exists and accept unzip before call
    String format = getSimpleString(parameters, "format");
    String inputFile = getSimpleString(parameters, "inputfile");
    // String fileFormat = getSimpleString(parameters,"fileformat","");
    Long importId = Long.valueOf(getSimpleString(parameters, "importid"));
    if (!importDao.exists(importId)) {
        // error import not found
        logger.error("import not found " + importId);
        return 1;
    }
    GuiImport guiImport = importDao.get(importId);
    logger.info("Export data for export id " + importId);
    logger.info("  type : " + guiImport.getType());
    logger.info("  options : " + guiImport.getOptions());

    Referential referential = referentialDao.get(guiImport.getReferentialId());
    logger.info("Referential " + guiImport.getReferentialId());
    logger.info("  name : " + referential.getName());
    logger.info("  slug : " + referential.getSlug());
    logger.info("  projection type : " + referential.getProjectionType());

    String projectionType = null;
    if (referential.getProjectionType() != null && !referential.getProjectionType().isEmpty()) {
        logger.info("  projection type for export: " + referential.getProjectionType());
        projectionType = referential.getProjectionType();
        parameters.put("srid", Arrays.asList(new String[] { projectionType }));
    }
    // set projection for import (inactive if not set)
    geographicService.switchProjection(projectionType);

    int beanCount = 0;

    boolean zipped = (inputFile.toLowerCase().endsWith(".zip"));

    try {
        List<FormatDescription> formats = manager.getImportFormats(null);
        FormatDescription description = null;

        for (FormatDescription formatDescription : formats) {
            if (formatDescription.getName().equalsIgnoreCase(format)) {
                description = formatDescription;
                break;
            }
        }
        if (description == null) {
            throw new IllegalArgumentException("format " + format + " unavailable");
        }
        List<String> suffixes = new ArrayList<String>();
        for (ParameterDescription desc : description.getParameterDescriptions()) {
            if (desc.getName().equalsIgnoreCase("inputfile")) {
                suffixes = desc.getAllowedExtensions();
                break;
            }
        }
        List<ParameterValue> values = populateParameters(description, parameters, "inputfile", "fileformat");
        if (zipped && description.isUnzipAllowed()) {
            SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
            values.add(inputFileParam);
            // unzip files , import and save contents 
            ZipFile zip = null;
            File temp = null;
            File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importId);
            if (!tempRep.exists())
                tempRep.mkdirs();
            try {

                zip = new ZipFile(inputFile);
                for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
                    ZipEntry entry = entries.nextElement();

                    if (entry.isDirectory()) {
                        File dir = new File(tempRep, entry.getName());
                        dir.mkdirs();
                        continue;
                    }
                    if (!FilenameUtils.isExtension(entry.getName().toLowerCase(), suffixes)) {
                        logger.error("entry " + entry.getName() + " ignored, unknown extension");
                        continue;
                    }
                    InputStream stream = null;
                    try {
                        stream = zip.getInputStream(entry);
                    } catch (IOException e) {
                        logger.error("entry " + entry.getName() + " cannot read");
                        continue;
                    }
                    byte[] bytes = new byte[4096];
                    int len = stream.read(bytes);
                    temp = new File(tempRep, entry.getName());
                    FileOutputStream fos = new FileOutputStream(temp);
                    while (len > 0) {
                        fos.write(bytes, 0, len);
                        len = stream.read(bytes);
                    }
                    fos.close();

                    // import
                    if (verbose)
                        System.out.println("import file " + entry.getName());
                    logger.info("import file " + entry.getName());
                    inputFileParam.setFilepathValue(temp.getAbsolutePath());
                    ReportHolder holder = new ReportHolder();
                    List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, holder);
                    if (holder.getReport() != null) {
                        if (importReport == null) {
                            importReport = holder.getReport();
                            reports.add(importReport);
                        } else {
                            importReport.addAll(holder.getReport().getItems());
                        }

                    }
                    // save
                    if (beans != null && !beans.isEmpty()) {

                        for (NeptuneIdentifiedObject bean : beans) {
                            if (verbose) {
                                System.out.println("save " + bean.getName() + " (" + bean.getObjectId() + ")");
                            }
                            logger.info("save " + bean.getName() + " (" + bean.getObjectId() + ")");
                            // check all stopareas
                            if (bean instanceof Line) {
                                Line line = (Line) bean;
                                checkProjection(line);
                            }
                        }
                        try {
                            manager.saveAll(null, beans, true, true);
                            for (NeptuneIdentifiedObject bean : beans) {
                                GuiReportItem item = new GuiReportItem("SAVE_OK", Report.STATE.OK,
                                        bean.getName());
                                importReport.addItem(item);
                                beanCount++;
                            }
                        } catch (Exception e) {
                            logger.error("fail to save data :" + e.getMessage(), e);
                            for (NeptuneIdentifiedObject bean : beans) {
                                GuiReportItem item = new GuiReportItem("SAVE_ERROR", Report.STATE.ERROR,
                                        bean.getName(), filter_chars(e.getMessage()));
                                importReport.addItem(item);
                            }
                        }
                    }
                    temp.delete();
                }
                try {
                    zip.close();
                } catch (IOException e) {
                    logger.info("cannot close zip file");
                }
            } catch (IOException e) {
                //reports.add(saveReport);
                System.out.println("import failed " + e.getMessage());
                logger.error("import failed " + e.getMessage(), e);
                saveImportReports(importId, format, reports);
                return 1;
            } finally {
                try {
                    FileUtils.deleteDirectory(tempRep);
                } catch (IOException e) {
                    logger.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
                }
            }

        } else {
            SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
            inputFileParam.setFilepathValue(inputFile);
            values.add(inputFileParam);
            //            if (!fileFormat.isEmpty())
            //            {
            //               SimpleParameterValue fileFormatParam = new SimpleParameterValue("fileFormat");
            //               fileFormatParam.setStringValue(fileFormat);
            //               values.add(fileFormatParam);
            //            }
            // surround with try catch 
            ReportHolder holder = new ReportHolder();
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, holder);
            if (holder.getReport() != null) {
                importReport = holder.getReport();
                reports.add(holder.getReport());
            }
            logger.info("imported Lines " + beans.size());

            for (NeptuneIdentifiedObject bean : beans) {
                if (bean instanceof Line) {
                    Line line = (Line) bean;
                    checkProjection(line);
                }
                List<NeptuneIdentifiedObject> oneBean = new ArrayList<NeptuneIdentifiedObject>();
                oneBean.add(bean);
                try {
                    logger.info("save  Line " + bean.getName());
                    manager.saveAll(null, oneBean, true, true);
                    GuiReportItem item = new GuiReportItem("SAVE_OK", Report.STATE.OK, bean.getName());
                    saveReport.addItem(item);
                    beanCount++;
                } catch (Exception e) {
                    logger.error("save failed " + e.getMessage(), e);
                    GuiReportItem item = new GuiReportItem("SAVE_ERROR", Report.STATE.ERROR, bean.getName(),
                            e.getMessage());
                    saveReport.addItem(item);
                }
            }
        }
    } catch (Exception e) {
        // fill report with error
        if (saveReport.getItems() != null && !saveReport.getItems().isEmpty())
            reports.add(saveReport);
        String msg = e.getMessage();
        if (msg == null)
            msg = e.getClass().getName();
        System.out.println("import failed " + msg);
        logger.error("import failed " + msg, e);
        GuiReport errorReport = new GuiReport("IMPORT_ERROR", Report.STATE.ERROR);
        GuiReportItem item = new GuiReportItem("EXCEPTION", Report.STATE.ERROR, msg);
        errorReport.addItem(item);
        reports.add(errorReport);
        saveImportReports(importId, format, reports);

        return 1;
    }
    if (saveReport.getItems() != null && !saveReport.getItems().isEmpty())
        reports.add(saveReport);
    saveImportReports(importId, format, reports);
    return (beanCount == 0 ? 1 : 0);

}