Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:com.pari.pcb.zip.ZIPProcessor.java

public void process(boolean blocking) {
    tmpRoot = new File("TEMP" + File.separator + "ZIP_TMP_" + System.nanoTime());
    tmpRoot.mkdirs();//from ww  w  .  j a  va2s . c o  m
    long start = System.currentTimeMillis();
    if (!zipFile.exists()) {
        errMsg = "File " + fileName + " does not exist";
        setCompleted();
        return;
    }
    if (!zipFile.canRead()) {
        errMsg = "Unable to read the contents of the file " + fileName;
        setCompleted();
        return;
    }
    try {
        ZipFile inZip = new ZipFile(zipFile);
        numEntries = inZip.size();

        Enumeration<? extends ZipEntry> entryEnumeration = inZip.entries();
        if (numEntries == 0) {
            errMsg = "Empty ZIP file.";
            setCompleted();
            return;
        }
        while (entryEnumeration.hasMoreElements()) {
            ZipEntry entry = entryEnumeration.nextElement();
            currentEntryName = entry.getName();
            if (entry.isDirectory()) {
                if (numEntries > 1) {
                    numEntries--;
                }
                continue;
            }
            currentEntryIdx++;
            if (currentEntryIdx % 100 == 0) {
                System.gc();
                NCCMObserver.getInstance().logMemoryUsage(
                        "After handling " + currentEntryIdx + " files in Zip Processor, Memory Usage");
            }
            InputStream ipStream = inZip.getInputStream(entry);
            String fileName = entry.getName();
            System.err.println("Processing file: " + fileName);

            String line = null;
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(ipStream));
                line = br.readLine();
                CharsetDetector detector = new CharsetDetector();
                if (entry.getSize() == 0) {
                    logger.error("No Contents found in the file");
                    continue;
                } else {
                    detector.setText(line.getBytes());
                    charset = Charset.forName(detector.detect().getName());
                }
            } catch (Exception ex) {
                logger.error("Error while getting the charset encoding of the file");
            } finally {
                try {
                    ipStream.close();
                } catch (Exception e) {
                    logger.error("Exception while closing the stream");
                }
            }
            ipStream = inZip.getInputStream(entry);

            processZipEntry(ipStream, fileName, entry, inZip);
            if (progressIf != null) {
                progressIf.updateProgress(currentEntryName, currentEntryIdx, numEntries);
            }
            if (fileResultMap.get(fileName) == null) {
                ZIPFileResult fr = new ZIPFileResult(fileName);
                fr.fileType = ZIPFileType.UNKNOWN;
                fr.msg = "Unable to process the file.";
                fileResultMap.put(fileName, fr);
            }
            try {
                ipStream.close();
            } catch (Exception ex) {
                logger.warn("Unable to close the inputstream for entry " + entry.getName(), ex);
                ex.printStackTrace();
            }
            if (isCancelled) {
                break;
            }
            if (!blocking) {
                Thread.sleep(100 /* msec */);
            }
            if (isCancelled) {
                break;
            }
        }
        if (!isCancelled) {
            processCatOsVersionFiles(inZip);
            processFileResult();
        }
        inZip.close();
    } catch (ZipException e) {
        errMsg = "File is not a valid Zip file";
        logger.error("Exception while processing ZipFile: " + fileName, e);
    } catch (IOException e) {
        errMsg = "Unable to parse Zip file ";
        logger.error("IOException while processing ZipFile: " + fileName, e);
    } catch (InterruptedException e) {
        errMsg = "Zip processing Interrupted internally.";
        logger.error("Interrupted while processing ZipFile: " + fileName, e);
    } catch (Exception e) {
        errMsg = "Exception while processing zip file.";
        logger.error("Exception while processing ZipFile: " + fileName, e);
    }

    logger.debug("Done with : " + numEntries + " in " + (System.currentTimeMillis() - start) + " msecs");
    String[] devNames = getDeviceNames();
    if (devNames == null || devNames.length == 0) {
        addWarning("No valid devices found in the specified Zip file.");
    }
    setCompleted();
    return;
}

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/*w w  w  .  jav a  2s . c om*/
 * @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);

}

From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java

private void installOFR(File ofr) throws IOException {
    ZipFile zipFile = null;
    try {//  w  w w .  j ava  2 s.co  m
        zipFile = new ZipFile(ofr);

        String packageXmlUploadedFile = null;
        String resourceZipUploadedFile = null;
        String codeWarUploadedFile = null;
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (PackageFileType.PACKAGE_XML.getOfrFileName().equals(entry.getName())) {
                packageXmlUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.PACKAGE_XML.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.RESOURCE_ZIP.getOfrFileName().equals(entry.getName())) {
                resourceZipUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.RESOURCE_ZIP.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.APP_WAR.getOfrFileName().equals(entry.getName())) {
                codeWarUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.APP_WAR.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            }
        }

        InputStream packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                packageXmlUploadedFile, helper.getTemp());
        InputStream resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                resourceZipUploadedFile, helper.getTemp());
        StatusProviderTranslationResult statusResult = packageInstallationService.activatePackage(packageXml,
                resourceZip);
        IOUtils.closeQuietly(packageXml);
        IOUtils.closeQuietly(resourceZip);

        if (statusResult.getResult() && statusResult.getPackage() != null) {
            PackageModel packageRN = statusResult.getPackage();
            if (packageRN != null) {
                Integer oldVersion = packageRN.getVersion();
                packageRN = packageStore.updatePackageVersion(packageRN.getId(),
                        statusResult.getVersionNumber());

                if (statusResult.getOldPackageXml() != null) {
                    packageVersionHelper.archiveVersion(packageRN, oldVersion, statusResult.getOldPackageXml());
                }

                String packageXmlName = packageRN.getName() + PackageFileType.PACKAGE_XML.getDotExtension();
                packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                        packageXmlUploadedFile, helper.getTemp());
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlName, packageXml,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(packageXml);

                if (resourceZipUploadedFile != null) {
                    String resourceZipName = packageRN.getName()
                            + PackageFileType.RESOURCE_ZIP.getDotExtension();
                    resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            resourceZipUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipName, resourceZip,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(resourceZip);
                }

                //                    File webapps = new File(Env.CATALINA_BASE.getValue(), "webapps");
                //                    if (codeWarUploadedFile != null && webapps.exists()) {
                //                        FileUtils.copyFile(codeWarUploadedFile, new File(webapps, packageRN.getName() + PackageFileType.APP_WAR.getDotExtension()));
                //                    }

                if (codeWarUploadedFile != null) {
                    String codeWarName = packageRN.getName() + PackageFileType.APP_WAR.getDotExtension();
                    InputStream warstream = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            codeWarUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarName, warstream,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(warstream);
                }

                String packageFilename = packageRN.getName() + PackageFileType.PACKAGE_OFR.getDotExtension();
                FileInputStream stream = new FileInputStream(ofr);
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageFilename, stream,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(stream);
            } else {
                throw new BusinessFunctionException("Package archive has not created.");
            }
        }
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
}

From source file:com.taobao.android.tools.TPatchTool.java

/**
 * ?patchpatchInfo//from w  w w  .  j av  a 2 s. c o  m
 *
 * @param fileName
 * @return
 */
public PatchInfo createBasePatchInfo(File file) {
    PatchInfo patchInfo = new PatchInfo();
    patchInfo.setPatchVersion(input.newApkBo.getVersionName());
    patchInfo.setTargetVersion(input.baseApkBo.getVersionName());
    patchInfo.setFileName(file.getName());
    Set<String> modifyBundles = new HashSet<>();
    ZipFile zipFile = newZipFile(file);
    Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = enumeration.nextElement();
        if (zipEntry.getName().startsWith("lib") && zipEntry.getName().indexOf("/") != -1) {
            modifyBundles
                    .add(zipEntry.getName().substring(3, zipEntry.getName().indexOf("/")).replace("_", "."));
        } else if (zipEntry.getName().endsWith(".so") && zipEntry.getName().indexOf("/") == -1) {
            modifyBundles.add(
                    zipEntry.getName().substring(3, zipEntry.getName().lastIndexOf(".")).replace("_", "."));
        }

    }

    for (ArtifactBundleInfo artifactBundleInfo : input.artifactBundleInfos) {
        if (artifactBundleInfo.getMainBundle()) {
            if (DiffType.MODIFY.equals(artifactBundleInfo.getDiffType()) || hasMainBundle) {
                PatchBundleInfo patchBundleInfo = new PatchBundleInfo();
                patchBundleInfo.setNewBundle(DiffType.ADD.equals(artifactBundleInfo.getDiffType()));
                patchBundleInfo.setMainBundle(true);
                patchBundleInfo.setVersion(artifactBundleInfo.getVersion());
                patchBundleInfo.setName(((TpatchInput) input).mainBundleName);
                patchBundleInfo.setSrcUnitTag(artifactBundleInfo.getSrcUnitTag());
                patchBundleInfo.setUnitTag(artifactBundleInfo.getUnitTag());
                patchBundleInfo.setPatchType(bundleTypes.get(((TpatchInput) input).mainBundleName) == null ? 0
                        : bundleTypes.get(((TpatchInput) input).mainBundleName));
                patchBundleInfo.setApplicationName(artifactBundleInfo.getApplicationName());
                patchBundleInfo.setArtifactId(artifactBundleInfo.getArtifactId());
                patchBundleInfo.setPkgName(artifactBundleInfo.getPkgName());
                patchBundleInfo.setDependency(artifactBundleInfo.getDependency());
                patchBundleInfo.setBaseVersion(artifactBundleInfo.getBaseVersion());
                patchInfo.getBundles().add(patchBundleInfo);
                continue;
            }
        } else if (DiffType.MODIFY.equals(artifactBundleInfo.getDiffType())
                || DiffType.ADD.equals(artifactBundleInfo.getDiffType())) {
            PatchBundleInfo patchBundleInfo = new PatchBundleInfo();
            patchBundleInfo.setNewBundle(DiffType.ADD.equals(artifactBundleInfo.getDiffType()));
            patchBundleInfo.setMainBundle(false);
            patchBundleInfo.setSrcUnitTag(artifactBundleInfo.getSrcUnitTag());
            patchBundleInfo.setUnitTag(artifactBundleInfo.getUnitTag());
            patchBundleInfo.setVersion(artifactBundleInfo.getVersion());
            patchBundleInfo.setPatchType(bundleTypes.get(artifactBundleInfo.getPkgName()) == null ? 0
                    : bundleTypes.get(artifactBundleInfo.getPkgName()));
            patchBundleInfo.setName(artifactBundleInfo.getPkgName());
            if (!modifyBundles.contains(artifactBundleInfo.getPkgName().replace("_", "."))) {
                patchBundleInfo.setInherit(true);
            }
            patchBundleInfo.setApplicationName(artifactBundleInfo.getApplicationName());
            patchBundleInfo.setArtifactId(artifactBundleInfo.getArtifactId());
            patchBundleInfo.setPkgName(artifactBundleInfo.getPkgName());
            patchBundleInfo.setDependency(artifactBundleInfo.getDependency());
            patchBundleInfo.setBaseVersion(artifactBundleInfo.getBaseVersion());
            patchInfo.getBundles().add(patchBundleInfo);
        } else if (modifyBundles.contains(artifactBundleInfo.getPkgName().replace("_", "."))) {
            PatchBundleInfo patchBundleInfo = new PatchBundleInfo();
            patchBundleInfo.setNewBundle(false);
            patchBundleInfo.setMainBundle(false);
            patchBundleInfo.setPatchType(bundleTypes.get(artifactBundleInfo.getPkgName()) == null ? 0
                    : bundleTypes.get(artifactBundleInfo.getPkgName()));
            patchBundleInfo.setSrcUnitTag(artifactBundleInfo.getSrcUnitTag());
            patchBundleInfo.setUnitTag(artifactBundleInfo.getUnitTag());
            patchBundleInfo.setVersion(artifactBundleInfo.getVersion());
            patchBundleInfo.setName(artifactBundleInfo.getName());
            patchBundleInfo.setApplicationName(artifactBundleInfo.getApplicationName());
            patchBundleInfo.setArtifactId(artifactBundleInfo.getArtifactId());
            patchBundleInfo.setPkgName(artifactBundleInfo.getPkgName());
            patchBundleInfo.setDependency(artifactBundleInfo.getDependency());
            patchBundleInfo.setBaseVersion(artifactBundleInfo.getBaseVersion());
            patchInfo.getBundles().add(patchBundleInfo);
            if (artifactBundleInfo.getUnitTag().equals(artifactBundleInfo.getSrcUnitTag())) {
                throw new RuntimeException(artifactBundleInfo.getPkgName()
                        + "has contents change,but unitTag equals srcUnitTag" + artifactBundleInfo.getUnitTag()
                        + ",please upgrade bundle version and reintegration");
            }
        }
    }

    try {
        zipFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return patchInfo;
}

From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java

/**
 * /*from w  w w.j av a  2  s.c  o m*/
 * create one default index bean which based one the component zip file directly.
 * 
 * bundleId, version, mvn_uri are required
 */
public ComponentIndexBean create(File componentZipFile) {
    if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory()
            || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) {
        return null;
    }

    String name = null;
    String bundleId = null;
    String bundleVersion = null;
    String mvnUri = null;

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(componentZipFile);

        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            String path = zipEntry.getName();
            if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar
                // if it's bundle, not from other folder, like lib, m2 repository.
                IPath p = new Path(path);
                // must be in plugins
                if (p.segmentCount() > 1
                        && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) {
                    if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) {
                        JarInputStream jarEntryStream = null;
                        try {
                            // must use another stream
                            jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry));
                            // find the bundleId and version
                            Manifest manifest = jarEntryStream.getManifest();
                            if (manifest != null) {
                                bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                            }
                            boolean checkManifest = StringUtils.isBlank(bundleId)
                                    || StringUtils.isBlank(bundleVersion);

                            // find the pom.properties
                            JarEntry jarEntry = null;
                            while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) {
                                final String entryPath = jarEntry.getName();
                                if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) {
                                    manifest = new Manifest();
                                    manifest.read(jarEntryStream);
                                    bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                    bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                                    checkManifest = false;
                                }
                                final Path fullPath = new Path(entryPath);
                                final String fileName = fullPath.lastSegment();

                                /*
                                 * for example,
                                 * META-INF/maven/org.talend.components/components-splunk/pom.properties
                                 */
                                if (fileName.equals("pom.properties") //$NON-NLS-1$
                                        && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$

                                    // FIXME, didn't find one way to read the inner jar
                                    // final InputStream propStream = jarFile.getInputStream(jarEntry);
                                    // if (propStream != null) {
                                    // Properties pomProp = new Properties();
                                    // pomProp.load(propStream);
                                    //
                                    // String version = pomProp.getProperty("version"); //$NON-NLS-1$
                                    // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$
                                    // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$
                                    // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version,
                                    // FileExtensions.ZIP_FILE_SUFFIX, null);
                                    //
                                    // propStream.close();
                                    // }

                                    // FIXME, try the path way
                                    // META-INF/maven/org.talend.components/components-splunk
                                    IPath tmpMavenPath = fullPath.removeLastSegments(1);
                                    String artifactId = tmpMavenPath.lastSegment(); // components-splunk
                                    // META-INF/maven/org.talend.components
                                    tmpMavenPath = tmpMavenPath.removeLastSegments(1);
                                    String groupId = tmpMavenPath.lastSegment(); // org.talend.components

                                    mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion,
                                            FileExtensions.ZIP_EXTENSION, null);

                                } else
                                /*
                                 * /OSGI-INF/installer$$splunk.xml
                                 */
                                if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX)
                                        && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                        && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) {
                                    name = fullPath.removeFileExtension().lastSegment();
                                    name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                            + UpdatesHelper.NEW_COMPONENT_PREFIX.length());
                                }
                            }
                        } catch (IOException e) {
                            //
                        } finally {
                            try {
                                if (jarEntryStream != null) {
                                    jarEntryStream.close();
                                }
                            } catch (IOException e) {
                                //
                            }
                        }

                    }
                }
            }
        }

    } catch (ZipException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } catch (IOException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                //
            }
        }
    }
    // set the required
    if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) {
        final ComponentIndexBean indexBean = new ComponentIndexBean();
        final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri);
        indexBean.setValue(ComponentIndexNames.types,
                PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0)));
        if (set) {
            return indexBean;
        }
    }
    return null;
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();//from   w  w  w . j a  va2  s.  c o  m

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}

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

/** Called when the activity is first created. */
@Override//from  www  . ja v  a2s.c o  m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

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

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

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

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

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

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

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

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

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

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

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

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

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

    super.onCreate(savedInstanceState);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                        }

                                    }
                                } // for ZipEntry

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

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

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

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

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

            return result[0];
        }

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

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

                        return false;
                    }
                });
            }

        }
    });
    layout.addView(btn3);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            };

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

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

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

    setContentView(layout);
}

From source file:org.kaaproject.kaa.server.control.service.sdk.JavaSdkGenerator.java

@Override
public FileData generateSdk(String buildVersion, List<BootstrapNodeInfo> bootstrapNodes,
        SdkProfileDto sdkProfile, String profileSchemaBody, String notificationSchemaBody,
        String configurationProtocolSchemaBody, String configurationSchemaBody, byte[] defaultConfigurationData,
        List<EventFamilyMetadata> eventFamilies, String logSchemaBody) throws Exception {

    final String sdkToken = sdkProfile.getToken();
    final Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion();
    final Integer notificationSchemaVersion = sdkProfile.getNotificationSchemaVersion();
    final Integer logSchemaVersion = sdkProfile.getLogSchemaVersion();

    final Schema configurationSchema = new Schema.Parser().parse(configurationSchemaBody);
    final Schema profileSchema = new Schema.Parser().parse(profileSchemaBody);
    final Schema notificationSchema = new Schema.Parser().parse(notificationSchemaBody);
    final Schema logSchema = new Schema.Parser().parse(logSchemaBody);

    List<String> flatEventClassCtlSchemas = new ArrayList<>();
    eventFamilies.forEach(ecf -> flatEventClassCtlSchemas.addAll(ecf.getRawCtlsSchemas()));
    List<Schema> eventClassCtlSchemas = new LinkedList<>();
    if (!flatEventClassCtlSchemas.isEmpty()) {
        for (String flatCtlSchema : flatEventClassCtlSchemas) {
            Schema eventClassCtlSchema = new Schema.Parser().parse(flatCtlSchema);
            eventClassCtlSchemas.add(eventClassCtlSchema);
        }/* ww  w.jav a2s  . c  om*/
    }

    List<Schema> schemasToCheck = new LinkedList<>();
    schemasToCheck.add(configurationSchema);
    schemasToCheck.add(profileSchema);
    schemasToCheck.add(notificationSchema);
    schemasToCheck.add(logSchema);
    schemasToCheck.addAll(eventClassCtlSchemas);

    Map<String, Schema> uniqueSchemasMap = SchemaUtil.getUniqueSchemasMap(schemasToCheck);

    String sdkTemplateLocation;
    if (sdkPlatform == JAVA) {
        sdkTemplateLocation = Environment.getServerHomeDir() + "/" + JAVA_SDK_DIR + "/" + JAVA_SDK_PREFIX
                + buildVersion + ".jar";
        LOG.debug("Lookup Java SDK template: {}", sdkTemplateLocation);
    } else { // ANDROID
        sdkTemplateLocation = Environment.getServerHomeDir() + "/" + ANDROID_SDK_DIR + "/" + ANDROID_SDK_PREFIX
                + buildVersion + ".jar";
        LOG.debug("Lookup Android SDK template: {}", sdkTemplateLocation);
    }

    File sdkTemplateFile = new File(sdkTemplateLocation);
    ZipFile templateArhive = new ZipFile(sdkTemplateFile);

    Map<String, ZipEntryData> replacementData = new HashMap<String, ZipEntryData>();

    ZipEntry clientPropertiesEntry = templateArhive.getEntry(CLIENT_PROPERTIES);
    byte[] clientPropertiesData = generateClientProperties(templateArhive.getInputStream(clientPropertiesEntry),
            bootstrapNodes, sdkToken, configurationProtocolSchemaBody, defaultConfigurationData);

    replacementData.put(CLIENT_PROPERTIES,
            new ZipEntryData(new ZipEntry(CLIENT_PROPERTIES), clientPropertiesData));

    List<JavaDynamicBean> javaSources = new ArrayList<JavaDynamicBean>();

    String configurationClassName = configurationSchema.getName();
    String configurationClassPackage = configurationSchema.getNamespace();

    javaSources.addAll(generateSchemaSources(configurationSchema, uniqueSchemasMap));

    String configurationManagerImplTemplate = readResource(CONFIGURATION_MANAGER_IMPL_SOURCE_TEMPLATE);
    String configurationManagerImplSource = configurationManagerImplTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationManagerImplClassBean = new JavaDynamicBean(CONFIGURATION_MANAGER_IMPL,
            configurationManagerImplSource);
    javaSources.add(configurationManagerImplClassBean);

    String configurationManagerTemplate = readResource(CONFIGURATION_MANAGER_SOURCE_TEMPLATE);
    String configurationManagerSource = configurationManagerTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationManagerClassBean = new JavaDynamicBean(CONFIGURATION_MANAGER,
            configurationManagerSource);
    javaSources.add(configurationManagerClassBean);

    String configurationListenerTemplate = readResource(CONFIGURATION_LISTENER_SOURCE_TEMPLATE);
    String configurationListenerSource = configurationListenerTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationListenerClassBean = new JavaDynamicBean(CONFIGURATION_LISTENER,
            configurationListenerSource);
    javaSources.add(configurationListenerClassBean);

    String configurationDeserializerSourceTemplate = readResource(CONFIGURATION_DESERIALIZER_SOURCE_TEMPLATE);
    String configurationDeserializerSource = configurationDeserializerSourceTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationDeserializerClassBean = new JavaDynamicBean(CONFIGURATION_DESERIALIZER,
            configurationDeserializerSource);
    javaSources.add(configurationDeserializerClassBean);

    String profileClassName = profileSchema.getName();
    String profileClassPackage = profileSchema.getNamespace();

    if (profileSchemaVersion != DEFAULT_PROFILE_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(profileSchema, uniqueSchemasMap));
    }

    String profileContainerTemplate = readResource(PROFILE_CONTAINER_SOURCE_TEMPLATE);
    String profileContainerSource = profileContainerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);

    JavaDynamicBean profileContainerClassBean = new JavaDynamicBean(PROFILE_CONTAINER, profileContainerSource);

    javaSources.add(profileContainerClassBean);

    String defaultProfileContainerTemplate = readResource(DEFAULT_PROFILE_CONTAINER_SOURCE_TEMPLATE);
    String defaultProfileContainerSource = defaultProfileContainerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);
    JavaDynamicBean defaultProfileContainerClassBean = new JavaDynamicBean(DEFAULT_PROFILE_CONTAINER,
            defaultProfileContainerSource);
    javaSources.add(defaultProfileContainerClassBean);

    String profileSerializerTemplate;
    if (profileSchemaVersion == DEFAULT_PROFILE_SCHEMA_VERSION) {
        profileSerializerTemplate = readResource(DEFAULT_PROFILE_SERIALIZER_SOURCE_TEMPLATE);
    } else {
        profileSerializerTemplate = readResource(PROFILE_SERIALIZER_SOURCE_TEMPLATE);
    }
    String profileSerializerSource = profileSerializerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);

    JavaDynamicBean profileSerializerClassBean = new JavaDynamicBean(PROFILE_SERIALIZER,
            profileSerializerSource);

    javaSources.add(profileSerializerClassBean);

    String notificationClassName = notificationSchema.getName();
    String notificationClassPackage = notificationSchema.getNamespace();

    if (notificationSchemaVersion != DEFAULT_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(notificationSchema, uniqueSchemasMap));
    }

    String notificationListenerTemplate = readResource(NOTIFICATION_LISTENER_SOURCE_TEMPLATE);
    String notificationListenerSource = notificationListenerTemplate
            .replaceAll(NOTIFICATION_CLASS_PACKAGE_VAR, notificationClassPackage)
            .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

    JavaDynamicBean notificationListenerClassBean = new JavaDynamicBean(NOTIFICATION_LISTENER,
            notificationListenerSource);
    javaSources.add(notificationListenerClassBean);

    String notificationDeserializerSourceTemplate = readResource(NOTIFICATION_DESERIALIZER_SOURCE_TEMPLATE);

    String notificationDeserializerSource = notificationDeserializerSourceTemplate
            .replaceAll(NOTIFICATION_CLASS_PACKAGE_VAR, notificationClassPackage)
            .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

    JavaDynamicBean notificationDeserializerClassBean = new JavaDynamicBean(NOTIFICATION_DESERIALIZER,
            notificationDeserializerSource);
    javaSources.add(notificationDeserializerClassBean);

    if (logSchemaVersion != DEFAULT_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(logSchema, uniqueSchemasMap));
    }

    String logRecordTemplate = readResource(LOG_RECORD_SOURCE_TEMPLATE);
    String logRecordSource = logRecordTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    String logCollectorInterfaceTemplate = readResource(LOG_COLLECTOR_INTERFACE_TEMPLATE);
    String logCollectorInterface = logCollectorInterfaceTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    String logCollectorSourceTemplate = readResource(LOG_COLLECTOR_SOURCE_TEMPLATE);
    String logCollectorSource = logCollectorSourceTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    JavaDynamicBean logRecordClassBean = new JavaDynamicBean(LOG_RECORD, logRecordSource);
    JavaDynamicBean logCollectorInterfaceClassBean = new JavaDynamicBean(LOG_COLLECTOR_INTERFACE,
            logCollectorInterface);
    JavaDynamicBean logCollectorSourceClassBean = new JavaDynamicBean(LOG_COLLECTOR_SOURCE, logCollectorSource);

    javaSources.add(logRecordClassBean);
    javaSources.add(logCollectorInterfaceClassBean);
    javaSources.add(logCollectorSourceClassBean);

    if (eventFamilies != null && !eventFamilies.isEmpty()) {
        for (Schema ctlSchema : eventClassCtlSchemas) {
            javaSources.addAll(generateSchemaSources(ctlSchema, uniqueSchemasMap));
        }
        javaSources.addAll(JavaEventClassesGenerator.generateEventClasses(eventFamilies));
    }

    String defaultVerifierToken = sdkProfile.getDefaultVerifierToken();
    String userVerifierConstantsTemplate = readResource(USER_VERIFIER_CONSTANTS_SOURCE_TEMPLATE);
    if (defaultVerifierToken == null) {
        defaultVerifierToken = "null";
    } else {
        defaultVerifierToken = "\"" + defaultVerifierToken + "\"";
    }
    String userVerifierConstantsSource = userVerifierConstantsTemplate
            .replaceAll(DEFAULT_USER_VERIFIER_TOKEN_VAR, defaultVerifierToken);

    JavaDynamicBean userVerifierConstantsClassBean = new JavaDynamicBean(USER_VERIFIER_CONSTANTS,
            userVerifierConstantsSource);
    javaSources.add(userVerifierConstantsClassBean);

    String kaaClientTemplate = readResource(KAA_CLIENT_SOURCE_TEMPLATE);

    String kaaClientSource = kaaClientTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName())
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean kaaClientClassBean = new JavaDynamicBean(KAA_CLIENT, kaaClientSource);
    javaSources.add(kaaClientClassBean);

    String baseKaaClientTemplate = readResource(BASE_KAA_CLIENT_SOURCE_TEMPLATE);
    String baseKaaClientSource = baseKaaClientTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName())
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean baseKaaClientClassBean = new JavaDynamicBean(BASE_KAA_CLIENT, baseKaaClientSource);
    javaSources.add(baseKaaClientClassBean);

    packageSources(javaSources, replacementData);

    ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream();
    ZipOutputStream sdkFile = new ZipOutputStream(sdkOutput);

    Enumeration<? extends ZipEntry> entries = templateArhive.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (replacementData.containsKey(entry.getName())) {
            ZipEntryData replacementEntry = replacementData.remove(entry.getName());
            sdkFile.putNextEntry(replacementEntry.getEntry());
            sdkFile.write(replacementEntry.getData());
        } else {
            sdkFile.putNextEntry(entry);
            if (!entry.isDirectory()) {
                IOUtils.copy(templateArhive.getInputStream(entry), sdkFile);
            }
        }
        sdkFile.closeEntry();
    }
    templateArhive.close();

    for (String entryName : replacementData.keySet()) {
        ZipEntryData replacementEntry = replacementData.get(entryName);
        sdkFile.putNextEntry(replacementEntry.getEntry());
        sdkFile.write(replacementEntry.getData());
        sdkFile.closeEntry();
    }

    sdkFile.close();

    String fileNamePrefix = (sdkPlatform == JAVA ? JAVA_SDK_PREFIX : ANDROID_SDK_PREFIX);
    String sdkFileName = fileNamePrefix + sdkProfile.getToken() + ".jar";

    byte[] sdkData = sdkOutput.toByteArray();

    FileData sdk = new FileData();
    sdk.setFileName(sdkFileName);
    sdk.setFileData(sdkData);
    return sdk;
}

From source file:simonlang.coastdove.core.detection.AppDetectionDataSetup.java

/**
 * Constructs a new layout collection from the given .apk file
 * @param apkFile             APK file to process
 *///  w ww. ja va  2 s.  co  m
public static AppDetectionData fromAPK(Context context, File apkFile, String appPackageName,
        LoadingInfo loadingInfo) {
    // Map if how often IDs occur
    Map<String, Integer> idCounts = new HashMap<>();
    // Set of activities available from the Android launcher
    Set<String> mainActivities = new TreeSet<>(new CollatorWrapper());

    loadingInfo.setNotificationData(context.getString(R.string.add_app_notification_loading), appPackageName,
            R.drawable.notification_template_icon_bg);
    loadingInfo.setTitle(context.getString(R.string.add_app_parsing_resources));
    loadingInfo.start(true);

    ZipFile apk;
    try {
        apk = new ZipFile(apkFile);
    } catch (IOException e) {
        Log.e("AppDetectionDataSetup", "Cannot open ZipFile: " + e.getMessage());
        throw new RuntimeException(e.getMessage());
    }
    Log.d("AppDetectionDataSetup", "Parsing resources.arsc and AndroidManifest.xml");
    ARSCFileParser resourceParser = new ARSCFileParser();
    ZipEntry arscEntry = apk.getEntry("resources.arsc");
    APKToolHelper apktoolHelper = new APKToolHelper(apkFile);
    InputStream manifestInputStream = apktoolHelper.manifestInputStream();

    try {
        resourceParser.parse(apk.getInputStream(arscEntry));
        if (Thread.currentThread().isInterrupted()) {
            loadingInfo.end();
            apk.close();
            return null;
        }

        XmlPullParserFactory fac = XmlPullParserFactory.newInstance();
        XmlPullParser p = fac.newPullParser();
        p.setInput(manifestInputStream, "UTF-8");
        mainActivities = parseMainActivities(p);
        manifestInputStream.close();
        if (Thread.currentThread().isInterrupted()) {
            loadingInfo.end();
            apk.close();
            return null;
        }
    } catch (IOException e) {
        Log.e("AppDetectionDataSetup", "Cannot get InputStream: " + e.getMessage());
    } catch (XmlPullParserException e) {
        Log.e("AppDetectionDataSetup", "Cannot get XmlPullParser: " + e.getMessage());
    }

    AppMetaInformation appMetaInformation = new AppMetaInformation(appPackageName, mainActivities);

    // Read APK file
    loadingInfo.setTitle(context.getString(R.string.add_app_reading_apk));
    loadingInfo.update();
    Log.d("AppDetectionDataSetup", "Reading APK file");
    Enumeration<?> zipEntries = apk.entries();

    List<Pair<String, Set<String>>> layoutIDSets = new LinkedList<>();
    while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
        try {
            if (Thread.currentThread().isInterrupted()) {
                loadingInfo.end();
                apk.close();
                return null;
            }
            String entryName = zipEntry.getName();
            if (entryName.contains("res/layout/") && Misc.isBinaryXML(apk.getInputStream(zipEntry))) {
                String name = entryName.replaceAll(".*/", "").replace(".xml", "");

                AXmlResourceParser parser = new AXmlResourceParser();
                parser.open(apk.getInputStream(zipEntry));
                Set<String> androidIDs = parseAndroidIDs(parser, resourceParser);

                layoutIDSets.add(new Pair<>(name, androidIDs));

                // Count all IDs
                for (String id : androidIDs) {
                    if (idCounts.containsKey(id)) {
                        int count = idCounts.get(id);
                        idCounts.put(id, count + 1);
                    } else
                        idCounts.put(id, 1);
                }
            }
        } catch (IOException e) {
            Log.e("AppDetectionDataSetup", "Error reading APK file: " + e.getMessage());
        }
    }

    try {
        apk.close();
    } catch (IOException e) {
        Log.e("AppDetectionDataSetup", "Unable to close APK file: " + e.getMessage());
    }

    // get unique IDs and reverse map
    loadingInfo.setTitle(context.getString(R.string.add_app_setting_up_layouts));
    loadingInfo.update();

    // Build the final map we actually need (id -> layout)
    Map<String, String> idToLayoutMap = new HashMap<>();
    for (Pair<String, Set<String>> layoutIDSet : layoutIDSets) {
        for (String id : layoutIDSet.second) {
            if (idCounts.get(id) == 1)
                idToLayoutMap.put(id, layoutIDSet.first);
        }
    }

    loadingInfo.setNotificationData(context.getString(R.string.add_app_notification_finished_loading), null,
            null);
    loadingInfo.end();

    return new AppDetectionData(appPackageName, idToLayoutMap, appMetaInformation);
}