Back to project page Android-SDK.
The source code is released under:
MIT License
If you think the Android project Android-SDK listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package net.getcloudengine; /*w ww.j a v a 2 s . co m*/ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.AsyncTask; import android.util.Log; /** * Class to represent a file on the disk. Allows uploading and * downloading of a file to CloudEngine server. * */ public class CloudFile { private String name = null, path = null; private long size = 0; private String file_url = null; private final String TAG ="CloudFile"; private File diskFile = null; private byte[] data = null; private final String validName = "^[\\w]+\\.?[\\w]*$";; CloudEngineUtils utils = CloudEngineUtils.getInstance(); public CloudFile(String name){ isValidName(name); this.name = name; } /** * Validate the given file name. * Allowed - aplhanumeric _ . * */ private void isValidName(String name){ if(!name.matches(validName)) { throw new CloudException("Invalid name. Name should only contain alphanumeric characters, underscore(_) or period (.)"); } } /** * Constructs a new CloudFile object * * @param name name of the file * * @param file the file object constructed from a file on * the disk * * @throws CloudException in case the given name is invalid * or the file object is null * */ public CloudFile(String name, File file){ if(name == null || name == "" || file == null){ throw new CloudException("Invalid input parameters"); } this.size = file.length(); this.name = name; this.diskFile = file; } /** * Constructs a new CloudFile object * * @param name name of the file * * @param data byte array of data which will be the contents * of the file * * @throws CloudException in case the given name is invalid * or the file object is null * */ public CloudFile(String name, byte[] data){ if(name == null || name == "" || data == null){ throw new CloudException("Invalid input parameters"); } this.size = data.length; this.name = name; this.data = data; } /** * Get the server URL from where the file can be downloaded * * @return url URL from where the file can be downloaded * */ public String getUrl(){ return file_url; } /** * Returns the name of the file as provided to the constructor * This is only the name of the file and not its full path. * */ public String getName(){ return name; } /** * Returns the contents of the file in the form of byte array * */ public byte[] getData(){ return this.data; } private void saveFile() throws CloudAuthException, CloudException{ String response =null; JSONObject obj = null; String url = null; String address = CloudEndPoints.FILES + name + "/"; HttpPost post = new HttpPost(); Log.i(TAG, "Trying to save file " + name); FileInputStream stream; try { stream = new FileInputStream(diskFile); } catch (FileNotFoundException e1) { Log.e(TAG, "File is missing"); throw new CloudException("File is missing at the location"); } response = utils.httpRequest(address, post, stream); Log.i(TAG, "File save complete. Response: " + response); try { obj = new JSONObject(response); url = obj.getString("url"); this.file_url = url; } catch (JSONException e) { throw new CloudException("Invalid response received after file upload"); } } private byte[] fetchFile() throws CloudException { String response = null, fileURL = null; byte[] data; String address = CloudEndPoints.FILES + name + "/"; JSONObject obj = null; HttpClient httpclient = new DefaultHttpClient(); response = utils.httpRequest(address, new HttpGet()); Log.d(TAG, "Response from file get: " + response); //convert response to byte[] try { obj = new JSONObject(response); fileURL = obj.getString("url"); Log.d(TAG, "file url received: " + fileURL); } catch (JSONException e) { throw new CloudException("Invalid response received after file upload"); } //todo: validate fileURL is valid and not empty/null try{ HttpGet request = new HttpGet(); int status = 0; StatusLine statusLine = null; HttpResponse fileData = null; URL url = new URL(fileURL); request.setURI(url.toURI()); fileData = httpclient.execute(request); statusLine = fileData.getStatusLine(); status = statusLine.getStatusCode(); Log.d(TAG, "HTTP response status code: " + status); Log.d(TAG, "HTTP reason: " + statusLine.getReasonPhrase()); if(status != 200){ throw new CloudException("Error while retrieving the file"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); fileData.getEntity().writeTo(out); out.close(); data = out.toByteArray(); this.data = data; return data; } catch(Exception e){ Log.e(TAG, "Unable to connect to server. " + e.getMessage()); throw new CloudException("Unable to connect to server"); } } private class FetchResult{ byte[] data; CloudException exception; } private class FetchTask extends AsyncTask<Void, Void, FetchResult>{ FetchFileCallback callback = null; public void setCallback(FetchFileCallback cbk){ callback = cbk; } @Override protected FetchResult doInBackground(Void... args){ FetchResult result = new FetchResult(); result.data = null; result.exception = null; try{ byte[] data = fetchFile(); result.data = data; } catch (CloudException e){ result.exception = e; } return result; } protected void onPostExecute(FetchResult result) { if(callback != null){ callback.done(result.data, result.exception); } } } /** * * Fetch the file contents from the server in the current thread. * * @return File contents in the form of byte array. * * @throws CloudException if the file name hasn't been set or * the network is unavailable * */ public byte[] fetch(){ if(name == null || name == ""){ throw new CloudException("Filename not set"); } Context ctx = CloudEngine.getContext(); if(utils.isNetworkAvailable(ctx)) { return fetchFile(); } else{ throw new CloudException("Network unavailable"); } } /** * * Fetches the file contents from the server in a background thread. * * @throws CloudException if the file name hasn't been set or * the network is unavailable * */ public void fetchInBackground(){ if(name == null || name == ""){ throw new CloudException("Filename not set"); } Context ctx = CloudEngine.getContext(); FetchTask fetchtask = new FetchTask(); if(utils.isNetworkAvailable(ctx)) { Log.d(TAG, "Starting background file fetch task"); fetchtask.execute(); } else{ throw new CloudException("Network unavailable"); } } /** * * Fetches the file contents from the server in a background thread. * * @param callback The callback function which will be called upon * completion of the request in the background thread. The function will * be passed the file contents data along with any exception information * that may have occured during the operation. * * @throws CloudException if the file name hasn't been set or * the network is unavailable * */ public void fetchInBackground(FetchFileCallback callback){ if(name == null || name == ""){ throw new CloudException("Filename not set"); } if(callback == null){ throw new CloudException("Invalid parameters"); } Context ctx = CloudEngine.getContext(); FetchTask fetchtask = new FetchTask(); fetchtask.setCallback(callback); if(utils.isNetworkAvailable(ctx)) { Log.d(TAG, "Starting background file fetch task"); fetchtask.execute(); } else{ throw new CloudException("Network unavailable"); } } private class SaveTask extends AsyncTask<Void, Void, CloudException> { SaveFileCallback callback = null; public void setCallback(SaveFileCallback cbk){ callback = cbk; } @Override protected CloudException doInBackground(Void... args) { try{ saveFile(); } catch (CloudAuthException e){ return e; } catch (CloudException e){ return e; } return null; } protected void onPostExecute(CloudException e) { if(callback != null){ callback.done(e); } } } /** * Saves this file on the server in the current thread. * This method throws an exception is there is no network * available. * * @throws CloudException * */ public void save() throws CloudException{ if(name == null || name == ""){ throw new CloudException("Filename not set"); } Context ctx = CloudEngine.getContext(); if(utils.isNetworkAvailable(ctx)){ saveFile(); } else{ throw new CloudException("Unable to save object. No network available."); } } /** * Saves this file on the server in a background thread. * If there is no network available, this method will save * the object eventually when network becomes again available. * * @throws CloudException * */ public void saveInBackground(){ if(name == null || name == ""){ throw new CloudException("Filename not set"); } Context ctx = CloudEngine.getContext(); SaveTask savetask = new SaveTask(); if(utils.isNetworkAvailable(ctx)) { savetask.execute(); } else{ throw new CloudException("Unable to save file. No network available"); } } /** * Saves this file on the server in a background thread. * If there is no network available, this method will save * the object eventually when network becomes again available. * Upon completion of save operation the provided callback * function is called along with any Exception information that * may have occured during the save operation. * * @throws CloudException * */ public void saveInBackground(SaveFileCallback callback){ if(name == null || name == ""){ throw new CloudException("Filename not set"); } Context ctx = CloudEngine.getContext(); SaveTask savetask = new SaveTask(); savetask.setCallback(callback); if(utils.isNetworkAvailable(ctx)) { savetask.execute(); } else{ throw new CloudException("Unable to save file. No network available"); } } }