Statistics
| Branch: | Revision:

root / src / com / rackspacecloud / android / ContainerObjectDetails.java @ 51938302

History | View | Annotate | Download (16.1 kB)

1
package com.rackspacecloud.android;
2

    
3
import java.io.BufferedOutputStream;
4
import java.io.File;
5
import java.io.FileNotFoundException;
6
import java.io.FileOutputStream;
7
import java.io.IOException;
8
import java.io.StringReader;
9
import java.text.ParseException;
10
import java.text.SimpleDateFormat;
11
import java.util.Date;
12

    
13
import javax.xml.parsers.FactoryConfigurationError;
14
import javax.xml.parsers.ParserConfigurationException;
15
import javax.xml.parsers.SAXParser;
16
import javax.xml.parsers.SAXParserFactory;
17

    
18
import org.apache.http.HttpEntity;
19
import org.apache.http.HttpResponse;
20
import org.apache.http.client.ClientProtocolException;
21
import org.apache.http.impl.client.BasicResponseHandler;
22
import org.apache.http.util.EntityUtils;
23
import org.xml.sax.InputSource;
24
import org.xml.sax.SAXException;
25
import org.xml.sax.XMLReader;
26

    
27
import android.app.Activity;
28
import android.app.AlertDialog;
29
import android.app.Dialog;
30
import android.app.ProgressDialog;
31
import android.content.Context;
32
import android.content.DialogInterface;
33
import android.content.Intent;
34
import android.net.Uri;
35
import android.os.AsyncTask;
36
import android.os.Bundle;
37
import android.os.Environment;
38
import android.util.Log;
39
import android.view.Menu;
40
import android.view.MenuInflater;
41
import android.view.MenuItem;
42
import android.view.View;
43
import android.widget.Button;
44
import android.widget.TextView;
45

    
46
import com.rackspace.cloud.files.api.client.ContainerObjectManager;
47
import com.rackspace.cloud.files.api.client.ContainerObjects;
48
import com.rackspace.cloud.servers.api.client.CloudServersException;
49
import com.rackspace.cloud.servers.api.client.parsers.CloudServersFaultXMLParser;
50

    
51

    
52
/** 
53
 * 
54
 * @author Phillip Toohill
55
 *
56
 */
57

    
58
public class ContainerObjectDetails extends Activity {
59
        
60
        private static final int deleteObject = 0;
61
        private final String DOWNLOAD_DIRECTORY = "/RackspaceCloud";
62
        private ContainerObjects objects;
63
        private String containerNames;
64
        private String cdnURL;
65
        private String cdnEnabled;
66
        public String LOG = "ViewObject";
67
        private int bConver = 1048576;
68
        private int kbConver = 1024;
69
        private double megaBytes;
70
        private double kiloBytes;
71
        public Button previewButton;
72
        public Button downloadButton;
73
        public Context context;
74
        private ProgressDialog dialog;
75
        private Boolean isDownloaded;
76
        
77
    /** Called when the activity is first created. */
78
    @Override
79
    public void onCreate(Bundle savedInstanceState) {
80
        super.onCreate(savedInstanceState);
81
        
82
        context = getApplicationContext();
83
        
84
        objects = (ContainerObjects) this.getIntent().getExtras().get("container");
85
        containerNames =  (String) this.getIntent().getExtras().get("containerNames");
86
        cdnURL = (String) this.getIntent().getExtras().get("cdnUrl");
87
        cdnEnabled = (String) this.getIntent().getExtras().get("isCdnEnabled");
88
        
89

    
90
        setContentView(R.layout.viewobject);       
91
        restoreState(savedInstanceState);
92
        
93
    }
94
    
95
        @Override
96
        protected void onSaveInstanceState(Bundle outState) {
97
                super.onSaveInstanceState(outState);
98
                outState.putSerializable("container", objects);
99
                outState.putBoolean("isDownloaded", isDownloaded);
100
        }
101

    
102
    private void restoreState(Bundle state) {
103
            if (state != null && state.containsKey("container")) {
104
                    objects = (ContainerObjects) state.getSerializable("container");
105
            }
106
            loadObjectData();
107

    
108
            if ( cdnEnabled.equals("true"))  {
109
                    this.previewButton = (Button) findViewById(R.id.preview_button);
110
                    previewButton.setOnClickListener(new MyOnClickListener());
111
            } else {
112
                    this.previewButton = (Button) findViewById(R.id.preview_button);
113
                    previewButton.setVisibility(View.GONE);
114
            }
115

    
116
            if (state != null && state.containsKey("isDownloaded")){
117
                    isDownloaded = state.getBoolean("isDownloaded");
118
            }
119
            else{
120
                    isDownloaded = fileIsDownloaded();
121
            }
122
            this.downloadButton = (Button) findViewById(R.id.download_button);
123
            if ( isDownloaded )  {
124
                    downloadButton.setText("Open File");
125
            } else {
126
                    downloadButton.setText("Download File");
127
            }           
128
            downloadButton.setOnClickListener(new MyOnClickListener());
129
    }
130

    
131

    
132
    private void loadObjectData() {
133
            //Object Name
134
            TextView name = (TextView) findViewById(R.id.view_container_name);
135
            name.setText(objects.getCName().toString());
136
            
137
            //File size
138
            if (objects.getBytes() >= bConver) {
139
                        megaBytes = Math.abs(objects.getBytes()/bConver + 0.2);
140
                                TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
141
                                sublabel.setText(megaBytes + " MB");
142
                } else if (objects.getBytes() >= kbConver){
143
                        kiloBytes = Math.abs(objects.getBytes()/kbConver + 0.2);
144
                                TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
145
                                sublabel.setText(kiloBytes + " KB");
146
                } else {
147
                                TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
148
                                sublabel.setText(objects.getBytes() + " B");
149
                }        
150
            
151
            //Content Type
152
            TextView cType = (TextView) findViewById(R.id.view_content_type);
153
            cType.setText(objects.getContentType().toString());
154
        
155
            //Last Modification date
156
        String strDate = objects.getLastMod();
157
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.ssssss");
158
        Date dateStr = null;
159
                        try {
160
                                dateStr = formatter.parse(strDate);
161
                        } catch (ParseException e1) {
162
                                e1.printStackTrace();
163
                        }
164
        String formattedDate = formatter.format(dateStr);
165
        Date date1 = null;
166
                        try {
167
                                date1 = formatter.parse(formattedDate);
168
                        } catch (ParseException e) {
169
                                e.printStackTrace();
170
                        }      
171
        formatter = new SimpleDateFormat("MMM-dd-yyyy");
172
        formattedDate = formatter.format(date1);
173
            TextView lastmod = (TextView) findViewById(R.id.view_file_modification);
174
            lastmod.setText(formattedDate);              
175
                        
176
    }
177
    
178
    private class MyOnClickListener implements View.OnClickListener {
179
        //@Override********************************************************************remove comment
180
        public void onClick(View v) {
181
                if(v.equals(findViewById(R.id.preview_button))){
182
                        Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(cdnURL + "/" + objects.getCName()));
183
                        startActivity(viewIntent);  
184
                }
185
                /*
186
                 * need to perform different functions based on if
187
                 * the file has in the devices filesystem
188
                 */
189
                if(v.equals(findViewById(R.id.download_button))){
190
                        if(!isDownloaded){
191
                                if(storageIsReady()){
192
                                        new ContainerObjectDownloadTask().execute();
193
                                }
194
                        }
195
                        else{
196
                                openFile();
197
                        }
198
                }
199
        }
200
    }
201
    
202
    private void showAlert(String title, String message) {
203
                AlertDialog alert = new AlertDialog.Builder(this).create();
204
                alert.setTitle(title);
205
                alert.setMessage(message);
206
                alert.setButton("OK", new DialogInterface.OnClickListener() {
207
              public void onClick(DialogInterface dialog, int which) {
208
                return;
209
            } }); 
210
                alert.show();
211
    }
212
  //Create the Menu options
213
    @Override 
214
    public boolean onCreateOptionsMenu(Menu menu) {
215
                super.onCreateOptionsMenu(menu);
216
                MenuInflater inflater = getMenuInflater();
217
                inflater.inflate(R.menu.container_object_list_menu, menu);
218
                return true;
219
        } 
220
    
221
    @Override 
222
    public boolean onOptionsItemSelected(MenuItem item) {
223
                switch (item.getItemId()) {
224
                case R.id.delete_object:
225
                        showDialog(deleteObject); 
226
                        return true;
227
                case R.id.refresh:
228
                        loadObjectData();
229
                return true;
230
                }
231
                return false;
232
        } 
233
    
234
    @Override
235
    protected Dialog onCreateDialog(int id ) {
236
            switch (id) {
237
                        case deleteObject:
238
            return new AlertDialog.Builder(ContainerObjectDetails.this)
239
                .setIcon(R.drawable.alert_dialog_icon)
240
                .setTitle("Delete File")
241
                .setMessage("Are you sure you want to delete this file?")
242
                .setPositiveButton("Delete File", new DialogInterface.OnClickListener() {
243
                        public void onClick(DialogInterface dialog, int whichButton) {
244
                                // User clicked OK so do some stuff
245
                                new ContainerObjectDeleteTask().execute((Void[]) null);
246
                        }
247
                })
248
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
249
                        public void onClick(DialogInterface dialog, int whichButton) {
250
                                // User clicked Cancel so do some stuff
251
                        }
252
                })
253
                .create();
254
        }
255
        return null;
256
    }
257
    /**
258
         * @return the file
259
         */
260
        public ContainerObjects getViewFile() {
261
                return objects;
262
        }
263

    
264
        /**
265
         * @param File the file to set
266
         */
267
        public void setViewFile(ContainerObjects object) {
268
                this.objects = object;
269
        }
270
        
271
        /*
272
         * returns false if external storage is not avaliable
273
         * (if its mounted, missing, read-only, etc)
274
         * from: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
275
         */
276
        private boolean storageIsReady(){
277
                boolean mExternalStorageAvailable = false;
278
                boolean mExternalStorageWriteable = false;
279
                String state = Environment.getExternalStorageState();
280

    
281
                if (Environment.MEDIA_MOUNTED.equals(state)) {
282
                    // We can read and write the media
283
                    mExternalStorageAvailable = mExternalStorageWriteable = true;
284
                } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
285
                    // We can only read the media
286
                    mExternalStorageAvailable = true;
287
                    mExternalStorageWriteable = false;
288
                } else {
289
                    // Something else is wrong. It may be one of many other states, but all we need
290
                    //  to know is we can neither read nor write
291
                    mExternalStorageAvailable = mExternalStorageWriteable = false;
292
                }
293
                return mExternalStorageAvailable && mExternalStorageWriteable;
294
        }
295
        
296
        private boolean fileIsDownloaded(){
297
                if(storageIsReady()){
298
                        String fileName = Environment.getExternalStorageDirectory().getPath() + "/RackspaceCloud/" + objects.getCName();
299
                        File f = new File(fileName);
300
                        return f.isFile();
301
                }
302
                return false;
303
        }
304
        
305
        private void openFile(){
306
                File object = new File(Environment.getExternalStorageDirectory().getPath() + "/RackspaceCloud/" + objects.getCName());
307
                Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
308
            File file = new File(object.getAbsolutePath()); 
309
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
310
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
311
            myIntent.setDataAndType(Uri.fromFile(file),mimetype);
312
            startActivity(myIntent);
313
        }
314
        
315
        private boolean writeFile(byte[] data){
316
                String directoryName = Environment.getExternalStorageDirectory().getPath() + DOWNLOAD_DIRECTORY;
317
                File f = new File(directoryName);
318
                
319
                if(!f.isDirectory()){
320
                        if(!f.mkdir()){
321
                                return false;
322
                        }
323
                }
324
                
325
                String filename = directoryName + "/" + objects.getCName();
326
                File object = new File(filename);
327
                BufferedOutputStream bos = null;
328
                
329
                try{
330
                        FileOutputStream fos = new FileOutputStream(object);
331
                        bos = new BufferedOutputStream(fos);
332
                        bos.write(data);
333
                }
334
                catch(FileNotFoundException e){
335
                        e.printStackTrace();
336
                }
337
                catch(IOException e){
338
                        e.printStackTrace();
339
                }
340
                finally{
341
                        if(bos != null){
342
                                try {
343
                                        bos.flush();
344
                                        bos.close();
345
                                } catch (IOException e) {
346
                                        // TODO Auto-generated catch block
347
                                        e.printStackTrace();
348
                                }
349
                        }
350
                }
351
                return true;
352
        }
353
        
354
        //Task's
355
                    
356
                     private CloudServersException parseCloudServersException(HttpResponse response) {
357
                                    CloudServersException cse = new CloudServersException();
358
                                    try {
359
                                        BasicResponseHandler responseHandler = new BasicResponseHandler();
360
                                        String body = responseHandler.handleResponse(response);
361
                                        CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
362
                                        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
363
                                        XMLReader xmlReader = saxParser.getXMLReader();
364
                                        xmlReader.setContentHandler(parser);
365
                                        xmlReader.parse(new InputSource(new StringReader(body)));                            
366
                                        cse = parser.getException();                            
367
                                    } catch (ClientProtocolException e) {
368
                                            cse = new CloudServersException();
369
                                            cse.setMessage(e.getLocalizedMessage());
370
                                    } catch (IOException e) {
371
                                            cse = new CloudServersException();
372
                                            cse.setMessage(e.getLocalizedMessage());
373
                                    } catch (ParserConfigurationException e) {
374
                                            cse = new CloudServersException();
375
                                            cse.setMessage(e.getLocalizedMessage());
376
                                    } catch (SAXException e) {
377
                                            cse = new CloudServersException();
378
                                            cse.setMessage(e.getLocalizedMessage());
379
                                    } catch (FactoryConfigurationError e) {
380
                                            cse = new CloudServersException();
381
                                            cse.setMessage(e.getLocalizedMessage());
382
                                    }
383
                                    return cse;
384
                        }
385
                     
386
                     private class ContainerObjectDeleteTask extends AsyncTask<Void, Void, HttpResponse> {
387
                                
388
                                    private CloudServersException exception;
389
                                    
390
                                    protected void onPreExecute(){
391
                                            dialog = ProgressDialog.show(ContainerObjectDetails.this, "", "Deleting...", true);
392
                                    }
393

    
394
                                    @Override
395
                                    protected HttpResponse doInBackground(Void... arg0) {
396
                                            HttpResponse resp = null;        
397
                                            try {
398
                                                    resp = (new ContainerObjectManager(context)).deleteObject(containerNames, objects.getCName() );
399
                                                    Log.v(LOG, "container name " + objects.getCName() + " " + containerNames);
400
                                            } catch (CloudServersException e) {
401
                                                    exception = e;
402
                                            }
403
                                            return resp;
404
                                    }
405
                                
406
                                    @Override
407
                                    protected void onPostExecute(HttpResponse response) {
408
                                            dialog.dismiss();
409
                                            if (response != null) {
410
                                                    int statusCode = response.getStatusLine().getStatusCode();
411
                                                    if (statusCode == 204) {
412
                                                            setResult(Activity.RESULT_OK);
413
                                                            finish();
414
                                                            
415
                                                    } else {
416
                                                            CloudServersException cse = parseCloudServersException(response);
417
                                                            if ("".equals(cse.getMessage())) {
418
                                                                    showAlert("Error", "There was a problem deleting your File.");
419
                                                            } else {
420
                                                                    showAlert("Error", "There was a problem deleting your file: " + cse.getMessage());
421
                                                            }
422
                                                    }
423
                                            } else if (exception != null) {
424
                                                    showAlert("Error", "There was a problem deleting your file: " + exception.getMessage());                                
425
                                            }                        
426
                                    }
427
                        }
428
                     
429
                     private class ContainerObjectDownloadTask extends AsyncTask<Void, Void, HttpResponse> {
430
                                
431
                                    private CloudServersException exception;
432
                                    
433
                                    protected void onPreExecute(){
434
                                            dialog = ProgressDialog.show(ContainerObjectDetails.this, "", "Downloading...", true);
435
                                    }
436

    
437
                                    @Override
438
                                    protected HttpResponse doInBackground(Void... arg0) {
439
                                            HttpResponse resp = null;        
440
                                            try {
441
                                                    resp = (new ContainerObjectManager(context)).getObject(containerNames, objects.getCName());
442
                                            } catch (CloudServersException e) {
443
                                                    exception = e;
444
                                            }
445
                                            return resp;
446
                                    }
447
                                
448
                                    @Override
449
                                    protected void onPostExecute(HttpResponse response) {
450
                                            dialog.dismiss();
451
                                            if (response != null) {
452
                                                    int statusCode = response.getStatusLine().getStatusCode();
453
                                                    if (statusCode == 200) {
454
                                                            setResult(Activity.RESULT_OK);
455
                                                        HttpEntity entity = response.getEntity();
456
                                                                
457
                                                                try {
458
                                                                        if(writeFile(EntityUtils.toByteArray(entity))){
459
                                                                                downloadButton.setText("Open File");
460
                                                                                isDownloaded = true;
461
                                                                        }
462
                                                                        else{
463
                                                                                showAlert("Error", "There was a problem downloading your file.");
464
                                                                        }
465
                                                                        
466
                                                                } catch (IOException e) {
467
                                                                        // TODO Auto-generated catch block
468
                                                                        e.printStackTrace();
469
                                                                }
470
                                                                
471
                                                    } else {
472
                                                            CloudServersException cse = parseCloudServersException(response);
473
                                                            if ("".equals(cse.getMessage())) {
474
                                                                    showAlert("Error", "There was a problem downloading your File.");
475
                                                            } else {
476
                                                                    showAlert("Error", "There was a problem downloading your file: " + cse.getMessage());
477
                                                            }
478
                                                    }
479
                                            } else if (exception != null) {
480
                                                    showAlert("Error", "There was a problem downloading your file: " + exception.getMessage());                                
481
                                            }                        
482
                                    }
483
                        }
484
        
485
  }