List of usage examples for java.util.zip ZipEntry getSize
public long getSize()
From source file:freenet.client.ArchiveManager.java
private void handleZIPArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element, ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context) throws ArchiveFailureException, ArchiveRestartException { if (logMINOR) Logger.minor(this, "Handling a ZIP Archive"); ZipInputStream zis = null;//from w w w. j a va 2 s .com try { zis = new ZipInputStream(data); // MINOR: Assumes the first entry in the zip is a directory. ZipEntry entry; byte[] buf = new byte[32768]; HashSet<String> names = new HashSet<String>(); boolean gotMetadata = false; outerZIP: while (true) { entry = zis.getNextEntry(); if (entry == null) break; if (entry.isDirectory()) continue; String name = stripLeadingSlashes(entry.getName()); if (names.contains(name)) { Logger.error(this, "Duplicate key " + name + " in archive " + key); continue; } long size = entry.getSize(); if (name.equals(".metadata")) gotMetadata = true; if (size > maxArchivedFileSize && !name.equals(element)) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); } else { // Read the element long realLen = 0; Bucket output = tempBucketFactory.makeBucket(size); OutputStream out = output.getOutputStream(); try { int readBytes; while ((readBytes = zis.read(buf)) > 0) { out.write(buf, 0, readBytes); readBytes += realLen; if (readBytes > maxArchivedFileSize) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); out.close(); out = null; output.free(); continue outerZIP; } } } finally { if (out != null) out.close(); } if (size <= maxArchivedFileSize) { addStoreElement(ctx, key, name, output, gotElement, element, callback, context); names.add(name); trimStoredData(); } else { // We are here because they asked for this file. callback.gotBucket(output, context); gotElement.value = true; addErrorElement( ctx, key, name, "File too big: " + size + " greater than current archived file size limit " + maxArchivedFileSize, true); } } } // If no metadata, generate some if (!gotMetadata) { generateMetadata(ctx, key, names, gotElement, element, callback, context); trimStoredData(); } if (throwAtExit) throw new ArchiveRestartException("Archive changed on re-fetch"); if ((!gotElement.value) && element != null) callback.notInArchive(context); } catch (IOException e) { throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { Logger.error(this, "Failed to close stream: " + e, e); } } } }
From source file:org.opencms.importexport.A_CmsImport.java
/** * Returns a byte array containing the content of the file.<p> * * @param filename the name of the file to read * @return a byte array containing the content of the file *//*from www. j a v a2s . co m*/ protected byte[] getFileBytes(String filename) { try { // is this a zip-file? if (m_importZip != null) { // yes ZipEntry entry = m_importZip.getEntry(filename); // path to file might be relative, too if ((entry == null) && filename.startsWith("/")) { entry = m_importZip.getEntry(filename.substring(1)); } if (entry == null) { throw new ZipException(Messages.get().getBundle() .key(Messages.LOG_IMPORTEXPORT_FILE_NOT_FOUND_IN_ZIP_1, filename)); } InputStream stream = m_importZip.getInputStream(entry); int size = new Long(entry.getSize()).intValue(); return CmsFileUtil.readFully(stream, size); } else { // no - use directory File file = new File(m_importResource, filename); return CmsFileUtil.readFile(file); } } catch (FileNotFoundException fnfe) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_IMPORTEXPORT_FILE_NOT_FOUND_1, filename), fnfe); } m_report.println(fnfe); } catch (IOException ioe) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_IMPORTEXPORT_ERROR_READING_FILE_1, filename), ioe); } m_report.println(ioe); } // this will only be returned in case there was an exception return "".getBytes(); }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean unzipSync(File targetFile, String outputDirectory, ProgressEvent progress, CallbackContext callbackContext) { Log.d(LOG_TAG, "unzipSync called"); Log.d(LOG_TAG, "zip = " + targetFile.getAbsolutePath()); InputStream inputStream = null; ZipFile zip = null;/*w w w . ja va2 s.co m*/ boolean anyEntries = false; try { synchronized (progress) { if (progress.isAborted()) { return false; } } zip = new ZipFile(targetFile); // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile:// // Accept a path or a URI for the source zip. Uri zipUri = getUriForArg(targetFile.getAbsolutePath()); Uri outputUri = getUriForArg(outputDirectory); CordovaResourceApi resourceApi = webView.getResourceApi(); File tempFile = resourceApi.mapUriToFile(zipUri); if (tempFile == null || !tempFile.exists()) { sendErrorMessage("Zip file does not exist", UNZIP_ERROR, callbackContext); } File outputDir = resourceApi.mapUriToFile(outputUri); outputDirectory = outputDir.getAbsolutePath(); outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator; if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) { sendErrorMessage("Could not create output directory", UNZIP_ERROR, callbackContext); } OpenForReadResult zipFile = resourceApi.openForRead(zipUri); progress.setStatus(STATUS_EXTRACTING); progress.setLoaded(0); progress.setTotal(zip.size()); Log.d(LOG_TAG, "zip file len = " + zip.size()); inputStream = new BufferedInputStream(zipFile.inputStream); inputStream.mark(10); int magic = readInt(inputStream); if (magic != 875721283) { // CRX identifier inputStream.reset(); } else { // CRX files contain a header. This header consists of: // * 4 bytes of magic number // * 4 bytes of CRX format version, // * 4 bytes of public key length // * 4 bytes of signature length // * the public key // * the signature // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream. readInt(inputStream); // version == 2. int pubkeyLength = readInt(inputStream); int signatureLength = readInt(inputStream); inputStream.skip(pubkeyLength + signatureLength); } // The inputstream is now pointing at the start of the actual zip file content. ZipInputStream zis = new ZipInputStream(inputStream); inputStream = zis; ZipEntry ze; byte[] buffer = new byte[32 * 1024]; while ((ze = zis.getNextEntry()) != null) { synchronized (progress) { if (progress.isAborted()) { return false; } } anyEntries = true; String compressedName = ze.getName(); if (ze.getSize() > getFreeSpace()) { return false; } if (ze.isDirectory()) { File dir = new File(outputDirectory + compressedName); dir.mkdirs(); } else { File file = new File(outputDirectory + compressedName); file.getParentFile().mkdirs(); if (file.exists() || file.createNewFile()) { Log.w(LOG_TAG, "extracting: " + file.getPath()); FileOutputStream fout = new FileOutputStream(file); int count; while ((count = zis.read(buffer)) != -1) { fout.write(buffer, 0, count); } fout.close(); } } progress.addLoaded(1); updateProgress(callbackContext, progress); zis.closeEntry(); } } catch (Exception e) { String errorMessage = "An error occurred while unzipping."; sendErrorMessage(errorMessage, UNZIP_ERROR, callbackContext); Log.e(LOG_TAG, errorMessage, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (zip != null) { try { zip.close(); } catch (IOException e) { } } } if (anyEntries) return true; else return false; }
From source file:org.wso2.carbon.greg.soap.viewer.WSDLVisualizer.java
/** * Get the temp location of output directory where wsdl files is saved with its dependencies * * @param path Registry path the the WSDL file * @return Output directory path/*from w w w . j a va 2 s . co m*/ */ private String writeResourceToFile(String path) { String outDir = null; try { Registry registry = ServiceHolder.getRegistryService().getSystemRegistry(); ContentDownloadBean zipContentBean = ContentUtil.getContentWithDependencies(path, (UserRegistry) registry); InputStream zipContentStream = zipContentBean.getContent().getInputStream(); ZipInputStream stream = new ZipInputStream(zipContentStream); byte[] buffer = new byte[2048]; String uniqueID = UUID.randomUUID().toString(); outDir = CarbonUtils.getCarbonHome() + File.separator + "tmp" + File.separator + uniqueID; (new File(outDir)).mkdir(); ZipEntry entry; while ((entry = stream.getNextEntry()) != null) { String s = String.format("Entry: %s len %d added %TD", outDir + File.separator + entry.getName(), entry.getSize(), new Date(entry.getTime())); String outPath = outDir + File.separator + entry.getName(); (new File(outPath)).getParentFile().mkdirs(); FileOutputStream output = null; try { output = new FileOutputStream(outPath); int len = 0; while ((len = stream.read(buffer)) > 0) { output.write(buffer, 0, len); } } finally { // Close the output file if (output != null) { output.close(); } } } } catch (FileNotFoundException e) { logger.error("temporary output directory cannot be found ", e); } catch (IOException e) { logger.error("Error occurred while writing the WSDL content to the temporary file", e); } catch (RegistryException e) { logger.error("Error occurred while getting registry from service holder", e); } catch (Exception e) { logger.error("Error occurred while getting registry from service holder", e); } return outDir; }
From source file:org.wso2.carbon.governance.soap.viewer.WSDLVisualizer.java
/** * Get the temp location of output directory where wsdl files is saved with its dependencies * * @param path Registry path the the WSDL file * @return Output directory path// w ww. j ava 2 s. c o m */ private String writeResourceToFile(String path, int tenantId) { String outDir = null; try { UserRegistry registry = ServiceHolder.getRegistryService().getSystemRegistry(tenantId); ContentDownloadBean zipContentBean = ContentUtil.getContentWithDependencies(path, registry); InputStream zipContentStream = zipContentBean.getContent().getInputStream(); ZipInputStream stream = new ZipInputStream(zipContentStream); byte[] buffer = new byte[2048]; String uniqueID = UUID.randomUUID().toString(); outDir = CarbonUtils.getCarbonHome() + File.separator + "tmp" + File.separator + uniqueID; (new File(outDir)).mkdir(); ZipEntry entry; while ((entry = stream.getNextEntry()) != null) { String s = String.format("Entry: %s len %d added %TD", outDir + File.separator + entry.getName(), entry.getSize(), new Date(entry.getTime())); String outPath = outDir + File.separator + entry.getName(); (new File(outPath)).getParentFile().mkdirs(); FileOutputStream output = null; try { output = new FileOutputStream(outPath); int len = 0; while ((len = stream.read(buffer)) > 0) { output.write(buffer, 0, len); } } finally { // Close the output file if (output != null) { output.close(); } } } } catch (FileNotFoundException e) { logger.error("temporary output directory cannot be found ", e); } catch (IOException e) { logger.error("Error occurred while writing the WSDL content to the temporary file", e); } catch (RegistryException e) { logger.error("Error occurred while getting registry from service holder", e); } catch (Exception e) { logger.error("Error occurred while getting registry from service holder", e); } return outDir; }
From source file:net.wastl.webmail.config.ExtConfigListener.java
/** * @param baseDir/*w ww . j av a 2 s . c o m*/ * Parent directory of metaFile * @param metaFile * Properties file to be created. IT CAN NOT EXIST YET! * @throws IOException * if fail to create new XML Storage system */ protected void installXmlStorage(File baseDir, File metaFile) throws IOException { log.warn("Will attempt install a brand new data store"); final File dataDir = new File(baseDir, "data"); if (dataDir.exists()) throw new IOException("Target data path dir already exists: " + dataDir.getAbsolutePath()); if (!baseDir.isDirectory()) { final File parentDir = baseDir.getParentFile(); if (!parentDir.canWrite()) throw new IOException("Cannot create base RT directory '" + baseDir.getAbsolutePath() + "'"); if (!baseDir.mkdir()) throw new IOException("Failed to create base RT directory '" + baseDir.getAbsolutePath() + "'"); log.debug("Created base RT dir '" + baseDir.getAbsolutePath() + "'"); mkLockFile(); } if (!baseDir.canWrite()) throw new IOException( "Do not have privilegest to create meta file '" + metaFile.getAbsolutePath() + "'"); if (!dataDir.mkdir()) throw new IOException("Failed to create data directory '" + dataDir.getAbsolutePath() + "'"); log.debug("Created data dir '" + dataDir.getAbsolutePath() + "'"); // In my experience, you can't trust the return values of the // File.mkdir() method. But the file creations or extractions // wild fail below in that case, so that's no problem. // Could create a Properties object and save it, but why? final PrintWriter pw = new PrintWriter(new FileWriter(metaFile)); try { pw.println("webmail.data.path: ${rtconfig.dir}/data"); pw.println("webmail.mimetypes.filepath: " + "${rtconfig.dir}/mimetypes.txt"); pw.flush(); } finally { pw.close(); } final InputStream zipFileStream = getClass().getResourceAsStream("/data.zip"); if (zipFileStream == null) throw new IOException("Zip file 'data.zip' missing from web application"); final InputStream mimeInStream = getClass().getResourceAsStream("/mimetypes.txt"); if (mimeInStream == null) throw new IOException("Mime-types file 'mimetypes.txt' missing from web application"); ZipEntry entry; File newNode; FileOutputStream fileStream; long fileSize, bytesRead; int i; final byte[] buffer = new byte[10240]; final FileOutputStream mimeOutStream = new FileOutputStream(new File(baseDir, "mimetypes.txt")); try { while ((i = mimeInStream.read(buffer)) > 0) { mimeOutStream.write(buffer, 0, i); } mimeOutStream.flush(); } finally { mimeOutStream.close(); } log.debug("Extracted mime types file"); final ZipInputStream zipStream = new ZipInputStream(zipFileStream); try { while ((entry = zipStream.getNextEntry()) != null) { newNode = new File(dataDir, entry.getName()); if (entry.isDirectory()) { if (!newNode.mkdir()) throw new IOException( "Failed to extract dir '" + entry.getName() + "' from 'data.zip' file"); log.debug("Extracted dir '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); zipStream.closeEntry(); continue; } fileSize = entry.getSize(); fileStream = new FileOutputStream(newNode); try { bytesRead = 0; while ((i = zipStream.read(buffer)) > 0) { fileStream.write(buffer, 0, i); bytesRead += i; } fileStream.flush(); } finally { fileStream.close(); } zipStream.closeEntry(); if (bytesRead != fileSize) throw new IOException("Expected " + fileSize + " bytes for '" + entry.getName() + ", but extracted " + bytesRead + " bytes to '" + newNode.getAbsolutePath() + "'"); log.debug("Extracted file '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); } } finally { zipStream.close(); } }
From source file:org.lockss.exporter.FuncZipExporter.java
public List<String> testExport(boolean isCompress, long maxSize, FilenameTranslation xlate, boolean excludeDirContent) throws Exception { exportDir = getTempDir();/* www .j a va2s.c o m*/ exportFiles = null; ZipExporter exp = new ZipExporter(daemon, sau); exp.setDir(exportDir); exp.setPrefix("zippre"); exp.setCompress(isCompress); exp.setFilenameTranslation(xlate); exp.setExcludeDirNodes(excludeDirContent); if (maxSize > 0) { exp.setMaxSize(maxSize); } exp.export(); int numZipRecords = 0; File expFile; List<String> urls = new ArrayList<String>(); while ((expFile = nextExportFile()) != null) { ZipFile zip = new ZipFile(expFile); Enumeration iter = zip.entries(); while (iter.hasMoreElements()) { ZipEntry rec = null; CachedUrl cu = null; try { rec = (ZipEntry) iter.nextElement(); String url = rec.getName(); switch (xlate) { case XLATE_NONE: assertMatchesRE("^http://", url); break; case XLATE_WINDOWS: case XLATE_MAC: // The filenames were translated. Current windows translation // isn't reversible in general, but we know that the only // windows-illegal character in simulated content is the colon, // so we can reverse it. If that changes, this test will // break. assertMatchesRE("^http_//", url); url = StringUtil.replaceString(url, "_", ":"); break; } String comment = rec.getComment(); cu = sau.makeCachedUrl(url); // log.debug("Comp " + hdr.getMimetype() + ": " + url); assertTrue("No content in AU: " + url, cu.hasContent()); urls.add(cu.getUrl()); InputStream ins = cu.getUnfilteredInputStream(); assertTrue(StreamUtil.compare(zip.getInputStream(rec), ins)); assertEquals(cu.getContentSize(), rec.getSize()); // assertMatchesRE(cu.getContentType(), comment); numZipRecords++; } finally { AuUtil.safeRelease(cu); } } } if (excludeDirContent) { assertEquals(auUrls.size() - auDirs.size(), numZipRecords); } else { assertEquals(auUrls.size(), numZipRecords); } if (maxSize <= 0) { assertEquals(1, exportFiles.length); } else { assertTrue("Expected more than one export file", exportFiles.length > 1); } return urls; }
From source file:reconcile.hbase.mapreduce.ZipInputFormat.java
private List<ZipEntrySplit> getZipFileEntries(JobContext context, FileSystem fs, Path[] zipFiles, Integer maxEntryFiles, Integer ignoreFilesLargerThanMB, List<String> processMimeTypes) throws IOException { ArrayList<ZipEntrySplit> splits = new ArrayList<ZipEntrySplit>(); ZipInputStream zis = null;//from w ww . j ava 2 s . co m ZipEntry zipEntry = null; for (int i = 0; i < zipFiles.length; i++) { Path file = zipFiles[i]; LOG.debug("Opening zip file: " + file.toString()); try { zis = new ZipInputStream(fs.open(file)); while ((zipEntry = zis.getNextEntry()) != null) { if (maxEntryFiles != null && splits.size() == maxEntryFiles.intValue()) { LOG.debug("Exceeded maximum number of splits. End getSplits()"); return splits; } boolean processFile = true; if (processMimeTypes.size() > 0) { // Ensure that if process mime types were specified, that entry // mime type meets that criteria String mimeType = fileNameMap.getContentTypeFor(zipEntry.getName()); if (mimeType == null || (!processMimeTypes.contains(mimeType.toLowerCase()))) { processFile = false; LOG.debug("Ignoring entry file (" + zipEntry.getName() + " mimeType(" + mimeType + ") not in process list"); } } long byteCount = zipEntry.getSize(); /* if (byteCount <= 0) { // Read entry and figure out size for ourselves byteCount = 0; while (zis.available()==1) { zis.read(); ++byteCount; } } */ if (ignoreFilesLargerThanMB != null && byteCount > ignoreFilesLargerThanMB.intValue()) { processFile = false; LOG.debug("Ignoring entry file (" + zipEntry.getName() + ") which exceeds size limit"); } if (processFile) { LOG.debug("Creating split for zip entry: " + zipEntry.getName() + " Size: " + byteCount + " Method: " + (ZipEntry.DEFLATED == zipEntry.getMethod() ? "DEFLATED" : "STORED") + " Compressed Size: " + zipEntry.getCompressedSize()); ZipEntrySplit zipSplit = new ZipEntrySplit(file, zipEntry.getName(), zipEntry.getSize(), context); splits.add(zipSplit); } zis.closeEntry(); } } finally { IOUtils.closeQuietly(zis); } } return splits; }
From source file:org.dbgl.util.FileUtils.java
public static void extractEntry(final ZipFile zf, final ZipEntry srcEntry, final File dstFile, final ProgressNotifyable prog) throws IOException { File foundDstFile = null, temporarilyRenamedFile = null; if (PlatformUtils.IS_WINDOWS && dstFile.getName().contains("~")) { foundDstFile = dstFile.getCanonicalFile(); if (!foundDstFile.getName().equals(dstFile.getName()) && foundDstFile.exists()) { temporarilyRenamedFile = getUniqueFileName(foundDstFile); foundDstFile.renameTo(temporarilyRenamedFile); }//from w w w . j a va 2 s. c o m } if (dstFile.exists()) throw new IOException( Settings.getInstance().msg("general.error.filetobeextractedexists", new Object[] { dstFile })); if (srcEntry.isDirectory()) { if (!dstFile.exists()) createDir(dstFile); } else { if (dstFile.getParentFile() != null) createDir(dstFile.getParentFile()); FileOutputStream fos = new FileOutputStream(dstFile); InputStream is = zf.getInputStream(srcEntry); byte[] readBuffer = new byte[ZIP_BUFFER]; int bytesIn; while ((bytesIn = is.read(readBuffer)) != -1) fos.write(readBuffer, 0, bytesIn); fos.flush(); fos.close(); is.close(); byte[] extra = srcEntry.getExtra(); if ((extra != null) && (extra.length == 1) && (extra[0] == 1)) fileSetReadOnly(dstFile); } fileSetLastModified(dstFile, srcEntry.getTime()); if (foundDstFile != null && temporarilyRenamedFile != null) temporarilyRenamedFile.renameTo(foundDstFile); prog.incrProgress((int) (srcEntry.getSize() / 1024)); }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override//from w w w . j a v a 2s.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); }