You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by ma...@apache.org on 2012/02/03 16:43:10 UTC
[7/15] Rename to Cordova
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/ExifHelper.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/ExifHelper.java b/framework/src/com/phonegap/ExifHelper.java
deleted file mode 100644
index 6b63edd..0000000
--- a/framework/src/com/phonegap/ExifHelper.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import java.io.IOException;
-
-import android.media.ExifInterface;
-
-public class ExifHelper {
- private String aperature = null;
- private String datetime = null;
- private String exposureTime = null;
- private String flash = null;
- private String focalLength = null;
- private String gpsAltitude = null;
- private String gpsAltitudeRef = null;
- private String gpsDateStamp = null;
- private String gpsLatitude = null;
- private String gpsLatitudeRef = null;
- private String gpsLongitude = null;
- private String gpsLongitudeRef = null;
- private String gpsProcessingMethod = null;
- private String gpsTimestamp = null;
- private String iso = null;
- private String make = null;
- private String model = null;
- private String orientation = null;
- private String whiteBalance = null;
-
- private ExifInterface inFile = null;
- private ExifInterface outFile = null;
-
- /**
- * The file before it is compressed
- *
- * @param filePath
- * @throws IOException
- */
- public void createInFile(String filePath) throws IOException {
- this.inFile = new ExifInterface(filePath);
- }
-
- /**
- * The file after it has been compressed
- *
- * @param filePath
- * @throws IOException
- */
- public void createOutFile(String filePath) throws IOException {
- this.outFile = new ExifInterface(filePath);
- }
-
- /**
- * Reads all the EXIF data from the input file.
- */
- public void readExifData() {
- this.aperature = inFile.getAttribute(ExifInterface.TAG_APERTURE);
- this.datetime = inFile.getAttribute(ExifInterface.TAG_DATETIME);
- this.exposureTime = inFile.getAttribute(ExifInterface.TAG_EXPOSURE_TIME);
- this.flash = inFile.getAttribute(ExifInterface.TAG_FLASH);
- this.focalLength = inFile.getAttribute(ExifInterface.TAG_FOCAL_LENGTH);
- this.gpsAltitude = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE);
- this.gpsAltitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF);
- this.gpsDateStamp = inFile.getAttribute(ExifInterface.TAG_GPS_DATESTAMP);
- this.gpsLatitude = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
- this.gpsLatitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
- this.gpsLongitude = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
- this.gpsLongitudeRef = inFile.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
- this.gpsProcessingMethod = inFile.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD);
- this.gpsTimestamp = inFile.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP);
- this.iso = inFile.getAttribute(ExifInterface.TAG_ISO);
- this.make = inFile.getAttribute(ExifInterface.TAG_MAKE);
- this.model = inFile.getAttribute(ExifInterface.TAG_MODEL);
- this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION);
- this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE);
- }
-
- /**
- * Writes the previously stored EXIF data to the output file.
- *
- * @throws IOException
- */
- public void writeExifData() throws IOException {
- // Don't try to write to a null file
- if (this.outFile == null) {
- return;
- }
-
- if (this.aperature != null) {
- this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperature);
- }
- if (this.datetime != null) {
- this.outFile.setAttribute(ExifInterface.TAG_DATETIME, this.datetime);
- }
- if (this.exposureTime != null) {
- this.outFile.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, this.exposureTime);
- }
- if (this.flash != null) {
- this.outFile.setAttribute(ExifInterface.TAG_FLASH, this.flash);
- }
- if (this.focalLength != null) {
- this.outFile.setAttribute(ExifInterface.TAG_FOCAL_LENGTH, this.focalLength);
- }
- if (this.gpsAltitude != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, this.gpsAltitude);
- }
- if (this.gpsAltitudeRef != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, this.gpsAltitudeRef);
- }
- if (this.gpsDateStamp != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, this.gpsDateStamp);
- }
- if (this.gpsLatitude != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE, this.gpsLatitude);
- }
- if (this.gpsLatitudeRef != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, this.gpsLatitudeRef);
- }
- if (this.gpsLongitude != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, this.gpsLongitude);
- }
- if (this.gpsLongitudeRef != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, this.gpsLongitudeRef);
- }
- if (this.gpsProcessingMethod != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, this.gpsProcessingMethod);
- }
- if (this.gpsTimestamp != null) {
- this.outFile.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, this.gpsTimestamp);
- }
- if (this.iso != null) {
- this.outFile.setAttribute(ExifInterface.TAG_ISO, this.iso);
- }
- if (this.make != null) {
- this.outFile.setAttribute(ExifInterface.TAG_MAKE, this.make);
- }
- if (this.model != null) {
- this.outFile.setAttribute(ExifInterface.TAG_MODEL, this.model);
- }
- if (this.orientation != null) {
- this.outFile.setAttribute(ExifInterface.TAG_ORIENTATION, this.orientation);
- }
- if (this.whiteBalance != null) {
- this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance);
- }
-
- this.outFile.saveAttributes();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/FileTransfer.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/FileTransfer.java b/framework/src/com/phonegap/FileTransfer.java
deleted file mode 100644
index a75f768..0000000
--- a/framework/src/com/phonegap/FileTransfer.java
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Iterator;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.net.Uri;
-import android.util.Log;
-import android.webkit.CookieManager;
-
-import com.phonegap.api.Plugin;
-import com.phonegap.api.PluginResult;
-
-public class FileTransfer extends Plugin {
-
- private static final String LOG_TAG = "FileTransfer";
- private static final String LINE_START = "--";
- private static final String LINE_END = "\r\n";
- private static final String BOUNDRY = "*****";
-
- public static int FILE_NOT_FOUND_ERR = 1;
- public static int INVALID_URL_ERR = 2;
- public static int CONNECTION_ERR = 3;
-
- private SSLSocketFactory defaultSSLSocketFactory = null;
- private HostnameVerifier defaultHostnameVerifier = null;
-
- /* (non-Javadoc)
- * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
- */
- @Override
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- String source = null;
- String target = null;
- try {
- source = args.getString(0);
- target = args.getString(1);
- }
- catch (JSONException e) {
- Log.d(LOG_TAG, "Missing source or target");
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing source or target");
- }
-
- try {
- if (action.equals("upload")) {
- // Setup the options
- String fileKey = null;
- String fileName = null;
- String mimeType = null;
-
- fileKey = getArgument(args, 2, "file");
- fileName = getArgument(args, 3, "image.jpg");
- mimeType = getArgument(args, 4, "image/jpeg");
- JSONObject params = args.optJSONObject(5);
- boolean trustEveryone = args.optBoolean(6);
- boolean chunkedMode = args.optBoolean(7);
- FileUploadResult r = upload(source, target, fileKey, fileName, mimeType, params, trustEveryone, chunkedMode);
- Log.d(LOG_TAG, "****** About to return a result from upload");
- return new PluginResult(PluginResult.Status.OK, r.toJSONObject());
- } else if (action.equals("download")) {
- JSONObject r = download(source, target);
- Log.d(LOG_TAG, "****** About to return a result from download");
- return new PluginResult(PluginResult.Status.OK, r, "window.localFileSystem._castEntry");
- } else {
- return new PluginResult(PluginResult.Status.INVALID_ACTION);
- }
- } catch (FileNotFoundException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } catch (IllegalArgumentException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } catch (SSLException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- Log.d(LOG_TAG, "Got my ssl exception!!!");
- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } catch (IOException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target);
- return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
- } catch (JSONException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
- }
-
- // always verify the host - don't check for certificate
- final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- };
-
- /**
- * This function will install a trust manager that will blindly trust all SSL
- * certificates. The reason this code is being added is to enable developers
- * to do development using self signed SSL certificates on their web server.
- *
- * The standard HttpsURLConnection class will throw an exception on self
- * signed certificates if this code is not run.
- */
- private void trustAllHosts() {
- // Create a trust manager that does not validate certificate chains
- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[] {};
- }
-
- public void checkClientTrusted(X509Certificate[] chain,
- String authType) throws CertificateException {
- }
-
- public void checkServerTrusted(X509Certificate[] chain,
- String authType) throws CertificateException {
- }
- } };
-
- // Install the all-trusting trust manager
- try {
- // Backup the current SSL socket factory
- defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
- // Install our all trusting manager
- SSLContext sc = SSLContext.getInstance("TLS");
- sc.init(null, trustAllCerts, new java.security.SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- } catch (Exception e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- }
- }
-
- /**
- * Create an error object based on the passed in errorCode
- * @param errorCode the error
- * @return JSONObject containing the error
- */
- private JSONObject createFileTransferError(int errorCode, String source, String target) {
- JSONObject error = null;
- try {
- error = new JSONObject();
- error.put("code", errorCode);
- error.put("source", source);
- error.put("target", target);
- } catch (JSONException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- }
- return error;
- }
-
- /**
- * Convenience method to read a parameter from the list of JSON args.
- * @param args the args passed to the Plugin
- * @param position the position to retrieve the arg from
- * @param defaultString the default to be used if the arg does not exist
- * @return String with the retrieved value
- */
- private String getArgument(JSONArray args, int position, String defaultString) {
- String arg = defaultString;
- if(args.length() >= position) {
- arg = args.optString(position);
- if (arg == null || "null".equals(arg)) {
- arg = defaultString;
- }
- }
- return arg;
- }
-
- /**
- * Uploads the specified file to the server URL provided using an HTTP
- * multipart request.
- * @param file Full path of the file on the file system
- * @param server URL of the server to receive the file
- * @param fileKey Name of file request parameter
- * @param fileName File name to be used on server
- * @param mimeType Describes file content type
- * @param params key:value pairs of user-defined parameters
- * @return FileUploadResult containing result of upload request
- */
- public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
- final String mimeType, JSONObject params, boolean trustEveryone, boolean chunkedMode) throws IOException, SSLException {
- // Create return object
- FileUploadResult result = new FileUploadResult();
-
- // Get a input stream of the file on the phone
- InputStream fileInputStream = getPathFromUri(file);
-
- HttpURLConnection conn = null;
- DataOutputStream dos = null;
-
- int bytesRead, bytesAvailable, bufferSize;
- long totalBytes;
- byte[] buffer;
- int maxBufferSize = 8096;
-
- //------------------ CLIENT REQUEST
- // open a URL connection to the server
- URL url = new URL(server);
-
- // Open a HTTP connection to the URL based on protocol
- if (url.getProtocol().toLowerCase().equals("https")) {
- // Using standard HTTPS connection. Will not allow self signed certificate
- if (!trustEveryone) {
- conn = (HttpsURLConnection) url.openConnection();
- }
- // Use our HTTPS connection that blindly trusts everyone.
- // This should only be used in debug environments
- else {
- // Setup the HTTPS connection class to trust everyone
- trustAllHosts();
- HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
- // Save the current hostnameVerifier
- defaultHostnameVerifier = https.getHostnameVerifier();
- // Setup the connection not to verify hostnames
- https.setHostnameVerifier(DO_NOT_VERIFY);
- conn = https;
- }
- }
- // Return a standard HTTP connection
- else {
- conn = (HttpURLConnection) url.openConnection();
- }
-
- // Allow Inputs
- conn.setDoInput(true);
-
- // Allow Outputs
- conn.setDoOutput(true);
-
- // Don't use a cached copy.
- conn.setUseCaches(false);
-
- // Use a post method.
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
-
- // Set the cookies on the response
- String cookie = CookieManager.getInstance().getCookie(server);
- if (cookie != null) {
- conn.setRequestProperty("Cookie", cookie);
- }
-
- // Should set this up as an option
- if (chunkedMode) {
- conn.setChunkedStreamingMode(maxBufferSize);
- }
-
- dos = new DataOutputStream( conn.getOutputStream() );
-
- // Send any extra parameters
- try {
- for (Iterator iter = params.keys(); iter.hasNext();) {
- Object key = iter.next();
- dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
- dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\";");
- dos.writeBytes(LINE_END + LINE_END);
- dos.write(params.getString(key.toString()).getBytes());
- dos.writeBytes(LINE_END);
- }
- } catch (JSONException e) {
- Log.e(LOG_TAG, e.getMessage(), e);
- }
-
- dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
- dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName +"\"" + LINE_END);
- dos.writeBytes("Content-Type: " + mimeType + LINE_END);
- dos.writeBytes(LINE_END);
-
- // create a buffer of maximum size
- bytesAvailable = fileInputStream.available();
- bufferSize = Math.min(bytesAvailable, maxBufferSize);
- buffer = new byte[bufferSize];
-
- // read file and write it into form...
- bytesRead = fileInputStream.read(buffer, 0, bufferSize);
- totalBytes = 0;
-
- while (bytesRead > 0) {
- totalBytes += bytesRead;
- result.setBytesSent(totalBytes);
- dos.write(buffer, 0, bufferSize);
- bytesAvailable = fileInputStream.available();
- bufferSize = Math.min(bytesAvailable, maxBufferSize);
- bytesRead = fileInputStream.read(buffer, 0, bufferSize);
- }
-
- // send multipart form data necesssary after file data...
- dos.writeBytes(LINE_END);
- dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);
-
- // close streams
- fileInputStream.close();
- dos.flush();
- dos.close();
-
- //------------------ read the SERVER RESPONSE
- StringBuffer responseString = new StringBuffer("");
- DataInputStream inStream;
- try {
- inStream = new DataInputStream ( conn.getInputStream() );
- } catch(FileNotFoundException e) {
- throw new IOException("Received error from server");
- }
-
- String line;
- while (( line = inStream.readLine()) != null) {
- responseString.append(line);
- }
- Log.d(LOG_TAG, "got response from server");
- Log.d(LOG_TAG, responseString.toString());
-
- // send request and retrieve response
- result.setResponseCode(conn.getResponseCode());
- result.setResponse(responseString.toString());
-
- inStream.close();
- conn.disconnect();
-
- // Revert back to the proper verifier and socket factories
- if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
- ((HttpsURLConnection)conn).setHostnameVerifier(defaultHostnameVerifier);
- HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
- }
-
- return result;
- }
-
- /**
- * 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
- * @return JSONObject the downloaded file
- */
- public JSONObject download(String source, String target) throws IOException {
- try {
- File file = new File(target);
-
- // create needed directories
- file.getParentFile().mkdirs();
-
- // connect to server
- URL url = new URL(source);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("GET");
- connection.connect();
-
- Log.d(LOG_TAG, "Download file:" + url);
-
- InputStream inputStream = connection.getInputStream();
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
-
- FileOutputStream outputStream = new FileOutputStream(file);
-
- // write bytes to file
- while ( (bytesRead = inputStream.read(buffer)) > 0 ) {
- outputStream.write(buffer,0, bytesRead);
- }
-
- outputStream.close();
-
- Log.d(LOG_TAG, "Saved file: " + target);
-
- // create FileEntry object
- FileUtils fileUtil = new FileUtils();
-
- return fileUtil.getEntry(file);
- } catch (Exception e) {
- Log.d(LOG_TAG, e.getMessage(), e);
- throw new IOException("Error while downloading");
- }
- }
-
- /**
- * Get an input stream based on file path or content:// uri
- *
- * @param path
- * @return an input stream
- * @throws FileNotFoundException
- */
- private InputStream getPathFromUri(String path) throws FileNotFoundException {
- if (path.startsWith("content:")) {
- Uri uri = Uri.parse(path);
- return ctx.getContentResolver().openInputStream(uri);
- }
- else if (path.startsWith("file://")) {
- int question = path.indexOf("?");
- if (question == -1) {
- return new FileInputStream(path.substring(7));
- } else {
- return new FileInputStream(path.substring(7, question));
- }
- }
- else {
- return new FileInputStream(path);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/FileUploadResult.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/FileUploadResult.java b/framework/src/com/phonegap/FileUploadResult.java
deleted file mode 100644
index 245cf13..0000000
--- a/framework/src/com/phonegap/FileUploadResult.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-/**
- * Encapsulates the result and/or status of uploading a file to a remote server.
- */
-public class FileUploadResult {
-
- private long bytesSent = 0; // bytes sent
- private int responseCode = -1; // HTTP response code
- private String response = null; // HTTP response
-
- public long getBytesSent() {
- return bytesSent;
- }
-
- public void setBytesSent(long bytes) {
- this.bytesSent = bytes;
- }
-
- public int getResponseCode() {
- return responseCode;
- }
-
- public void setResponseCode(int responseCode) {
- this.responseCode = responseCode;
- }
-
- public String getResponse() {
- return response;
- }
-
- public void setResponse(String response) {
- this.response = response;
- }
-
- public JSONObject toJSONObject() throws JSONException {
- return new JSONObject(
- "{bytesSent:" + bytesSent +
- ",responseCode:" + responseCode +
- ",response:" + JSONObject.quote(response) + "}");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/FileUtils.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/FileUtils.java b/framework/src/com/phonegap/FileUtils.java
deleted file mode 100755
index b20652a..0000000
--- a/framework/src/com/phonegap/FileUtils.java
+++ /dev/null
@@ -1,1024 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import java.io.*;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLDecoder;
-import java.nio.channels.FileChannel;
-
-import org.apache.commons.codec.binary.Base64;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.Environment;
-import android.provider.MediaStore;
-import android.util.Log;
-import android.webkit.MimeTypeMap;
-
-import com.phonegap.api.PhonegapActivity;
-import com.phonegap.api.Plugin;
-import com.phonegap.api.PluginResult;
-import com.phonegap.file.EncodingException;
-import com.phonegap.file.FileExistsException;
-import com.phonegap.file.InvalidModificationException;
-import com.phonegap.file.NoModificationAllowedException;
-import com.phonegap.file.TypeMismatchException;
-
-/**
- * This class provides SD card file and directory services to JavaScript.
- * Only files on the SD card can be accessed.
- */
-public class FileUtils extends Plugin {
- private static final String LOG_TAG = "FileUtils";
- private static final String _DATA = "_data"; // The column name where the file path is stored
-
- public static int NOT_FOUND_ERR = 1;
- public static int SECURITY_ERR = 2;
- public static int ABORT_ERR = 3;
-
- public static int NOT_READABLE_ERR = 4;
- public static int ENCODING_ERR = 5;
- public static int NO_MODIFICATION_ALLOWED_ERR = 6;
- public static int INVALID_STATE_ERR = 7;
- public static int SYNTAX_ERR = 8;
- public static int INVALID_MODIFICATION_ERR = 9;
- public static int QUOTA_EXCEEDED_ERR = 10;
- public static int TYPE_MISMATCH_ERR = 11;
- public static int PATH_EXISTS_ERR = 12;
-
- public static int TEMPORARY = 0;
- public static int PERSISTENT = 1;
- public static int RESOURCE = 2;
- public static int APPLICATION = 3;
-
- FileReader f_in;
- FileWriter f_out;
-
- /**
- * Constructor.
- */
- public FileUtils() {
- }
-
- /**
- * Executes the request and returns PluginResult.
- *
- * @param action The action to execute.
- * @param args JSONArry of arguments for the plugin.
- * @param callbackId The callback id used when calling back into JavaScript.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult.Status status = PluginResult.Status.OK;
- String result = "";
- //System.out.println("FileUtils.execute("+action+")");
-
- try {
- try {
- if (action.equals("testSaveLocationExists")) {
- boolean b = DirectoryManager.testSaveLocationExists();
- return new PluginResult(status, b);
- }
- else if (action.equals("getFreeDiskSpace")) {
- long l = DirectoryManager.getFreeDiskSpace(false);
- return new PluginResult(status, l);
- }
- else if (action.equals("testFileExists")) {
- boolean b = DirectoryManager.testFileExists(args.getString(0));
- return new PluginResult(status, b);
- }
- else if (action.equals("testDirectoryExists")) {
- boolean b = DirectoryManager.testFileExists(args.getString(0));
- return new PluginResult(status, b);
- }
- else if (action.equals("readAsText")) {
- String s = this.readAsText(args.getString(0), args.getString(1));
- return new PluginResult(status, s);
- }
- else if (action.equals("readAsDataURL")) {
- String s = this.readAsDataURL(args.getString(0));
- return new PluginResult(status, s);
- }
- else if (action.equals("write")) {
- long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2));
- return new PluginResult(status, fileSize);
- }
- else if (action.equals("truncate")) {
- long fileSize = this.truncateFile(args.getString(0), args.getLong(1));
- return new PluginResult(status, fileSize);
- }
- else if (action.equals("requestFileSystem")) {
- long size = args.optLong(1);
- if (size != 0) {
- if (size > (DirectoryManager.getFreeDiskSpace(true)*1024)) {
- JSONObject error = new JSONObject().put("code", FileUtils.QUOTA_EXCEEDED_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- }
- }
- JSONObject obj = requestFileSystem(args.getInt(0));
- return new PluginResult(status, obj, "window.localFileSystem._castFS");
- }
- else if (action.equals("resolveLocalFileSystemURI")) {
- JSONObject obj = resolveLocalFileSystemURI(args.getString(0));
- return new PluginResult(status, obj, "window.localFileSystem._castEntry");
- }
- else if (action.equals("getMetadata")) {
- JSONObject obj = getMetadata(args.getString(0));
- return new PluginResult(status, obj, "window.localFileSystem._castDate");
- }
- else if (action.equals("getFileMetadata")) {
- JSONObject obj = getFileMetadata(args.getString(0));
- return new PluginResult(status, obj, "window.localFileSystem._castDate");
- }
- else if (action.equals("getParent")) {
- JSONObject obj = getParent(args.getString(0));
- return new PluginResult(status, obj, "window.localFileSystem._castEntry");
- }
- else if (action.equals("getDirectory")) {
- JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), true);
- return new PluginResult(status, obj, "window.localFileSystem._castEntry");
- }
- else if (action.equals("getFile")) {
- JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), false);
- return new PluginResult(status, obj, "window.localFileSystem._castEntry");
- }
- else if (action.equals("remove")) {
- boolean success;
-
- success = remove(args.getString(0));
-
- if (success) {
- notifyDelete(args.getString(0));
- return new PluginResult(status);
- } else {
- JSONObject error = new JSONObject().put("code", FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- }
- }
- else if (action.equals("removeRecursively")) {
- boolean success = removeRecursively(args.getString(0));
- if (success) {
- return new PluginResult(status);
- } else {
- JSONObject error = new JSONObject().put("code", FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- }
- }
- else if (action.equals("moveTo")) {
- JSONObject entry = transferTo(args.getString(0), args.getJSONObject(1), args.optString(2), true);
- return new PluginResult(status, entry, "window.localFileSystem._castEntry");
- }
- else if (action.equals("copyTo")) {
- JSONObject entry = transferTo(args.getString(0), args.getJSONObject(1), args.optString(2), false);
- return new PluginResult(status, entry, "window.localFileSystem._castEntry");
- }
- else if (action.equals("readEntries")) {
- JSONArray entries = readEntries(args.getString(0));
- return new PluginResult(status, entries, "window.localFileSystem._castEntries");
- }
- return new PluginResult(status, result);
- } catch (FileNotFoundException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.NOT_FOUND_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (FileExistsException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.PATH_EXISTS_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (NoModificationAllowedException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (JSONException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (InvalidModificationException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.INVALID_MODIFICATION_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (MalformedURLException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.ENCODING_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (IOException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.INVALID_MODIFICATION_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (EncodingException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.ENCODING_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- } catch (TypeMismatchException e) {
- JSONObject error = new JSONObject().put("code", FileUtils.TYPE_MISMATCH_ERR);
- return new PluginResult(PluginResult.Status.ERROR, error);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
- }
-
- /**
- * Need to check to see if we need to clean up the content store
- *
- * @param filePath the path to check
- */
- private void notifyDelete(String filePath) {
- int result = this.ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
- MediaStore.Images.Media.DATA + " = ?",
- new String[] {filePath});
- }
-
- /**
- * Allows the user to look up the Entry for a file or directory referred to by a local URI.
- *
- * @param url of the file/directory to look up
- * @return a JSONObject representing a Entry from the filesystem
- * @throws MalformedURLException if the url is not valid
- * @throws FileNotFoundException if the file does not exist
- * @throws IOException if the user can't read the file
- * @throws JSONException
- */
- private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException {
- String decoded = URLDecoder.decode(url, "UTF-8");
-
- File fp = null;
-
- // Handle the special case where you get an Android content:// uri.
- if (decoded.startsWith("content:")) {
- Cursor cursor = this.ctx.managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
- // Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- fp = new File(cursor.getString(column_index));
- } else {
- // Test to see if this is a valid URL first
- @SuppressWarnings("unused")
- URL testUrl = new URL(decoded);
-
- if (decoded.startsWith("file://")) {
- fp = new File(decoded.substring(7, decoded.length()));
- } else {
- fp = new File(decoded);
- }
- }
-
- if (!fp.exists()) {
- throw new FileNotFoundException();
- }
- if (!fp.canRead()) {
- throw new IOException();
- }
- return getEntry(fp);
- }
-
- /**
- * Read the list of files from this directory.
- *
- * @param fileName the directory to read from
- * @return a JSONArray containing JSONObjects that represent Entry objects.
- * @throws FileNotFoundException if the directory is not found.
- * @throws JSONException
- */
- private JSONArray readEntries(String fileName) throws FileNotFoundException, JSONException {
- File fp = new File(fileName);
-
- if (!fp.exists()) {
- // The directory we are listing doesn't exist so we should fail.
- throw new FileNotFoundException();
- }
-
- JSONArray entries = new JSONArray();
-
- if (fp.isDirectory()) {
- File[] files = fp.listFiles();
- for (int i=0; i<files.length; i++) {
- entries.put(getEntry(files[i]));
- }
- }
-
- return entries;
- }
-
- /**
- * A setup method that handles the move/copy of files/directories
- *
- * @param fileName to be copied/moved
- * @param newParent is the location where the file will be copied/moved to
- * @param newName for the file directory to be called, if null use existing file name
- * @param move if false do a copy, if true do a move
- * @return a Entry object
- * @throws NoModificationAllowedException
- * @throws IOException
- * @throws InvalidModificationException
- * @throws EncodingException
- * @throws JSONException
- */
- private JSONObject transferTo(String fileName, JSONObject newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException {
- // Check for invalid file name
- if (newName != null && newName.contains(":")) {
- throw new EncodingException("Bad file name");
- }
-
- File source = new File(fileName);
-
- if (!source.exists()) {
- // The file/directory we are copying doesn't exist so we should fail.
- throw new FileNotFoundException("The source does not exist");
- }
-
- File destinationDir = new File(newParent.getString("fullPath"));
- if (!destinationDir.exists()) {
- // The destination does not exist so we should fail.
- throw new FileNotFoundException("The source does not exist");
- }
-
- // Figure out where we should be copying to
- File destination = createDestination(newName, source, destinationDir);
-
- //Log.d(LOG_TAG, "Source: " + source.getAbsolutePath());
- //Log.d(LOG_TAG, "Destin: " + destination.getAbsolutePath());
-
- // Check to see if source and destination are the same file
- if (source.getAbsolutePath().equals(destination.getAbsolutePath())) {
- throw new InvalidModificationException("Can't copy a file onto itself");
- }
-
- if (source.isDirectory()) {
- if (move) {
- return moveDirectory(source, destination);
- } else {
- return copyDirectory(source, destination);
- }
- } else {
- if (move) {
- return moveFile(source, destination);
- } else {
- return copyFile(source, destination);
- }
- }
- }
-
- /**
- * Creates the destination File object based on name passed in
- *
- * @param newName for the file directory to be called, if null use existing file name
- * @param fp represents the source file
- * @param destination represents the destination file
- * @return a File object that represents the destination
- */
- private File createDestination(String newName, File fp, File destination) {
- File destFile = null;
-
- // I know this looks weird but it is to work around a JSON bug.
- if ("null".equals(newName) || "".equals(newName) ) {
- newName = null;
- }
-
- if (newName != null) {
- destFile = new File(destination.getAbsolutePath() + File.separator + newName);
- } else {
- destFile = new File(destination.getAbsolutePath() + File.separator + fp.getName());
- }
- return destFile;
- }
-
- /**
- * Copy a file
- *
- * @param srcFile file to be copied
- * @param destFile destination to be copied to
- * @return a FileEntry object
- * @throws IOException
- * @throws InvalidModificationException
- * @throws JSONException
- */
- private JSONObject copyFile(File srcFile, File destFile) throws IOException, InvalidModificationException, JSONException {
- // Renaming a file to an existing directory should fail
- if (destFile.exists() && destFile.isDirectory()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- FileChannel input = new FileInputStream(srcFile).getChannel();
- FileChannel output = new FileOutputStream(destFile).getChannel();
-
- input.transferTo(0, input.size(), output);
-
- input.close();
- output.close();
-
- /*
- if (srcFile.length() != destFile.length()) {
- return false;
- }
- */
-
- return getEntry(destFile);
- }
-
- /**
- * Copy a directory
- *
- * @param srcDir directory to be copied
- * @param destinationDir destination to be copied to
- * @return a DirectoryEntry object
- * @throws JSONException
- * @throws IOException
- * @throws NoModificationAllowedException
- * @throws InvalidModificationException
- */
- private JSONObject copyDirectory(File srcDir, File destinationDir) throws JSONException, IOException, NoModificationAllowedException, InvalidModificationException {
- // Renaming a file to an existing directory should fail
- if (destinationDir.exists() && destinationDir.isFile()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Check to make sure we are not copying the directory into itself
- if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
- throw new InvalidModificationException("Can't copy itself into itself");
- }
-
- // See if the destination directory exists. If not create it.
- if (!destinationDir.exists()) {
- if (!destinationDir.mkdir()) {
- // If we can't create the directory then fail
- throw new NoModificationAllowedException("Couldn't create the destination direcotry");
- }
- }
-
- for (File file : srcDir.listFiles()) {
- if (file.isDirectory()) {
- copyDirectory(file, destinationDir);
- } else {
- File destination = new File(destinationDir.getAbsoluteFile() + File.separator + file.getName());
- copyFile(file, destination);
- }
- }
-
- return getEntry(destinationDir);
- }
-
- /**
- * Check to see if the user attempted to copy an entry into its parent without changing its name,
- * or attempted to copy a directory into a directory that it contains directly or indirectly.
- *
- * @param srcDir
- * @param destinationDir
- * @return
- */
- private boolean isCopyOnItself(String src, String dest) {
-
- // This weird test is to determine if we are copying or moving a directory into itself.
- // Copy /sdcard/myDir to /sdcard/myDir-backup is okay but
- // Copy /sdcard/myDir to /sdcard/myDir/backup should thow an INVALID_MODIFICATION_ERR
- if (dest.startsWith(src) && dest.indexOf(File.separator, src.length()-1) != -1) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Move a file
- *
- * @param srcFile file to be copied
- * @param destFile destination to be copied to
- * @return a FileEntry object
- * @throws IOException
- * @throws InvalidModificationException
- * @throws JSONException
- */
- private JSONObject moveFile(File srcFile, File destFile) throws JSONException, InvalidModificationException {
- // Renaming a file to an existing directory should fail
- if (destFile.exists() && destFile.isDirectory()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Try to rename the file
- if (!srcFile.renameTo(destFile)) {
- // Trying to rename the file failed. Possibly because we moved across file system on the device.
- // Now we have to do things the hard way
- // 1) Copy all the old file
- // 2) delete the src file
- }
-
- return getEntry(destFile);
- }
-
- /**
- * Move a directory
- *
- * @param srcDir directory to be copied
- * @param destinationDir destination to be copied to
- * @return a DirectoryEntry object
- * @throws JSONException
- * @throws IOException
- * @throws InvalidModificationException
- */
- private JSONObject moveDirectory(File srcDir, File destinationDir) throws JSONException, InvalidModificationException {
- // Renaming a file to an existing directory should fail
- if (destinationDir.exists() && destinationDir.isFile()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Check to make sure we are not copying the directory into itself
- if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
- throw new InvalidModificationException("Can't move itself into itself");
- }
-
- // If the destination directory already exists and is empty then delete it. This is according to spec.
- if (destinationDir.exists()) {
- if (destinationDir.list().length > 0) {
- throw new InvalidModificationException("directory is not empty");
- }
- }
-
- // Try to rename the directory
- if (!srcDir.renameTo(destinationDir)) {
- // Trying to rename the directory failed. Possibly because we moved across file system on the device.
- // Now we have to do things the hard way
- // 1) Copy all the old files
- // 2) delete the src directory
- }
-
- return getEntry(destinationDir);
- }
-
- /**
- * Deletes a directory and all of its contents, if any. In the event of an error
- * [e.g. trying to delete a directory that contains a file that cannot be removed],
- * some of the contents of the directory may be deleted.
- * It is an error to attempt to delete the root directory of a filesystem.
- *
- * @param filePath the directory to be removed
- * @return a boolean representing success of failure
- * @throws FileExistsException
- */
- private boolean removeRecursively(String filePath) throws FileExistsException {
- File fp = new File(filePath);
-
- // You can't delete the root directory.
- if (atRootDirectory(filePath)) {
- return false;
- }
-
- return removeDirRecursively(fp);
- }
-
- /**
- * Loops through a directory deleting all the files.
- *
- * @param directory to be removed
- * @return a boolean representing success of failure
- * @throws FileExistsException
- */
- private boolean removeDirRecursively(File directory) throws FileExistsException {
- if (directory.isDirectory()) {
- for (File file : directory.listFiles()) {
- removeDirRecursively(file);
- }
- }
-
- if (!directory.delete()) {
- throw new FileExistsException("could not delete: " + directory.getName());
- } else {
- return true;
- }
- }
-
- /**
- * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty.
- * It is an error to attempt to delete the root directory of a filesystem.
- *
- * @param filePath file or directory to be removed
- * @return a boolean representing success of failure
- * @throws NoModificationAllowedException
- * @throws InvalidModificationException
- */
- private boolean remove(String filePath) throws NoModificationAllowedException, InvalidModificationException {
- File fp = new File(filePath);
-
- // You can't delete the root directory.
- if (atRootDirectory(filePath)) {
- throw new NoModificationAllowedException("You can't delete the root directory");
- }
-
- // You can't delete a directory that is not empty
- if (fp.isDirectory() && fp.list().length > 0) {
- throw new InvalidModificationException("You can't delete a directory that is not empty.");
- }
-
- return fp.delete();
- }
-
- /**
- * Creates or looks up a file.
- *
- * @param dirPath base directory
- * @param fileName file/directory to lookup or create
- * @param options specify whether to create or not
- * @param directory if true look up directory, if false look up file
- * @return a Entry object
- * @throws FileExistsException
- * @throws IOException
- * @throws TypeMismatchException
- * @throws EncodingException
- * @throws JSONException
- */
- private JSONObject getFile(String dirPath, String fileName, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
- boolean create = false;
- boolean exclusive = false;
- if (options != null) {
- create = options.optBoolean("create");
- if (create) {
- exclusive = options.optBoolean("exclusive");
- }
- }
-
- // Check for a ":" character in the file to line up with BB and iOS
- if (fileName.contains(":")) {
- throw new EncodingException("This file has a : in it's name");
- }
-
- File fp = createFileObject(dirPath, fileName);
-
- if (create) {
- if (exclusive && fp.exists()) {
- throw new FileExistsException("create/exclusive fails");
- }
- if (directory) {
- fp.mkdir();
- } else {
- fp.createNewFile();
- }
- if (!fp.exists()) {
- throw new FileExistsException("create fails");
- }
- }
- else {
- if (!fp.exists()) {
- throw new FileNotFoundException("path does not exist");
- }
- if (directory) {
- if (fp.isFile()) {
- throw new TypeMismatchException("path doesn't exist or is file");
- }
- } else {
- if (fp.isDirectory()) {
- throw new TypeMismatchException("path doesn't exist or is directory");
- }
- }
- }
-
- // Return the directory
- return getEntry(fp);
- }
-
- /**
- * If the path starts with a '/' just return that file object. If not construct the file
- * object from the path passed in and the file name.
- *
- * @param dirPath root directory
- * @param fileName new file name
- * @return
- */
- private File createFileObject(String dirPath, String fileName) {
- File fp = null;
- if (fileName.startsWith("/")) {
- fp = new File(fileName);
- } else {
- fp = new File(dirPath + File.separator + fileName);
- }
- return fp;
- }
-
- /**
- * Look up the parent DirectoryEntry containing this Entry.
- * If this Entry is the root of its filesystem, its parent is itself.
- *
- * @param filePath
- * @return
- * @throws JSONException
- */
- private JSONObject getParent(String filePath) throws JSONException {
- if (atRootDirectory(filePath)) {
- return getEntry(filePath);
- }
- return getEntry(new File(filePath).getParent());
- }
-
- /**
- * Checks to see if we are at the root directory. Useful since we are
- * not allow to delete this directory.
- *
- * @param filePath to directory
- * @return true if we are at the root, false otherwise.
- */
- private boolean atRootDirectory(String filePath) {
- if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + ctx.getPackageName() + "/cache") ||
- filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
- return true;
- }
- return false;
- }
-
- /**
- * Look up metadata about this entry.
- *
- * @param filePath to entry
- * @return a Metadata object
- * @throws FileNotFoundException
- * @throws JSONException
- */
- private JSONObject getMetadata(String filePath) throws FileNotFoundException, JSONException {
- File file = new File(filePath);
-
- if (!file.exists()) {
- throw new FileNotFoundException("Failed to find file in getMetadata");
- }
-
- JSONObject metadata = new JSONObject();
- metadata.put("modificationTime", file.lastModified());
-
- return metadata;
- }
-
- /**
- * Returns a File that represents the current state of the file that this FileEntry represents.
- *
- * @param filePath to entry
- * @return returns a JSONObject represent a W3C File object
- * @throws FileNotFoundException
- * @throws JSONException
- */
- private JSONObject getFileMetadata(String filePath) throws FileNotFoundException, JSONException {
- File file = new File(filePath);
-
- if (!file.exists()) {
- throw new FileNotFoundException("File: " + filePath + " does not exist.");
- }
-
- JSONObject metadata = new JSONObject();
- metadata.put("size", file.length());
- metadata.put("type", getMimeType(filePath));
- metadata.put("name", file.getName());
- metadata.put("fullPath", file.getAbsolutePath());
- metadata.put("lastModifiedDate", file.lastModified());
-
- return metadata;
- }
-
- /**
- * Requests a filesystem in which to store application data.
- *
- * @param type of file system requested
- * @return a JSONObject representing the file system
- * @throws IOException
- * @throws JSONException
- */
- private JSONObject requestFileSystem(int type) throws IOException, JSONException {
- JSONObject fs = new JSONObject();
- if (type == TEMPORARY) {
- File fp;
- fs.put("name", "temporary");
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- fs.put("root", getEntry(Environment.getExternalStorageDirectory().getAbsolutePath() +
- "/Android/data/" + ctx.getPackageName() + "/cache/"));
-
- // Create the cache dir if it doesn't exist.
- fp = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
- "/Android/data/" + ctx.getPackageName() + "/cache/");
- } else {
- fs.put("root", getEntry("/data/data/" + ctx.getPackageName() + "/cache/"));
- // Create the cache dir if it doesn't exist.
- fp = new File("/data/data/" + ctx.getPackageName() + "/cache/");
- }
- fp.mkdirs();
- }
- else if (type == PERSISTENT) {
- fs.put("name", "persistent");
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- fs.put("root", getEntry(Environment.getExternalStorageDirectory()));
- } else {
- fs.put("root", getEntry("/data/data/" + ctx.getPackageName()));
- }
- }
- else {
- throw new IOException("No filesystem of type requested");
- }
-
- return fs;
- }
-
- /**
- * Returns a JSON Object representing a directory on the device's file system
- *
- * @param path to the directory
- * @return
- * @throws JSONException
- */
- public JSONObject getEntry(File file) throws JSONException {
- JSONObject entry = new JSONObject();
-
- entry.put("isFile", file.isFile());
- entry.put("isDirectory", file.isDirectory());
- entry.put("name", file.getName());
- entry.put("fullPath", file.getAbsolutePath());
- // I can't add the next thing it as it would be an infinite loop
- //entry.put("filesystem", null);
-
- return entry;
- }
-
- /**
- * Returns a JSON Object representing a directory on the device's file system
- *
- * @param path to the directory
- * @return
- * @throws JSONException
- */
- private JSONObject getEntry(String path) throws JSONException {
- return getEntry(new File(path));
- }
-
- /**
- * Identifies if action to be executed returns a value and should be run synchronously.
- *
- * @param action The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- if (action.equals("testSaveLocationExists")) {
- return true;
- }
- else if (action.equals("getFreeDiskSpace")) {
- return true;
- }
- else if (action.equals("testFileExists")) {
- return true;
- }
- else if (action.equals("testDirectoryExists")) {
- return true;
- }
- return false;
- }
-
- //--------------------------------------------------------------------------
- // LOCAL METHODS
- //--------------------------------------------------------------------------
-
- /**
- * Read content of text file.
- *
- * @param filename The name of the file.
- * @param encoding The encoding to return contents as. Typical value is UTF-8.
- * (see http://www.iana.org/assignments/character-sets)
- * @return Contents of file.
- * @throws FileNotFoundException, IOException
- */
- public String readAsText(String filename, String encoding) throws FileNotFoundException, IOException {
- byte[] bytes = new byte[1000];
- BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- int numRead = 0;
- while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
- bos.write(bytes, 0, numRead);
- }
- return new String(bos.toByteArray(), encoding);
- }
-
- /**
- * Read content of text file and return as base64 encoded data url.
- *
- * @param filename The name of the file.
- * @return Contents of file = data:<media type>;base64,<data>
- * @throws FileNotFoundException, IOException
- */
- public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
- byte[] bytes = new byte[1000];
- BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- int numRead = 0;
- while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
- bos.write(bytes, 0, numRead);
- }
-
- // Determine content type from file name
- String contentType = null;
- if (filename.startsWith("content:")) {
- Uri fileUri = Uri.parse(filename);
- contentType = this.ctx.getContentResolver().getType(fileUri);
- }
- else {
- contentType = getMimeType(filename);
- }
-
- byte[] base64 = Base64.encodeBase64(bos.toByteArray());
- String data = "data:" + contentType + ";base64," + new String(base64);
- return data;
- }
-
- /**
- * Looks up the mime type of a given file name.
- *
- * @param filename
- * @return a mime type
- */
- public static String getMimeType(String filename) {
- MimeTypeMap map = MimeTypeMap.getSingleton();
- return map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename));
- }
-
- /**
- * Write contents of file.
- *
- * @param filename The name of the file.
- * @param data The contents of the file.
- * @param offset The position to begin writing the file.
- * @throws FileNotFoundException, IOException
- */
- /**/
- public long write(String filename, String data, int offset) throws FileNotFoundException, IOException {
- boolean append = false;
- if (offset > 0) {
- this.truncateFile(filename, offset);
- append = true;
- }
-
- byte [] rawData = data.getBytes();
- ByteArrayInputStream in = new ByteArrayInputStream(rawData);
- FileOutputStream out = new FileOutputStream(filename, append);
- byte buff[] = new byte[rawData.length];
- in.read(buff, 0, buff.length);
- out.write(buff, 0, rawData.length);
- out.flush();
- out.close();
-
- return data.length();
- }
-
- /**
- * Truncate the file to size
- *
- * @param filename
- * @param size
- * @throws FileNotFoundException, IOException
- */
- private long truncateFile(String filename, long size) throws FileNotFoundException, IOException {
- RandomAccessFile raf = new RandomAccessFile(filename, "rw");
-
- if (raf.length() >= size) {
- FileChannel channel = raf.getChannel();
- channel.truncate(size);
- return size;
- }
-
- return raf.length();
- }
-
- /**
- * Get an input stream based on file path or content:// uri
- *
- * @param path
- * @return an input stream
- * @throws FileNotFoundException
- */
- private InputStream getPathFromUri(String path) throws FileNotFoundException {
- if (path.startsWith("content")) {
- Uri uri = Uri.parse(path);
- return ctx.getContentResolver().openInputStream(uri);
- }
- else {
- return new FileInputStream(path);
- }
- }
-
- /**
- * Queries the media store to find out what the file path is for the Uri we supply
- *
- * @param contentUri the Uri of the audio/image/video
- * @param ctx the current applicaiton context
- * @return the full path to the file
- */
- protected static String getRealPathFromURI(Uri contentUri, PhonegapActivity ctx) {
- String[] proj = { _DATA };
- Cursor cursor = ctx.managedQuery(contentUri, proj, null, null, null);
- int column_index = cursor.getColumnIndexOrThrow(_DATA);
- cursor.moveToFirst();
- return cursor.getString(column_index);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/GeoBroker.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/GeoBroker.java b/framework/src/com/phonegap/GeoBroker.java
deleted file mode 100755
index 5522109..0000000
--- a/framework/src/com/phonegap/GeoBroker.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import java.util.HashMap;
-import java.util.Map.Entry;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-
-import com.phonegap.api.Plugin;
-import com.phonegap.api.PluginResult;
-
-/*
- * This class is the interface to the Geolocation. It's bound to the geo object.
- *
- * This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener
- */
-
-public class GeoBroker extends Plugin {
-
- // List of gGeolocation listeners
- private HashMap<String, GeoListener> geoListeners;
- private GeoListener global;
-
- /**
- * Constructor.
- */
- public GeoBroker() {
- this.geoListeners = new HashMap<String, GeoListener>();
- }
-
- /**
- * Executes the request and returns PluginResult.
- *
- * @param action The action to execute.
- * @param args JSONArry of arguments for the plugin.
- * @param callbackId The callback id used when calling back into JavaScript.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult.Status status = PluginResult.Status.OK;
- String result = "";
-
- try {
- if (action.equals("getCurrentLocation")) {
- this.getCurrentLocation(args.getBoolean(0), args.getInt(1), args.getInt(2));
- }
- else if (action.equals("start")) {
- String s = this.start(args.getString(0), args.getBoolean(1), args.getInt(2), args.getInt(3));
- return new PluginResult(status, s);
- }
- else if (action.equals("stop")) {
- this.stop(args.getString(0));
- }
- return new PluginResult(status, result);
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
- }
- }
-
- /**
- * Identifies if action to be executed returns a value and should be run synchronously.
- *
- * @param action The action to execute
- * @return T=returns value
- */
- public boolean isSynch(String action) {
- // Starting listeners is easier to run on main thread, so don't run async.
- return true;
- }
-
- /**
- * Called when the activity is to be shut down.
- * Stop listener.
- */
- public void onDestroy() {
- java.util.Set<Entry<String,GeoListener>> s = this.geoListeners.entrySet();
- java.util.Iterator<Entry<String,GeoListener>> it = s.iterator();
- while (it.hasNext()) {
- Entry<String,GeoListener> entry = it.next();
- GeoListener listener = entry.getValue();
- listener.destroy();
- }
- this.geoListeners.clear();
- if (this.global != null) {
- this.global.destroy();
- }
- this.global = null;
- }
-
- //--------------------------------------------------------------------------
- // LOCAL METHODS
- //--------------------------------------------------------------------------
-
- /**
- * Get current location.
- * The result is returned to JavaScript via a callback.
- *
- * @param enableHighAccuracy
- * @param timeout
- * @param maximumAge
- */
- public void getCurrentLocation(boolean enableHighAccuracy, int timeout, int maximumAge) {
-
- // Create a geolocation listener just for getCurrentLocation and call it "global"
- if (this.global == null) {
- this.global = new GeoListener(this, "global", maximumAge);
- }
- else {
- this.global.start(maximumAge);
- }
- }
-
- /**
- * Start geolocation listener and add to listener list.
- *
- * @param key The listener id
- * @param enableHighAccuracy
- * @param timeout
- * @param maximumAge
- * @return
- */
- public String start(String key, boolean enableHighAccuracy, int timeout, int maximumAge) {
-
- // Make sure this listener doesn't already exist
- GeoListener listener = geoListeners.get(key);
- if (listener == null) {
- listener = new GeoListener(this, key, maximumAge);
- geoListeners.put(key, listener);
- }
-
- // Start it
- listener.start(maximumAge);
- return key;
- }
-
- /**
- * Stop geolocation listener and remove from listener list.
- *
- * @param key The listener id
- */
- public void stop(String key) {
- GeoListener listener = geoListeners.remove(key);
- if (listener != null) {
- listener.stop();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/GeoListener.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/GeoListener.java b/framework/src/com/phonegap/GeoListener.java
deleted file mode 100755
index 4d0c64f..0000000
--- a/framework/src/com/phonegap/GeoListener.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import android.content.Context;
-import android.location.Location;
-import android.location.LocationManager;
-import android.webkit.WebView;
-
-public class GeoListener {
- public static int PERMISSION_DENIED = 1;
- public static int POSITION_UNAVAILABLE = 2;
- public static int TIMEOUT = 3;
-
- String id; // Listener ID
- String successCallback; //
- String failCallback;
- GpsListener mGps; // GPS listener
- NetworkListener mNetwork; // Network listener
- LocationManager mLocMan; // Location manager
-
- private GeoBroker broker; // GeoBroker object
-
- int interval;
-
- /**
- * Constructor.
- *
- * @param id Listener id
- * @param ctx
- * @param time Sampling period in msec
- * @param appView
- */
- GeoListener(GeoBroker broker, String id, int time) {
- this.id = id;
- this.interval = time;
- this.broker = broker;
- this.mGps = null;
- this.mNetwork = null;
- this.mLocMan = (LocationManager) broker.ctx.getSystemService(Context.LOCATION_SERVICE);
-
- // If GPS provider, then create and start GPS listener
- if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
- this.mGps = new GpsListener(broker.ctx, time, this);
- }
-
- // If network provider, then create and start network listener
- if (this.mLocMan.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
- this.mNetwork = new NetworkListener(broker.ctx, time, this);
- }
- }
-
- /**
- * Destroy listener.
- */
- public void destroy() {
- this.stop();
- }
-
- /**
- * Location found. Send location back to JavaScript.
- *
- * @param loc
- */
- void success(Location loc) {
-
- String params = loc.getLatitude() + "," + loc.getLongitude() + ", " + loc.getAltitude() +
- "," + loc.getAccuracy() + "," + loc.getBearing() +
- "," + loc.getSpeed() + "," + loc.getTime();
-
- if (id == "global") {
- this.stop();
- }
- this.broker.sendJavascript("navigator._geo.success('" + id + "'," + params + ");");
- }
-
- /**
- * Location failed. Send error back to JavaScript.
- *
- * @param code The error code
- * @param msg The error message
- */
- void fail(int code, String msg) {
- this.broker.sendJavascript("navigator._geo.fail('" + this.id + "', '" + code + "', '" + msg + "');");
- this.stop();
- }
-
- /**
- * Start retrieving location.
- *
- * @param interval
- */
- void start(int interval) {
- if (this.mGps != null) {
- this.mGps.start(interval);
- }
- if (this.mNetwork != null) {
- this.mNetwork.start(interval);
- }
- if (this.mNetwork == null && this.mGps == null) {
- this.fail(POSITION_UNAVAILABLE, "No location providers available.");
- }
- }
-
- /**
- * Stop listening for location.
- */
- void stop() {
- if (this.mGps != null) {
- this.mGps.stop();
- }
- if (this.mNetwork != null) {
- this.mNetwork.stop();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/GpsListener.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/GpsListener.java b/framework/src/com/phonegap/GpsListener.java
deleted file mode 100755
index 5d82540..0000000
--- a/framework/src/com/phonegap/GpsListener.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-package com.phonegap;
-
-import com.phonegap.api.PhonegapActivity;
-
-import android.content.Context;
-import android.location.Location;
-import android.location.LocationManager;
-import android.location.LocationListener;
-import android.os.Bundle;
-
-/**
- * This class handles requests for GPS location services.
- *
- */
-public class GpsListener implements LocationListener {
-
- private PhonegapActivity mCtx; // PhonegapActivity object
-
- private LocationManager mLocMan; // Location manager object
- private GeoListener owner; // Geolistener object (parent)
- private boolean hasData = false; // Flag indicates if location data is available in cLoc
- private Location cLoc; // Last recieved location
- private boolean running = false; // Flag indicates if listener is running
-
- /**
- * Constructor.
- * Automatically starts listening.
- *
- * @param ctx
- * @param interval
- * @param m
- */
- public GpsListener(PhonegapActivity ctx, int interval, GeoListener m) {
- this.owner = m;
- this.mCtx = ctx;
- this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
- this.running = false;
- this.start(interval);
- }
-
- /**
- * Get last location.
- *
- * @return Location object
- */
- public Location getLocation() {
- this.cLoc = this.mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
- if (this.cLoc != null) {
- this.hasData = true;
- }
- return this.cLoc;
- }
-
- /**
- * Called when the provider is disabled by the user.
- *
- * @param provider
- */
- public void onProviderDisabled(String provider) {
- this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS provider disabled.");
- }
-
- /**
- * Called when the provider is enabled by the user.
- *
- * @param provider
- */
- public void onProviderEnabled(String provider) {
- System.out.println("GpsListener: The provider "+ provider + " is enabled");
- }
-
- /**
- * Called when the provider status changes. This method is called when a
- * provider is unable to fetch a location or if the provider has recently
- * become available after a period of unavailability.
- *
- * @param provider
- * @param status
- * @param extras
- */
- public void onStatusChanged(String provider, int status, Bundle extras) {
- System.out.println("GpsListener: The status of the provider " + provider + " has changed");
- if (status == 0) {
- System.out.println("GpsListener: " + provider + " is OUT OF SERVICE");
- this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS out of service.");
- }
- else if (status == 1) {
- System.out.println("GpsListener: " + provider + " is TEMPORARILY_UNAVAILABLE");
- }
- else {
- System.out.println("GpsListener: " + provider + " is Available");
- }
- }
-
- /**
- * Called when the location has changed.
- *
- * @param location
- */
- public void onLocationChanged(Location location) {
- System.out.println("GpsListener: The location has been updated!");
- this.hasData = true;
- this.cLoc = location;
- this.owner.success(location);
- }
-
- /**
- * Determine if location data is available.
- *
- * @return
- */
- public boolean hasLocation() {
- return this.hasData;
- }
-
- /**
- * Start requesting location updates.
- *
- * @param interval
- */
- public void start(int interval) {
- if (!this.running) {
- this.running = true;
- this.mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, 0, this);
- this.getLocation();
-
- // If GPS provider has data, then send now
- if (this.hasData) {
- this.owner.success(this.cLoc);
- }
- }
- }
-
- /**
- * Stop receiving location updates.
- */
- public void stop() {
- if (this.running) {
- this.mLocMan.removeUpdates(this);
- }
- this.running = false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-android/blob/664a061d/framework/src/com/phonegap/HttpHandler.java
----------------------------------------------------------------------
diff --git a/framework/src/com/phonegap/HttpHandler.java b/framework/src/com/phonegap/HttpHandler.java
deleted file mode 100755
index 3893d2a..0000000
--- a/framework/src/com/phonegap/HttpHandler.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package com.phonegap;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.DefaultHttpClient;
-
-public class HttpHandler {
-
- protected Boolean get(String url, String file)
- {
- HttpEntity entity = getHttpEntity(url);
- try {
- writeToDisk(entity, file);
- } catch (Exception e) { e.printStackTrace(); return false; }
- try {
- entity.consumeContent();
- } catch (Exception e) { e.printStackTrace(); return false; }
- return true;
- }
-
- private HttpEntity getHttpEntity(String url)
- /**
- * get the http entity at a given url
- */
- {
- HttpEntity entity=null;
- try {
- DefaultHttpClient httpclient = new DefaultHttpClient();
- HttpGet httpget = new HttpGet(url);
- HttpResponse response = httpclient.execute(httpget);
- entity = response.getEntity();
- } catch (Exception e) { e.printStackTrace(); return null; }
- return entity;
- }
-
- private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException
- /**
- * writes a HTTP entity to the specified filename and location on disk
- */
- {
- int i=0;
- String FilePath="/sdcard/" + file;
- InputStream in = entity.getContent();
- byte buff[] = new byte[1024];
- FileOutputStream out=
- new FileOutputStream(FilePath);
- do {
- int numread = in.read(buff);
- if (numread <= 0)
- break;
- out.write(buff, 0, numread);
- i++;
- } while (true);
- out.flush();
- out.close();
- }
-}