List of usage examples for org.apache.cordova CordovaResourceApi mapUriToFile
public File mapUriToFile(Uri uri)
From source file:com.adobe.phonegap.contentsync.Sync.java
License:Apache License
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;/*from w w w . j a va 2 s. com*/ 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:com.filetransfer.baidu.bcs.FileTransferBCS.java
License:Apache License
/** * Downloads a file form a given URL and saves it to the specified directory. * * @param source URL of the server to receive the file * @param target Full path of the file on the file system *//*from w ww . ja v a 2 s .c om*/ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "download " + source + " to " + target); final CordovaResourceApi resourceApi = webView.getResourceApi(); final boolean trustEveryone = args.optBoolean(2); final String objectId = args.getString(3); final JSONObject headers = args.optJSONObject(4); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); // Accept a path or a URI for the source. Uri tmpTarget = Uri.parse(target); final Uri targetUri = resourceApi .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } // TODO: refactor to also allow resources & content: if (!isLocalTransfer) { Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; File file = null; PluginResult result = null; TrackingInputStream inputStream = null; boolean cached = false; OutputStream outputStream = null; try { OpenForReadResult readResult = null; file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; Log.d(LOG_TAG, "Download file:" + sourceUri); FileProgressBCSResult progress = new FileProgressBCSResult(); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setLengthComputable(true); progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // TODO: Make OkHttp use this CookieManager by default. String cookie = CookieManager.getInstance().getCookie(sourceUri.toString()); if (cookie != null) { connection.setRequestProperty("cookie", cookie); } // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { cached = true; connection.disconnect(); Log.d(LOG_TAG, "Resource not modified: " + source); JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null); result = new PluginResult(PluginResult.Status.ERROR, error); } else { if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip if (connection.getContentLength() != -1) { progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } } inputStream = getInputStream(connection); } } if (!cached) { try { synchronized (context) { if (context.aborted) { return; } context.connection = connection; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; outputStream = resourceApi.openOutputStream(targetUri); while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } } finally { synchronized (context) { context.connection = null; } safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); // create FileEntry object Class webViewClass = webView.getClass(); PluginManager pm = null; try { Method gpm = webViewClass.getMethod("getPluginManager"); pm = (PluginManager) gpm.invoke(webView); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (pm == null) { try { Field pmf = webViewClass.getField("pluginManager"); pm = (PluginManager) pmf.get(webView); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } } file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; FileUtils filePlugin = (FileUtils) pm.getPlugin("File"); if (filePlugin != null) { JSONObject fileEntry = filePlugin.getEntryForFile(file); if (fileEntry != null) { result = new PluginResult(PluginResult.Status.OK, fileEntry); } else { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null); Log.e(LOG_TAG, "File plugin cannot represent download path"); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } } else { Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file"); result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file"); } } } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } if (result == null) { result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null)); } // Remove incomplete download. if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }
From source file:org.chromium.APKPackager.java
License:Open Source License
private void pack(CordovaArgs args, CallbackContext callbackContext) { File playground = null;//from w w w . j av a2 s. c om File template = null; File assets = null; File output = null; File zip = null; File archive = null; File publicKey = null; File privateKey = null; File appJSON = null; URL publicKeyUrl = null; URL privateKeyUrl = null; try { } catch (Exception e) { callbackContext.error("Error on cleaning: " + e.getMessage()); return; } try { CordovaResourceApi cra = webView.getResourceApi(); playground = cra.mapUriToFile(cra.remapUri(Uri.parse(args.getString(0)))); assets = cra.mapUriToFile(cra.remapUri(Uri.parse(args.getString(2)))); output = cra.mapUriToFile(cra.remapUri(Uri.parse(args.getString(3)))); zip = cra.mapUriToFile(cra.remapUri(Uri.parse(args.getString(1)))); archive = new File(playground, "archive"); template = new File(playground, "template"); } catch (Exception e) { callbackContext.error("Missing arguments: " + e.getMessage()); return; } try { deleteDir(archive); extractToFolder(zip, archive); } catch (Exception e) { callbackContext.error("Error at unzip: " + e.getMessage()); return; } String appName = ""; String packageName = ""; String versionName = ""; String privateKeyPass = ""; String publicKeyName = ""; String privateKeyName = ""; try { appJSON = new File(archive, "app.json"); String jsonString = loadJSONFromFile(appJSON); JSONObject jObject = new JSONObject(jsonString); appName = jObject.getString("appName"); packageName = jObject.getString("packageName"); versionName = jObject.getString("versionName"); privateKeyPass = jObject.getString("keyPassword"); publicKeyName = jObject.getString("publicKeyName"); privateKeyName = jObject.getString("privateKeyName"); publicKey = new File(archive, publicKeyName); privateKey = new File(archive, privateKeyName); publicKeyUrl = publicKey.toURI().toURL(); privateKeyUrl = privateKey.toURI().toURL(); } catch (Exception e) { callbackContext.error("Error at parsing the JSON: " + e.getMessage()); return; } try { BinaryXMLParser parser = new BinaryXMLParser(template.getAbsolutePath() + "/AndroidManifest.xml"); parser.parseXML(); parser.changeString(parser.getAppName(), appName); parser.changeString(parser.getPackageName(), packageName); parser.changeString(parser.getActivityName(), appName); parser.changeString(parser.getVersion(), versionName); parser.exportXML(template.getAbsolutePath() + "/AndroidManifest.xml"); BinaryResourceParser resParser = new BinaryResourceParser( template.getAbsolutePath() + "/resources.arsc"); resParser.parseResource(); resParser.changePackageName(packageName); //resParser.changePackageName("org.chromium.cadt.template"); resParser.exportResource(template.getAbsolutePath() + "/resources.arsc"); } catch (Exception e) { callbackContext.error("Error at modifing the Android Manifest: " + e.getMessage()); } String generatedApkPath = playground.getAbsolutePath() + "/temp.apk"; String signedApkPath = output.getAbsolutePath() + "/" + appName + ".apk"; //TODO: to copy the assets directory in the template try { File destAssets = new File(template, "assets"); File pluginAssets = new File(playground, "plugins"); deleteDirContent(destAssets); mergeDirectory(assets, destAssets); mergeDirectory(pluginAssets, destAssets); } catch (Exception e) { callbackContext.error("Error at assets copy: " + e.getMessage()); return; } File fakeResZip; // take the completed package and make the unsigned APK try { // ApkBuilder REALLY wants a resource zip file in the contructor // but the composite res is not a zip - so hand it a dummy fakeResZip = new File(playground, "FakeResourceZipFile.zip"); writeZipfile(fakeResZip); ApkBuilder b = new ApkBuilder(generatedApkPath, fakeResZip.getPath(), playground.getAbsolutePath() + "/classes.dex", null, null, null); b.addSourceFolder(template); b.sealApk(); } catch (Exception e) { callbackContext.error("ApkBuilder Error: " + e.getMessage()); return; } // sign the APK with the supplied key/cert try { ZipSigner zipSigner = new ZipSigner(); X509Certificate cert = zipSigner.readPublicKey(publicKeyUrl); PrivateKey pk = zipSigner.readPrivateKey(privateKeyUrl, privateKeyPass); zipSigner.setKeys("xx", cert, pk, null); zipSigner.signZip(generatedApkPath, signedApkPath); } catch (Exception e) { callbackContext.error("ZipSigner Error: " + e.getMessage()); return; } // After signing apk , delete intermediate stuff try { new File(generatedApkPath).delete(); fakeResZip.delete(); deleteDir(archive); } catch (Exception e) { callbackContext.error("Error cleaning up: " + e.getMessage()); return; } callbackContext.success("succes for " + appName); }