Statistics
| Branch: | Revision:

root / src / com / rackspace / cloud / android / ContainerObjectDetails.java @ 05a718db

History | View | Annotate | Download (27.3 kB)

1
package com.rackspace.cloud.android;
2

    
3
import java.io.BufferedOutputStream;
4
import java.io.File;
5
import java.io.FileOutputStream;
6
import java.io.IOException;
7
import java.io.InputStream;
8
import java.io.OutputStream;
9
import java.util.ArrayList;
10
import java.util.HashMap;
11
import java.util.Iterator;
12
import java.util.List;
13
import java.util.Map;
14
import java.util.Map.Entry;
15
import java.util.StringTokenizer;
16

    
17
import org.apache.http.HttpEntity;
18
import org.apache.http.HttpResponse;
19

    
20
import android.app.Activity;
21
import android.app.AlertDialog;
22
import android.app.Dialog;
23
import android.content.DialogInterface;
24
import android.content.Intent;
25
import android.graphics.Color;
26
import android.net.Uri;
27
import android.os.AsyncTask;
28
import android.os.Bundle;
29
import android.os.Environment;
30
import android.util.Log;
31
import android.view.LayoutInflater;
32
import android.view.Menu;
33
import android.view.MenuInflater;
34
import android.view.MenuItem;
35
import android.view.View;
36
import android.view.View.OnClickListener;
37
import android.widget.Button;
38
import android.widget.CheckBox;
39
import android.widget.CompoundButton;
40
import android.widget.CompoundButton.OnCheckedChangeListener;
41
import android.widget.EditText;
42
import android.widget.LinearLayout;
43
import android.widget.TabHost;
44
import android.widget.TextView;
45
import android.widget.Toast;
46

    
47
import com.rackspace.cloud.files.api.client.ContainerManager;
48
import com.rackspace.cloud.files.api.client.ContainerObjectManager;
49
import com.rackspace.cloud.files.api.client.ContainerObjects;
50
import com.rackspace.cloud.files.api.client.GroupResource;
51
import com.rackspace.cloud.files.api.client.ObjectVersion;
52
import com.rackspace.cloud.files.api.client.Permission;
53
import com.rackspace.cloud.servers.api.client.CloudServersException;
54
import com.rackspace.cloud.servers.api.client.http.HttpBundle;
55

    
56
/**
57
 * 
58
 * @author Phillip Toohill
59
 * 
60
 */
61

    
62
public class ContainerObjectDetails extends CloudActivity {
63
        private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
64
        private static final int deleteObject = 0;
65
        private final String DOWNLOAD_DIRECTORY = "PithosPlus";
66

    
67
        private ContainerObjects objects;
68
        private String containerNames;
69
        private String cdnURL;
70
        private String cdnEnabled;
71
        public String LOG = "ViewObject";
72
        private int bConver = 1048576;
73
        private int kbConver = 1024;
74
        private double megaBytes;
75
        private double kiloBytes;
76
        public Button previewButton;
77
        public Button downloadButton;
78
        private Boolean isDownloaded;
79
        private AndroidCloudApplication app;
80
        private DeleteObjectListenerTask deleteObjTask;
81
        private DownloadObjectListenerTask downloadObjTask;
82
        private List<ObjectVersion> versions = new ArrayList<ObjectVersion>();
83

    
84
        /** Called when the activity is first created. */
85
        @Override
86
        public void onCreate(Bundle savedInstanceState) {
87
                super.onCreate(savedInstanceState);
88
                trackPageView(GoogleAnalytics.PAGE_STORAGE_OBJECT);
89

    
90
                objects = (ContainerObjects) this.getIntent().getExtras()
91
                                .get("container");
92
                containerNames = (String) this.getIntent().getExtras()
93
                                .get("containerNames");
94
                cdnURL = (String) this.getIntent().getExtras().get("cdnUrl");
95
                cdnEnabled = (String) this.getIntent().getExtras().get("isCdnEnabled");
96

    
97
                setContentView(R.layout.viewobject);
98
                TabHost tabs = (TabHost) findViewById(R.id.tabhost2);
99

    
100
                tabs.setup();
101

    
102
                TabHost.TabSpec spec = tabs.newTabSpec("tag1");
103

    
104
                spec.setContent(R.id.details);
105
                spec.setIndicator("Details");
106
                tabs.addTab(spec);
107

    
108
                spec = tabs.newTabSpec("tag2");
109
                spec.setContent(R.id.metadata);
110
                spec.setIndicator("Metadata");
111
                tabs.addTab(spec);
112

    
113
                spec = tabs.newTabSpec("tag3");
114
                spec.setContent(R.id.sharing);
115
                spec.setIndicator("Sharing");
116
                tabs.addTab(spec);
117

    
118
                spec = tabs.newTabSpec("tag4");
119
                spec.setContent(R.id.versions);
120
                spec.setIndicator("Versions");
121
                tabs.addTab(spec);
122

    
123
                restoreState(savedInstanceState);
124
        }
125

    
126
        @Override
127
        protected void onSaveInstanceState(Bundle outState) {
128
                super.onSaveInstanceState(outState);
129
                outState.putSerializable("container", objects);
130
                outState.putBoolean("isDownloaded", isDownloaded);
131
        }
132

    
133
        protected void restoreState(Bundle state) {
134
                super.restoreState(state);
135
                /*
136
                 * need reference to the app so you can access curDirFiles as well as
137
                 * processing status
138
                 */
139
                app = (AndroidCloudApplication) this.getApplication();
140

    
141
                if (state != null && state.containsKey("container")) {
142
                        objects = (ContainerObjects) state.getSerializable("container");
143
                }
144
                loadObjectData();
145

    
146
                if (cdnEnabled.equals("true")) {
147
                        this.previewButton = (Button) findViewById(R.id.preview_button);
148
                        previewButton.setOnClickListener(new MyOnClickListener());
149
                } else {
150
                        this.previewButton = (Button) findViewById(R.id.preview_button);
151
                        previewButton.setVisibility(View.GONE);
152
                }
153

    
154
                if (state != null && state.containsKey("isDownloaded")) {
155
                        isDownloaded = state.getBoolean("isDownloaded");
156
                } else {
157
                        isDownloaded = fileIsDownloaded();
158
                }
159
                this.downloadButton = (Button) findViewById(R.id.download_button);
160
                if (isDownloaded) {
161
                        downloadButton.setText("Open File");
162
                } else {
163
                        downloadButton.setText("Download File");
164
                }
165
                downloadButton.setOnClickListener(new MyOnClickListener());
166

    
167
                if (app.isDeletingObject()) {
168
                        deleteObjTask = new DeleteObjectListenerTask();
169
                        deleteObjTask.execute();
170
                }
171

    
172
                if (app.isDownloadingObject()) {
173
                        downloadObjTask = new DownloadObjectListenerTask();
174
                        downloadObjTask.execute();
175
                }
176

    
177
        }
178

    
179
        @Override
180
        protected void onStop() {
181
                super.onStop();
182

    
183
                /*
184
                 * Need to stop running listener task if we exit
185
                 */
186
                if (deleteObjTask != null) {
187
                        deleteObjTask.cancel(true);
188
                }
189

    
190
                if (downloadObjTask != null) {
191
                        downloadObjTask.cancel(true);
192
                }
193
        }
194

    
195
        private void loadObjectData() {
196
                // Object Name
197
                TextView name = (TextView) findViewById(R.id.view_container_name);
198
                name.setText(objects.getCName().toString());
199

    
200
                // File size
201
                if (objects.getBytes() >= bConver) {
202
                        megaBytes = Math.abs(objects.getBytes() / bConver + 0.2);
203
                        TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
204
                        sublabel.setText(megaBytes + " MB");
205
                } else if (objects.getBytes() >= kbConver) {
206
                        kiloBytes = Math.abs(objects.getBytes() / kbConver + 0.2);
207
                        TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
208
                        sublabel.setText(kiloBytes + " KB");
209
                } else {
210
                        TextView sublabel = (TextView) findViewById(R.id.view_file_bytes);
211
                        sublabel.setText(objects.getBytes() + " B");
212
                }
213

    
214
                // Content Type
215
                TextView cType = (TextView) findViewById(R.id.view_content_type);
216
                cType.setText(objects.getContentType().toString());
217

    
218
                // Last Modification date
219
                String strDate = objects.getLastMod();
220
                strDate = strDate.substring(0, strDate.indexOf('T'));
221

    
222
                TextView lastmod = (TextView) findViewById(R.id.view_file_modification);
223
                lastmod.setText(strDate);
224
                rebuildMetadataList();
225
                rebuildPermissionList();
226
                try {
227
                        versions = new ContainerObjectManager(getApplicationContext())
228
                                        .getObjectVersions(objects.getContainerName(),
229
                                                        objects.getCName());
230
                        rebuildVersionList();
231
                } catch (CloudServersException e) {
232
                        // TODO Auto-generated catch block
233
                        e.printStackTrace();
234
                }
235
        }
236
        
237
        private void rebuildMetadataList() {
238
                Button newmetadata = (Button)findViewById(R.id.newMetadata);
239
                newmetadata.setOnClickListener(new OnClickListener() {
240
                        
241
                        @Override
242
                        public void onClick(View arg0) {
243
                                final AlertDialog.Builder alert = new AlertDialog.Builder(ContainerObjectDetails.this);
244
                                alert.setTitle("Add Metadata");
245
                                LinearLayout ll = new LinearLayout(ContainerObjectDetails.this);
246
                                ll.setOrientation(LinearLayout.VERTICAL);
247

    
248
                                final EditText input = new EditText(ContainerObjectDetails.this);
249
                                final EditText input2 = new EditText(ContainerObjectDetails.this);
250
                                ll.addView(input);
251
                                ll.addView(input2);
252
                                alert.setView(ll);
253
                                alert.setPositiveButton("Create", new DialogInterface.OnClickListener() {
254
                                        public void onClick(DialogInterface dialog, int whichButton) {
255
                                                String key = input.getText().toString().trim();
256
                                                String value = input2.getText().toString().trim();
257
                                                addMetatadata(key, value);
258
                                        }
259
                                });
260
                                
261
                                alert.setNegativeButton("Cancel",
262
                                                new DialogInterface.OnClickListener() {
263
                                        public void onClick(DialogInterface dialog, int whichButton) {
264
                                                dialog.cancel();
265
                                        }
266
                                });
267
                                alert.show();
268
                        }
269
                });
270
                LayoutInflater layoutInflater = LayoutInflater
271
                                .from(ContainerObjectDetails.this);
272
                final LinearLayout metadata = (LinearLayout) findViewById(R.id.metadataList);
273
                if (metadata.getChildCount() > 0)
274
                        metadata.removeViews(0, metadata.getChildCount());
275
                metadata.removeAllViews();
276

    
277
                if (objects.getMetadata() != null) {
278
                        int i = 0;
279
                        Iterator<Entry<String, String>> it = objects.getMetadata()
280
                                        .entrySet().iterator();
281
                        while (it.hasNext()) {
282
                                final Entry<String, String> perm = it.next();
283
                                final View v = layoutInflater.inflate(R.layout.metadatarow,
284
                                                null);
285
                                populateMetadataList(perm, v, metadata, i);
286
                                i++;
287
                        }
288
                }
289
        }
290
        
291
        private void addMetatadata(String key, String value){
292
                if(objects.getMetadata()==null)
293
                        objects.setMetadata(new HashMap<String, String>());
294
                objects.getMetadata().put(key, value);
295
                rebuildMetadataList();
296
        }
297

    
298
        private void populateMetadataList(final Entry<String, String> metadata,
299
                        final View v, final LinearLayout properties, int i) {
300
                properties.addView(v, i);
301
                Log.d(LOG, i + " " + metadata.getKey() + " " + metadata.getValue());
302
                ((TextView) v.findViewById(R.id.mkey)).setText(metadata.getKey());
303
                ((TextView) v.findViewById(R.id.mvalue)).setText(metadata.getValue());
304
                ((Button) v.findViewById(R.id.remove))
305
                .setOnClickListener(new OnClickListener() {
306

    
307
                        @Override
308
                        public void onClick(View v1) {
309
                                properties.removeView(v);
310
                                objects.getMetadata().remove(metadata.getKey());
311

    
312
                        }
313
                });
314
        }
315

    
316
        private void rebuildPermissionList() {
317
                Button newmetadata = (Button)findViewById(R.id.newPermission);
318
                newmetadata.setOnClickListener(new OnClickListener() {
319

    
320
                        @Override
321
                        public void onClick(View v) {
322
                                showAddDialog();                                
323
                        }
324
                        
325
                });
326
                LayoutInflater layoutInflater = LayoutInflater
327
                                .from(ContainerObjectDetails.this);
328
                final LinearLayout properties = (LinearLayout) findViewById(R.id.permissionsList);
329
                if (properties.getChildCount() > 0)
330
                        properties.removeViews(0, properties.getChildCount());
331
                properties.removeAllViews();
332
                Iterator<Permission> it = null;
333
                if (objects.getPermissions() != null) {
334
                        it = objects.getPermissions().iterator();
335
                        int i = 0;
336
                        while (it.hasNext()) {
337
                                final Permission perm = it.next();
338
                                final View v = layoutInflater.inflate(R.layout.propertiesrow,
339
                                                null);
340
                                populatePermissionList(perm, v, properties, i);
341
                                i++;
342
                        }
343
                }
344
        }
345

    
346
        private void populatePermissionList(final Permission perm, final View v,
347
                        final LinearLayout properties, int i) {
348

    
349
                properties.addView(v, i);
350

    
351
                ((TextView) v.findViewById(R.id.ownerName)).setText(perm.getUser());
352
                ((CheckBox) v.findViewById(R.id.read)).setChecked(perm.isRead());
353
                ((CheckBox) v.findViewById(R.id.write)).setChecked(perm.isWrite());
354

    
355
                ((CheckBox) v.findViewById(R.id.read))
356
                                .setOnCheckedChangeListener(new OnCheckedChangeListener() {
357

    
358
                                        @Override
359
                                        public void onCheckedChanged(CompoundButton buttonView,
360
                                                        boolean isChecked) {
361
                                                perm.setRead(isChecked);
362

    
363
                                        }
364
                                });
365
                ((CheckBox) v.findViewById(R.id.write))
366
                                .setOnCheckedChangeListener(new OnCheckedChangeListener() {
367

    
368
                                        @Override
369
                                        public void onCheckedChanged(CompoundButton buttonView,
370
                                                        boolean isChecked) {
371
                                                perm.setWrite(isChecked);
372

    
373
                                        }
374
                                });
375
                ((Button) v.findViewById(R.id.remove))
376
                                .setOnClickListener(new OnClickListener() {
377

    
378
                                        @Override
379
                                        public void onClick(View v1) {
380
                                                properties.removeView(v);
381
                                                objects.getPermissions().remove(perm);
382

    
383
                                        }
384
                                });
385
        }
386
        
387
        private void addPermission(boolean group, String userOrGroup){
388
                if(objects.getPermissions()==null)
389
                        objects.setPermissions(new ArrayList<Permission>());
390
                Permission np = new Permission();
391
                if(group)
392
                        np.setGroup(userOrGroup);
393
                else
394
                        np.setUser(userOrGroup);
395
                objects.getPermissions().add(np);
396
                rebuildPermissionList();
397
        }
398
        private void showAddDialog(){
399
                final CharSequence[] items = {"Add User", "Add Group"};
400

    
401
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
402
                builder.setTitle("User Or Group");
403
                builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
404
                    public void onClick(DialogInterface dialog, int item) {
405
                            boolean user;
406
                       if(item ==0){
407
                               user=true;
408
                       }
409
                       else
410
                               user=false;
411
                       populateAddDialog(user);
412
                       dialog.dismiss();
413
                       
414
                    }
415
                });
416
                AlertDialog alert2 = builder.create();
417
                alert2.show();
418
                
419
        }
420
        
421
        private void populateAddDialog(final boolean user){
422
                final AlertDialog.Builder alert = new AlertDialog.Builder(ContainerObjectDetails.this);
423
               if(user){
424
                       alert.setTitle("Add User");
425
                       final EditText input = new EditText(ContainerObjectDetails.this);
426
                input.setTextColor(Color.BLACK);
427
                    
428
                    alert.setView(input);
429
                    
430
                    alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
431
                            public void onClick(DialogInterface dialog, int whichButton) {
432
                                    String value = input.getText().toString().trim();
433
                                    addPermission(false, value);
434
                                    
435
                            }
436
                    });
437

    
438
                    alert.setNegativeButton("Cancel",
439
                                    new DialogInterface.OnClickListener() {
440
                                            public void onClick(DialogInterface dialog, int whichButton) {
441
                                                    dialog.cancel();
442
                                            
443
                                            }
444
                                    });
445
                    alert.show();
446
               }
447
               else{
448
                       AlertDialog.Builder builder = new AlertDialog.Builder(this);
449
                    builder.setTitle("Add Group");
450
                    builder.setSingleChoiceItems(getGroupNames().toArray(new String[0]), -1, new DialogInterface.OnClickListener() {
451
                        public void onClick(DialogInterface dialog, int item) {
452
                                addPermission(true, getGroupNames().get(item));
453
                           dialog.dismiss();
454
                           
455
                        }
456
                    });
457
                    AlertDialog alert2 = builder.create();
458
                    alert2.show();
459
               }
460
            
461
        }
462
        
463
        public List<String> getGroupNames(){
464
                List<String> result = new ArrayList<String>();
465
                List<GroupResource> groups = ((AndroidCloudApplication)getApplication()).getGroups();
466
                for(GroupResource g : groups){
467
                        result.add(g.getName());
468
                }
469
                return result;
470
        }
471
        
472
        private void rebuildVersionList() {
473
                LayoutInflater layoutInflater = LayoutInflater
474
                                .from(ContainerObjectDetails.this);
475
                final LinearLayout properties = (LinearLayout) findViewById(R.id.versionsList);
476
                if (properties.getChildCount() > 0)
477
                        properties.removeViews(0, properties.getChildCount());
478
                properties.removeAllViews();
479
                Iterator<ObjectVersion> it;
480
                // Collections.reverse(versions);
481
                it = versions.iterator();
482
                int i = 0;
483
                while (it.hasNext()) {
484
                        final ObjectVersion perm = it.next();
485
                        final View v = layoutInflater.inflate(R.layout.versionsrow, null);
486
                        populateVersionList(perm, v, properties, i);
487
                        i++;
488
                }
489
        }
490

    
491
        private void populateVersionList(final ObjectVersion perm, final View v,
492
                        final LinearLayout properties, int i) {
493

    
494
                properties.addView(v, i);
495

    
496
                ((TextView) v.findViewById(R.id.versionName)).setText("Version: "
497
                                + perm.getVersion());
498

    
499
                ((TextView) v.findViewById(R.id.versionModified)).setText("Modified: "
500
                                + perm.getDateString());
501
                if (versions.size() == 1) {
502
                        // ((Button)
503
                        // v.findViewById(R.id.vremove)).setVisibility(View.INVISIBLE);
504
                        ((Button) v.findViewById(R.id.vrestore))
505
                                        .setVisibility(View.INVISIBLE);
506
                }
507
                /*
508
                 * ((Button) v.findViewById(R.id.vremove)) .setOnClickListener(new
509
                 * OnClickListener() {
510
                 * 
511
                 * @Override public void onClick(View v1) { Log.d("PERMS",
512
                 * perm.getUri()); try { new GssHttpCommands(getDroidApplication()
513
                 * .getUserDetails
514
                 * ()).deleteFolder(perm.getUri()+"?version="+perm.getVersion()); }
515
                 * catch (SystemErrorException e) { // TODO Auto-generated catch block
516
                 * e.printStackTrace(); } catch (GssHttpException e) { // TODO
517
                 * Auto-generated catch block e.printStackTrace(); }
518
                 * getFileTask().execute(res.getUri()); //properties.removeView(v);
519
                 * 
520
                 * } });
521
                 */
522
                ((Button) v.findViewById(R.id.vrestore))
523
                                .setOnClickListener(new OnClickListener() {
524

    
525
                                        @Override
526
                                        public void onClick(View v1) {
527
                                                // Log.d("PERMS", perm.getUri());
528
                                                // geRestoreVersionTask().execute(perm.getUri()+"?restoreVersion="+perm.getVersion());
529

    
530
                                        }
531
                                });
532
                ((Button) v.findViewById(R.id.vdownload))
533
                                .setOnClickListener(new OnClickListener() {
534

    
535
                                        @Override
536
                                        public void onClick(View v1) {
537

    
538
                                                // getDownloadTask().execute(perm.getUri()+"?version="+perm.getVersion());
539
                                                // properties.removeView(v);
540

    
541
                                        }
542
                                });
543
        }
544

    
545
        private class MyOnClickListener implements View.OnClickListener {
546
                @Override
547
                public void onClick(View v) {
548
                        if (v.equals(findViewById(R.id.preview_button))) {
549
                                Intent viewIntent = new Intent("android.intent.action.VIEW",
550
                                                Uri.parse(cdnURL + "/" + objects.getCName()));
551
                                startActivity(viewIntent);
552
                        }
553
                        /*
554
                         * need to perform different functions based on if the file is in
555
                         * the devices filesystem
556
                         */
557
                        if (v.equals(findViewById(R.id.download_button))) {
558
                                if (!isDownloaded) {
559
                                        if (storageIsReady()) {
560
                                                new ContainerObjectDownloadTask().execute();
561
                                        } else {
562
                                                showAlert("Error", "Storage not found.");
563
                                        }
564
                                } else {
565
                                        openFile();
566
                                }
567
                        }
568
                }
569
        }
570

    
571
        // Create the Menu options
572
        @Override
573
        public boolean onCreateOptionsMenu(Menu menu) {
574
                super.onCreateOptionsMenu(menu);
575
                MenuInflater inflater = getMenuInflater();
576
                inflater.inflate(R.menu.container_object_list_menu, menu);
577
                return true;
578
        }
579

    
580
        @Override
581
        public boolean onOptionsItemSelected(MenuItem item) {
582
                switch (item.getItemId()) {
583
                case R.id.delete_object:
584
                        showDialog(deleteObject);
585
                        return true;
586
                case R.id.refresh:
587
                        loadObjectData();
588
                        return true;
589
                case R.id.save:
590
                        saveObject();
591
                        return true;
592
                }
593
                return false;
594
        }
595

    
596
        @Override
597
        protected Dialog onCreateDialog(int id) {
598
                switch (id) {
599
                case deleteObject:
600
                        return new AlertDialog.Builder(ContainerObjectDetails.this)
601
                                        .setIcon(R.drawable.alert_dialog_icon)
602
                                        .setTitle("Delete File")
603
                                        .setMessage("Are you sure you want to delete this file?")
604
                                        .setPositiveButton("Delete File",
605
                                                        new DialogInterface.OnClickListener() {
606
                                                                public void onClick(DialogInterface dialog,
607
                                                                                int whichButton) {
608
                                                                        // User clicked OK so do some stuff
609
                                                                        trackEvent(GoogleAnalytics.CATEGORY_FILE,
610
                                                                                        GoogleAnalytics.EVENT_DELETE, "",
611
                                                                                        -1);
612
                                                                        new ContainerObjectDeleteTask()
613
                                                                                        .execute((Void[]) null);
614
                                                                }
615
                                                        })
616
                                        .setNegativeButton("Cancel",
617
                                                        new DialogInterface.OnClickListener() {
618
                                                                public void onClick(DialogInterface dialog,
619
                                                                                int whichButton) {
620
                                                                        // User clicked Cancel so do some stuff
621
                                                                }
622
                                                        }).create();
623
                }
624
                return null;
625
        }
626

    
627
        /**
628
         * @return the file
629
         */
630
        public ContainerObjects getViewFile() {
631
                return objects;
632
        }
633

    
634
        /**
635
         * @param File
636
         *            the file to set
637
         */
638
        public void setViewFile(ContainerObjects object) {
639
                this.objects = object;
640
        }
641

    
642
        /*
643
         * returns false if external storage is not avaliable (if its mounted,
644
         * missing, read-only, etc) from:
645
         * http://developer.android.com/guide/topics/data
646
         * /data-storage.html#filesExternal
647
         */
648
        private boolean storageIsReady() {
649
                boolean mExternalStorageAvailable = false;
650
                boolean mExternalStorageWriteable = false;
651
                String state = Environment.getExternalStorageState();
652

    
653
                if (Environment.MEDIA_MOUNTED.equals(state)) {
654
                        // We can read and write the media
655
                        mExternalStorageAvailable = mExternalStorageWriteable = true;
656
                } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
657
                        // We can only read the media
658
                        mExternalStorageAvailable = true;
659
                        mExternalStorageWriteable = false;
660
                } else {
661
                        // Something else is wrong. It may be one of many other states, but
662
                        // all we need
663
                        // to know is we can neither read nor write
664
                        mExternalStorageAvailable = mExternalStorageWriteable = false;
665
                }
666
                return mExternalStorageAvailable && mExternalStorageWriteable;
667
        }
668

    
669
        private boolean fileIsDownloaded() {
670
                if (storageIsReady()) {
671
                        String fileName = Environment.getExternalStorageDirectory()
672
                                        .getPath() + "/PithosPlus/" + objects.getCName();
673
                        File f = new File(fileName);
674
                        return f.isFile();
675
                }
676
                return false;
677
        }
678

    
679
        private void openFile() {
680
                File object = new File(Environment.getExternalStorageDirectory()
681
                                .getPath() + "/PithosPlus/" + objects.getCName());
682
                Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
683
                File file = new File(object.getAbsolutePath());
684
                String extension = android.webkit.MimeTypeMap
685
                                .getFileExtensionFromUrl(Uri.fromFile(file).toString());
686
                String mimetype = android.webkit.MimeTypeMap.getSingleton()
687
                                .getMimeTypeFromExtension(extension);
688
                myIntent.setDataAndType(Uri.fromFile(file), mimetype);
689
                // myIntent.setData(Uri.fromFile(file));
690
                try {
691
                        startActivity(myIntent);
692
                } catch (Exception e) {
693
                        Toast.makeText(this, "Could not open file.", Toast.LENGTH_SHORT)
694
                                        .show();
695
                }
696
        }
697

    
698
        // Task's
699

    
700
        private class ContainerObjectDeleteTask extends
701
                        AsyncTask<Void, Void, HttpBundle> {
702

    
703
                private CloudServersException exception;
704

    
705
                protected void onPreExecute() {
706
                        showDialog();
707
                        app.setDeleteingObject(true);
708
                        deleteObjTask = new DeleteObjectListenerTask();
709
                        deleteObjTask.execute();
710
                }
711

    
712
                @Override
713
                protected HttpBundle doInBackground(Void... arg0) {
714
                        HttpBundle bundle = null;
715
                        try {
716
                                bundle = (new ContainerObjectManager(getContext()))
717
                                                .deleteObject(containerNames, objects.getCName());
718
                        } catch (CloudServersException e) {
719
                                exception = e;
720
                        }
721

    
722
                        return bundle;
723
                }
724

    
725
                @Override
726
                protected void onPostExecute(HttpBundle bundle) {
727
                        app.setDeleteingObject(false);
728
                        hideDialog();
729
                        HttpResponse response = bundle.getResponse();
730
                        if (response != null) {
731
                                int statusCode = response.getStatusLine().getStatusCode();
732
                                if (statusCode == 204) {
733
                                        // handled by listener
734
                                } else {
735
                                        CloudServersException cse = parseCloudServersException(response);
736
                                        if ("".equals(cse.getMessage())) {
737
                                                showError("There was a problem deleting your File.",
738
                                                                bundle);
739
                                        } else {
740
                                                showError("There was a problem deleting your file: "
741
                                                                + cse.getMessage(), bundle);
742
                                        }
743
                                }
744
                        } else if (exception != null) {
745
                                showError("There was a problem deleting your file: "
746
                                                + exception.getMessage(), bundle);
747
                        }
748
                }
749
        }
750

    
751
        private class ContainerObjectDownloadTask extends
752
                        AsyncTask<Void, Void, HttpBundle> {
753

    
754
                private CloudServersException exception;
755

    
756
                @Override
757
                protected void onPreExecute() {
758
                        showDialog();
759
                        app.setDownloadingObject(true);
760
                        downloadObjTask = new DownloadObjectListenerTask();
761
                        downloadObjTask.execute();
762
                }
763

    
764
                @Override
765
                protected HttpBundle doInBackground(Void... arg0) {
766
                        HttpBundle bundle = null;
767
                        try {
768
                                bundle = (new ContainerObjectManager(getContext())).getObject(
769
                                                containerNames, objects.getCName());
770
                        } catch (CloudServersException e) {
771
                                exception = e;
772
                        }
773
                        return bundle;
774
                }
775

    
776
                @Override
777
                protected void onPostExecute(HttpBundle bundle) {
778
                        
779
                        
780
                        HttpResponse response = bundle.getResponse();
781
                        if (response != null) {
782
                                int statusCode = response.getStatusLine().getStatusCode();
783
                                if (statusCode == 200) {
784
                                        setResult(Activity.RESULT_OK);
785
                                        HttpEntity entity = response.getEntity();
786
                                        app.setDownloadedEntity(entity);
787
                                } else {
788
                                        CloudServersException cse = parseCloudServersException(response);
789
                                        if ("".equals(cse.getMessage())) {
790
                                                showError("There was a problem downloading your File.",
791
                                                                bundle);
792
                                        } else {
793
                                                showError("There was a problem downloading your file: "
794
                                                                + cse.getMessage(), bundle);
795
                                        }
796
                                }
797
                        } else if (exception != null) {
798
                                showError("There was a problem downloading your file: "
799
                                                + exception.getMessage(), bundle);
800
                        }
801
                        app.setDownloadingObject(false);
802
                }
803
        }
804

    
805
        private class DeleteObjectListenerTask extends AsyncTask<Void, Void, Void> {
806

    
807
                @Override
808
                protected Void doInBackground(Void... arg1) {
809

    
810
                        while (app.isDeletingObject()) {
811
                                // wait for process to finish
812
                                // or have it be canceled
813
                                if (deleteObjTask.isCancelled()) {
814
                                        return null;
815
                                }
816
                        }
817
                        return null;
818
                }
819

    
820
                /*
821
                 * when no longer processing, time to load the new files
822
                 */
823
                @Override
824
                protected void onPostExecute(Void arg1) {
825
                        hideDialog();
826
                        setResult(99);
827
                        finish();
828
                }
829
        }
830

    
831
        private class DownloadObjectListenerTask extends
832
                        AsyncTask<Void, Void, Void> {
833

    
834
                @Override
835
                protected Void doInBackground(Void... arg1) {
836

    
837
                        while (app.isDownloadingObject()) {
838
                                // wait for process to finish
839
                                // or have it be canceled
840
                                if (downloadObjTask.isCancelled()) {
841
                                        return null;
842
                                }
843
                        }
844
                        return null;
845
                }
846

    
847
                /*
848
                 * when no longer processing, time to load the new files
849
                 */
850
                @Override
851
                protected void onPostExecute(Void arg1) {
852
                        
853
                        try {
854
                                //TODO: run in background
855
                                if (writeFile(app.getDownloadedEntity().getContent())) {
856
                                        downloadButton.setText("Open File");
857
                                        isDownloaded = true;
858
                                } else {
859
                                        showAlert("Error",
860
                                                        "There was a problem downloading your file.");
861
                                }
862

    
863
                        } catch (IOException e) {
864
                                showAlert("Error", "There was a problem downloading your file.");
865
                                e.printStackTrace();
866
                        } catch (Exception e) {
867
                                showAlert("Error", "There was a problem downloading your file.");
868
                                e.printStackTrace();
869
                        }
870
                        hideDialog();
871
                }
872
        }
873

    
874
        private boolean writeFile(InputStream in) {
875
                String directoryName = Environment.getExternalStorageDirectory()
876
                                .getPath();
877
                File f = new File(directoryName, DOWNLOAD_DIRECTORY);
878
                Log.i(LOG,directoryName);
879
                if (!f.isDirectory()) {
880
                        if (!f.mkdir()) {
881
                                return false;
882
                        }
883
                }
884
                Log.i(LOG,objects.toString());
885
                //String filename = directoryName + "/" + objects.getName();
886
                StringTokenizer str = new StringTokenizer(objects.getCName(),"/");
887
                String path="";
888
                String fname="";
889
                int count = str.countTokens();
890
                Log.i(LOG,"object is: "+objects.getCName()+" "+count);
891
                for(int i=0;i<count;i++){
892
                        if(i<(count-1)){
893
                                path = path+str.nextToken()+"/";
894
                        }
895
                        else
896
                                fname=str.nextToken();
897
                }
898
                Log.i(LOG,"Path is:"+path);
899
                Log.i(LOG,"Fname is:"+fname);
900
                File object;
901
                if("".equals(path)){
902
                        object = new File(f,fname);
903
                }
904
                else{
905
                        File t = new File(f,path);
906
                        t.mkdirs();
907
                        object = new File(t,fname);
908
                }
909
                
910
                
911
                BufferedOutputStream bos = null;
912

    
913
                try {
914
                        FileOutputStream fos = new FileOutputStream(object);
915
                        copy(in, fos);
916
                } catch (IOException e) {
917
                        e.printStackTrace();
918
                } finally {
919
                        if (bos != null) {
920
                                try {
921
                                        bos.flush();
922
                                        bos.close();
923
                                } catch (IOException e) {
924
                                        // TODO Auto-generated catch block
925
                                        e.printStackTrace();
926
                                }
927
                        }
928
                }
929
                return true;
930
        }
931

    
932
        public static long copy(InputStream input, OutputStream output) throws IOException {
933
                
934
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
935
                long count = 0;
936
                int n = 0;
937
                try{
938
                        while (-1 != (n = input.read(buffer))) {
939
                                output.write(buffer, 0, n);
940
                                count += n;
941
                                //monitor.setCurrent(count);
942
                        }
943
                }
944
                finally{
945
                        input.close();
946
                        output.close();
947
                }
948
                return count;
949
        }
950
        
951
        @Override
952
        public void onBackPressed() {
953
                
954
                //TODO: perform update
955
                super.onBackPressed();
956
        }
957
        
958
        public void saveObject(){
959
                Map<String,String> headers = new HashMap<String,String>();
960
                for(Entry<String,String> entry : objects.getMetadata().entrySet()){
961
                        headers.put("X-Object-Meta-"+entry.getKey(), entry.getValue());
962
                }
963
                try {
964
                        HttpBundle b = new ContainerObjectManager(getApplicationContext()).updateObject(objects.getContainerName(), objects.getCName(), "", null, headers);
965
                        Log.i(LOG,"response:"+b.getResponse().getStatusLine().getStatusCode());
966
                } catch (CloudServersException e) {
967
                        // TODO Auto-generated catch block
968
                        e.printStackTrace();
969
                }
970
        }
971
        
972

    
973
}