Revision 9c4430bd

b/src/com/rackspace/cloud/android/ContainerObjectDetails.java
5 5
import java.io.FileNotFoundException;
6 6
import java.io.FileOutputStream;
7 7
import java.io.IOException;
8
import java.io.InputStream;
9
import java.io.OutputStream;
8 10
import java.util.ArrayList;
9 11
import java.util.Iterator;
10 12
import java.util.List;
11 13
import java.util.Map.Entry;
14
import java.util.StringTokenizer;
12 15

  
13 16
import org.apache.http.HttpEntity;
14 17
import org.apache.http.HttpResponse;
......
47 50
import com.rackspace.cloud.servers.api.client.CloudServersException;
48 51
import com.rackspace.cloud.servers.api.client.http.HttpBundle;
49 52

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

  
56 59
public class ContainerObjectDetails extends CloudActivity {
57

  
60
	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
58 61
	private static final int deleteObject = 0;
59
	private final String DOWNLOAD_DIRECTORY = "/PithosPlus";
60
	
62
	private final String DOWNLOAD_DIRECTORY = "PithosPlus";
63

  
61 64
	private ContainerObjects objects;
62 65
	private String containerNames;
63 66
	private String cdnURL;
......
73 76
	private AndroidCloudApplication app;
74 77
	private DeleteObjectListenerTask deleteObjTask;
75 78
	private DownloadObjectListenerTask downloadObjTask;
76
	private List<ObjectVersion> versions=new ArrayList<ObjectVersion>();
77
		
79
	private List<ObjectVersion> versions = new ArrayList<ObjectVersion>();
80

  
78 81
	/** Called when the activity is first created. */
79 82
	@Override
80 83
	public void onCreate(Bundle savedInstanceState) {
81 84
		super.onCreate(savedInstanceState);
82 85
		trackPageView(GoogleAnalytics.PAGE_STORAGE_OBJECT);
83 86

  
84
		objects = (ContainerObjects) this.getIntent().getExtras().get("container");
85
		containerNames =  (String) this.getIntent().getExtras().get("containerNames");
87
		objects = (ContainerObjects) this.getIntent().getExtras()
88
				.get("container");
89
		containerNames = (String) this.getIntent().getExtras()
90
				.get("containerNames");
86 91
		cdnURL = (String) this.getIntent().getExtras().get("cdnUrl");
87 92
		cdnEnabled = (String) this.getIntent().getExtras().get("isCdnEnabled");
88 93

  
89
		setContentView(R.layout.viewobject); 
90
		TabHost tabs = (TabHost)findViewById(R.id.tabhost2);
91

  
92
        tabs.setup();
93

  
94
        TabHost.TabSpec spec = tabs.newTabSpec("tag1");
95

  
96
        spec.setContent(R.id.details);
97
        spec.setIndicator("Details");
98
        tabs.addTab(spec);
99

  
100
        spec = tabs.newTabSpec("tag2");
101
        spec.setContent(R.id.metadata);
102
        spec.setIndicator("Metadata");
103
        tabs.addTab(spec);
104
        
105
        spec = tabs.newTabSpec("tag3");
106
        spec.setContent(R.id.sharing);
107
        spec.setIndicator("Sharing");
108
        tabs.addTab(spec);
109
        
110
        spec = tabs.newTabSpec("tag4");
111
        spec.setContent(R.id.versions);
112
        spec.setIndicator("Versions");
113
        tabs.addTab(spec);
114
        
94
		setContentView(R.layout.viewobject);
95
		TabHost tabs = (TabHost) findViewById(R.id.tabhost2);
96

  
97
		tabs.setup();
98

  
99
		TabHost.TabSpec spec = tabs.newTabSpec("tag1");
100

  
101
		spec.setContent(R.id.details);
102
		spec.setIndicator("Details");
103
		tabs.addTab(spec);
104

  
105
		spec = tabs.newTabSpec("tag2");
106
		spec.setContent(R.id.metadata);
107
		spec.setIndicator("Metadata");
108
		tabs.addTab(spec);
109

  
110
		spec = tabs.newTabSpec("tag3");
111
		spec.setContent(R.id.sharing);
112
		spec.setIndicator("Sharing");
113
		tabs.addTab(spec);
114

  
115
		spec = tabs.newTabSpec("tag4");
116
		spec.setContent(R.id.versions);
117
		spec.setIndicator("Versions");
118
		tabs.addTab(spec);
119

  
115 120
		restoreState(savedInstanceState);
116 121
	}
117 122

  
......
125 130
	protected void restoreState(Bundle state) {
126 131
		super.restoreState(state);
127 132
		/*
128
		 * need reference to the app so you can access curDirFiles
129
		 * as well as processing status
133
		 * need reference to the app so you can access curDirFiles as well as
134
		 * processing status
130 135
		 */
131
		app = (AndroidCloudApplication)this.getApplication();
136
		app = (AndroidCloudApplication) this.getApplication();
132 137

  
133 138
		if (state != null && state.containsKey("container")) {
134 139
			objects = (ContainerObjects) state.getSerializable("container");
135 140
		}
136 141
		loadObjectData();
137 142

  
138
		if ( cdnEnabled.equals("true"))  {
143
		if (cdnEnabled.equals("true")) {
139 144
			this.previewButton = (Button) findViewById(R.id.preview_button);
140 145
			previewButton.setOnClickListener(new MyOnClickListener());
141 146
		} else {
......
143 148
			previewButton.setVisibility(View.GONE);
144 149
		}
145 150

  
146
		if (state != null && state.containsKey("isDownloaded")){
151
		if (state != null && state.containsKey("isDownloaded")) {
147 152
			isDownloaded = state.getBoolean("isDownloaded");
148
		}
149
		else{
153
		} else {
150 154
			isDownloaded = fileIsDownloaded();
151 155
		}
152 156
		this.downloadButton = (Button) findViewById(R.id.download_button);
153
		if ( isDownloaded )  {
157
		if (isDownloaded) {
154 158
			downloadButton.setText("Open File");
155 159
		} else {
156 160
			downloadButton.setText("Download File");
157
		}   	
161
		}
158 162
		downloadButton.setOnClickListener(new MyOnClickListener());
159
		
160
		if(app.isDeletingObject()){
163

  
164
		if (app.isDeletingObject()) {
161 165
			deleteObjTask = new DeleteObjectListenerTask();
162 166
			deleteObjTask.execute();
163 167
		}
164
		
165
		if(app.isDownloadingObject()){
168

  
169
		if (app.isDownloadingObject()) {
166 170
			downloadObjTask = new DownloadObjectListenerTask();
167 171
			downloadObjTask.execute();
168 172
		}
169
		
173

  
170 174
	}
171
	
172
	
173
	
175

  
174 176
	@Override
175
	protected void onStop(){
177
	protected void onStop() {
176 178
		super.onStop();
177 179

  
178 180
		/*
179
		 * Need to stop running listener task
180
		 * if we exit
181
		 * Need to stop running listener task if we exit
181 182
		 */
182
		if(deleteObjTask != null){
183
		if (deleteObjTask != null) {
183 184
			deleteObjTask.cancel(true);
184 185
		}
185
		
186
		if(downloadObjTask != null){
186

  
187
		if (downloadObjTask != null) {
187 188
			downloadObjTask.cancel(true);
188 189
		}
189 190
	}
190 191

  
191

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

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

  
211
		//Content Type
211
		// Content Type
212 212
		TextView cType = (TextView) findViewById(R.id.view_content_type);
213 213
		cType.setText(objects.getContentType().toString());
214 214

  
215
		//Last Modification date
215
		// Last Modification date
216 216
		String strDate = objects.getLastMod();
217 217
		strDate = strDate.substring(0, strDate.indexOf('T'));
218 218

  
219 219
		TextView lastmod = (TextView) findViewById(R.id.view_file_modification);
220
		lastmod.setText(strDate);    	  
220
		lastmod.setText(strDate);
221 221
		rebuildMetadataList();
222 222
		rebuildPermissionList();
223 223
		try {
224
			versions = new ContainerObjectManager(getApplicationContext()).getObjectVersions(objects.getContainerName(), objects.getCName());
224
			versions = new ContainerObjectManager(getApplicationContext())
225
					.getObjectVersions(objects.getContainerName(),
226
							objects.getCName());
225 227
			rebuildVersionList();
226 228
		} catch (CloudServersException e) {
227 229
			// TODO Auto-generated catch block
228 230
			e.printStackTrace();
229 231
		}
230 232
	}
231
	
232
	private void rebuildMetadataList(){
233
		LayoutInflater layoutInflater = LayoutInflater.from(ContainerObjectDetails.this);
233

  
234
	private void rebuildMetadataList() {
235
		LayoutInflater layoutInflater = LayoutInflater
236
				.from(ContainerObjectDetails.this);
234 237
		final LinearLayout metadata = (LinearLayout) findViewById(R.id.metadataList);
235
		if(metadata.getChildCount()>0)
236
			metadata.removeViews(0,metadata.getChildCount());
238
		if (metadata.getChildCount() > 0)
239
			metadata.removeViews(0, metadata.getChildCount());
237 240
		metadata.removeAllViews();
238
		
239
		if(objects.getMetadata()!=null){
240
			int i=0;
241
			Iterator<Entry<String,String>> it = objects.getMetadata().entrySet().iterator();
241

  
242
		if (objects.getMetadata() != null) {
243
			int i = 0;
244
			Iterator<Entry<String, String>> it = objects.getMetadata()
245
					.entrySet().iterator();
242 246
			while (it.hasNext()) {
243
				final Entry<String,String> perm = it.next();
244
				final View v = layoutInflater.inflate(R.layout.metadatarow, null);
247
				final Entry<String, String> perm = it.next();
248
				final View v = layoutInflater.inflate(R.layout.metadatarow,
249
						null);
245 250
				populateMetadataList(perm, v, metadata, i);
246 251
				i++;
247 252
			}
248 253
		}
249 254
	}
250
	
251
	private void populateMetadataList(final Entry<String,String>  metadata, final View v, final LinearLayout properties, int i){
255

  
256
	private void populateMetadataList(final Entry<String, String> metadata,
257
			final View v, final LinearLayout properties, int i) {
252 258
		properties.addView(v, i);
253
		Log.d(LOG,i+" "+metadata.getKey()+" "+metadata.getValue());
259
		Log.d(LOG, i + " " + metadata.getKey() + " " + metadata.getValue());
254 260
		((TextView) v.findViewById(R.id.mkey)).setText(metadata.getKey());
255 261
		((TextView) v.findViewById(R.id.mvalue)).setText(metadata.getValue());
256 262
	}
257 263

  
258
	
259
	private void rebuildPermissionList(){
260
		LayoutInflater layoutInflater = LayoutInflater.from(ContainerObjectDetails.this);
264
	private void rebuildPermissionList() {
265
		LayoutInflater layoutInflater = LayoutInflater
266
				.from(ContainerObjectDetails.this);
261 267
		final LinearLayout properties = (LinearLayout) findViewById(R.id.permissionsList);
262
		if(properties.getChildCount()>0)
263
			properties.removeViews(0,properties.getChildCount());
268
		if (properties.getChildCount() > 0)
269
			properties.removeViews(0, properties.getChildCount());
264 270
		properties.removeAllViews();
265
		Iterator<Permission> it=null;
266
		if(objects.getPermissions()!=null){
267
			it= objects.getPermissions().iterator();
271
		Iterator<Permission> it = null;
272
		if (objects.getPermissions() != null) {
273
			it = objects.getPermissions().iterator();
268 274
			int i = 0;
269 275
			while (it.hasNext()) {
270 276
				final Permission perm = it.next();
271
				final View v = layoutInflater.inflate(R.layout.propertiesrow, null);
277
				final View v = layoutInflater.inflate(R.layout.propertiesrow,
278
						null);
272 279
				populatePermissionList(perm, v, properties, i);
273 280
				i++;
274 281
			}
275 282
		}
276 283
	}
277
	
278
	private void populatePermissionList(final Permission perm, final View v, final LinearLayout properties, int i){
279
		
280
		
284

  
285
	private void populatePermissionList(final Permission perm, final View v,
286
			final LinearLayout properties, int i) {
287

  
281 288
		properties.addView(v, i);
282
		
283
		
284
		
289

  
285 290
		((TextView) v.findViewById(R.id.ownerName)).setText(perm.getUser());
286 291
		((CheckBox) v.findViewById(R.id.read)).setChecked(perm.isRead());
287 292
		((CheckBox) v.findViewById(R.id.write)).setChecked(perm.isWrite());
288
		
289
		((CheckBox) v.findViewById(R.id.read)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
290 293

  
291
			@Override
292
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
293
				perm.setRead(isChecked);
294
		((CheckBox) v.findViewById(R.id.read))
295
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
294 296

  
295
			}
296
		});
297
		((CheckBox) v.findViewById(R.id.write)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
297
					@Override
298
					public void onCheckedChanged(CompoundButton buttonView,
299
							boolean isChecked) {
300
						perm.setRead(isChecked);
298 301

  
299
			@Override
300
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
301
				perm.setWrite(isChecked);
302
					}
303
				});
304
		((CheckBox) v.findViewById(R.id.write))
305
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
302 306

  
303
			}
304
		});
305
		((Button) v.findViewById(R.id.remove)).setOnClickListener(new OnClickListener() {
307
					@Override
308
					public void onCheckedChanged(CompoundButton buttonView,
309
							boolean isChecked) {
310
						perm.setWrite(isChecked);
306 311

  
307
			@Override
308
			public void onClick(View v1) {
309
				properties.removeView(v);
310
				objects.getPermissions().remove(perm);
312
					}
313
				});
314
		((Button) v.findViewById(R.id.remove))
315
				.setOnClickListener(new OnClickListener() {
311 316

  
312
			}
313
		});
317
					@Override
318
					public void onClick(View v1) {
319
						properties.removeView(v);
320
						objects.getPermissions().remove(perm);
321

  
322
					}
323
				});
314 324
	}
315
	
325

  
316 326
	private void rebuildVersionList() {
317
		LayoutInflater layoutInflater = LayoutInflater.from(ContainerObjectDetails.this);
327
		LayoutInflater layoutInflater = LayoutInflater
328
				.from(ContainerObjectDetails.this);
318 329
		final LinearLayout properties = (LinearLayout) findViewById(R.id.versionsList);
319 330
		if (properties.getChildCount() > 0)
320 331
			properties.removeViews(0, properties.getChildCount());
321 332
		properties.removeAllViews();
322 333
		Iterator<ObjectVersion> it;
323
		//Collections.reverse(versions);
334
		// Collections.reverse(versions);
324 335
		it = versions.iterator();
325 336
		int i = 0;
326 337
		while (it.hasNext()) {
......
338 349

  
339 350
		((TextView) v.findViewById(R.id.versionName)).setText("Version: "
340 351
				+ perm.getVersion());
341
		
352

  
342 353
		((TextView) v.findViewById(R.id.versionModified)).setText("Modified: "
343 354
				+ perm.getDateString());
344
		if(versions.size()==1){
345
			//((Button) v.findViewById(R.id.vremove)).setVisibility(View.INVISIBLE);
346
			((Button) v.findViewById(R.id.vrestore)).setVisibility(View.INVISIBLE);
355
		if (versions.size() == 1) {
356
			// ((Button)
357
			// v.findViewById(R.id.vremove)).setVisibility(View.INVISIBLE);
358
			((Button) v.findViewById(R.id.vrestore))
359
					.setVisibility(View.INVISIBLE);
347 360
		}
348 361
		/*
349
		((Button) v.findViewById(R.id.vremove))
362
		 * ((Button) v.findViewById(R.id.vremove)) .setOnClickListener(new
363
		 * OnClickListener() {
364
		 * 
365
		 * @Override public void onClick(View v1) { Log.d("PERMS",
366
		 * perm.getUri()); try { new GssHttpCommands(getDroidApplication()
367
		 * .getUserDetails
368
		 * ()).deleteFolder(perm.getUri()+"?version="+perm.getVersion()); }
369
		 * catch (SystemErrorException e) { // TODO Auto-generated catch block
370
		 * e.printStackTrace(); } catch (GssHttpException e) { // TODO
371
		 * Auto-generated catch block e.printStackTrace(); }
372
		 * getFileTask().execute(res.getUri()); //properties.removeView(v);
373
		 * 
374
		 * } });
375
		 */
376
		((Button) v.findViewById(R.id.vrestore))
350 377
				.setOnClickListener(new OnClickListener() {
351 378

  
352 379
					@Override
353 380
					public void onClick(View v1) {
354
						Log.d("PERMS", perm.getUri());
355
						try {
356
							new GssHttpCommands(getDroidApplication()
357
									.getUserDetails()).deleteFolder(perm.getUri()+"?version="+perm.getVersion());
358
						} catch (SystemErrorException e) {
359
							// TODO Auto-generated catch block
360
							e.printStackTrace();
361
						} catch (GssHttpException e) {
362
							// TODO Auto-generated catch block
363
							e.printStackTrace();
364
						}
365
						getFileTask().execute(res.getUri());
366
						//properties.removeView(v);
381
						// Log.d("PERMS", perm.getUri());
382
						// geRestoreVersionTask().execute(perm.getUri()+"?restoreVersion="+perm.getVersion());
367 383

  
368 384
					}
369
				});*/
370
		((Button) v.findViewById(R.id.vrestore))
371
		.setOnClickListener(new OnClickListener() {
372

  
373
			@Override
374
			public void onClick(View v1) {
375
				//Log.d("PERMS", perm.getUri());
376
					//geRestoreVersionTask().execute(perm.getUri()+"?restoreVersion="+perm.getVersion());
377

  
378
			}
379
		});
385
				});
380 386
		((Button) v.findViewById(R.id.vdownload))
381
		.setOnClickListener(new OnClickListener() {
387
				.setOnClickListener(new OnClickListener() {
382 388

  
383
			@Override
384
			public void onClick(View v1) {
385
				
386
				//getDownloadTask().execute(perm.getUri()+"?version="+perm.getVersion());
387
				//properties.removeView(v);
389
					@Override
390
					public void onClick(View v1) {
388 391

  
389
			}
390
		});
392
						// getDownloadTask().execute(perm.getUri()+"?version="+perm.getVersion());
393
						// properties.removeView(v);
394

  
395
					}
396
				});
391 397
	}
392
	
393
	
398

  
394 399
	private class MyOnClickListener implements View.OnClickListener {
395 400
		@Override
396 401
		public void onClick(View v) {
397
			if(v.equals(findViewById(R.id.preview_button))){
398
				Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(cdnURL + "/" + objects.getCName()));
399
				startActivity(viewIntent);  
402
			if (v.equals(findViewById(R.id.preview_button))) {
403
				Intent viewIntent = new Intent("android.intent.action.VIEW",
404
						Uri.parse(cdnURL + "/" + objects.getCName()));
405
				startActivity(viewIntent);
400 406
			}
401 407
			/*
402
			 * need to perform different functions based on if
403
			 * the file is in the devices filesystem
408
			 * need to perform different functions based on if the file is in
409
			 * the devices filesystem
404 410
			 */
405
			if(v.equals(findViewById(R.id.download_button))){
406
				if(!isDownloaded){
407
					if(storageIsReady()){
411
			if (v.equals(findViewById(R.id.download_button))) {
412
				if (!isDownloaded) {
413
					if (storageIsReady()) {
408 414
						new ContainerObjectDownloadTask().execute();
409
					}
410
					else{
415
					} else {
411 416
						showAlert("Error", "Storage not found.");
412 417
					}
413
				}
414
				else{
418
				} else {
415 419
					openFile();
416 420
				}
417 421
			}
418 422
		}
419 423
	}
420 424

  
421
	//Create the Menu options
422
	@Override 
425
	// Create the Menu options
426
	@Override
423 427
	public boolean onCreateOptionsMenu(Menu menu) {
424 428
		super.onCreateOptionsMenu(menu);
425 429
		MenuInflater inflater = getMenuInflater();
426 430
		inflater.inflate(R.menu.container_object_list_menu, menu);
427 431
		return true;
428
	} 
432
	}
429 433

  
430
	@Override 
434
	@Override
431 435
	public boolean onOptionsItemSelected(MenuItem item) {
432 436
		switch (item.getItemId()) {
433 437
		case R.id.delete_object:
434
			showDialog(deleteObject); 
438
			showDialog(deleteObject);
435 439
			return true;
436 440
		case R.id.refresh:
437 441
			loadObjectData();
438 442
			return true;
439 443
		}
440 444
		return false;
441
	} 
445
	}
442 446

  
443 447
	@Override
444
	protected Dialog onCreateDialog(int id ) {
448
	protected Dialog onCreateDialog(int id) {
445 449
		switch (id) {
446 450
		case deleteObject:
447 451
			return new AlertDialog.Builder(ContainerObjectDetails.this)
448
			.setIcon(R.drawable.alert_dialog_icon)
449
			.setTitle("Delete File")
450
			.setMessage("Are you sure you want to delete this file?")
451
			.setPositiveButton("Delete File", new DialogInterface.OnClickListener() {
452
				public void onClick(DialogInterface dialog, int whichButton) {
453
					// User clicked OK so do some stuff
454
					trackEvent(GoogleAnalytics.CATEGORY_FILE, GoogleAnalytics.EVENT_DELETE, "", -1);
455
					new ContainerObjectDeleteTask().execute((Void[]) null);
456
				}
457
			})
458
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
459
				public void onClick(DialogInterface dialog, int whichButton) {
460
					// User clicked Cancel so do some stuff
461
				}
462
			})
463
			.create();
452
					.setIcon(R.drawable.alert_dialog_icon)
453
					.setTitle("Delete File")
454
					.setMessage("Are you sure you want to delete this file?")
455
					.setPositiveButton("Delete File",
456
							new DialogInterface.OnClickListener() {
457
								public void onClick(DialogInterface dialog,
458
										int whichButton) {
459
									// User clicked OK so do some stuff
460
									trackEvent(GoogleAnalytics.CATEGORY_FILE,
461
											GoogleAnalytics.EVENT_DELETE, "",
462
											-1);
463
									new ContainerObjectDeleteTask()
464
											.execute((Void[]) null);
465
								}
466
							})
467
					.setNegativeButton("Cancel",
468
							new DialogInterface.OnClickListener() {
469
								public void onClick(DialogInterface dialog,
470
										int whichButton) {
471
									// User clicked Cancel so do some stuff
472
								}
473
							}).create();
464 474
		}
465 475
		return null;
466 476
	}
477

  
467 478
	/**
468 479
	 * @return the file
469 480
	 */
......
472 483
	}
473 484

  
474 485
	/**
475
	 * @param File the file to set
486
	 * @param File
487
	 *            the file to set
476 488
	 */
477 489
	public void setViewFile(ContainerObjects object) {
478 490
		this.objects = object;
479 491
	}
480 492

  
481 493
	/*
482
	 * returns false if external storage is not avaliable
483
	 * (if its mounted, missing, read-only, etc)
484
	 * from: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
494
	 * returns false if external storage is not avaliable (if its mounted,
495
	 * missing, read-only, etc) from:
496
	 * http://developer.android.com/guide/topics/data
497
	 * /data-storage.html#filesExternal
485 498
	 */
486
	private boolean storageIsReady(){
499
	private boolean storageIsReady() {
487 500
		boolean mExternalStorageAvailable = false;
488 501
		boolean mExternalStorageWriteable = false;
489 502
		String state = Environment.getExternalStorageState();
......
496 509
			mExternalStorageAvailable = true;
497 510
			mExternalStorageWriteable = false;
498 511
		} else {
499
			// Something else is wrong. It may be one of many other states, but all we need
500
			//  to know is we can neither read nor write
512
			// Something else is wrong. It may be one of many other states, but
513
			// all we need
514
			// to know is we can neither read nor write
501 515
			mExternalStorageAvailable = mExternalStorageWriteable = false;
502 516
		}
503 517
		return mExternalStorageAvailable && mExternalStorageWriteable;
504 518
	}
505 519

  
506
	private boolean fileIsDownloaded(){
507
		if(storageIsReady()){
508
			String fileName = Environment.getExternalStorageDirectory().getPath() + "/PithosPlus/" + objects.getCName();
520
	private boolean fileIsDownloaded() {
521
		if (storageIsReady()) {
522
			String fileName = Environment.getExternalStorageDirectory()
523
					.getPath() + "/PithosPlus/" + objects.getCName();
509 524
			File f = new File(fileName);
510 525
			return f.isFile();
511 526
		}
512 527
		return false;
513 528
	}
514 529

  
515
	private void openFile(){
516
		File object = new File(Environment.getExternalStorageDirectory().getPath() + "/PithosPlus/" + objects.getCName());
530
	private void openFile() {
531
		File object = new File(Environment.getExternalStorageDirectory()
532
				.getPath() + "/PithosPlus/" + objects.getCName());
517 533
		Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
518
		File file = new File(object.getAbsolutePath()); 
519
		String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
520
		String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
521
		myIntent.setDataAndType(Uri.fromFile(file),mimetype);
522
		//myIntent.setData(Uri.fromFile(file));
523
		try{
534
		File file = new File(object.getAbsolutePath());
535
		String extension = android.webkit.MimeTypeMap
536
				.getFileExtensionFromUrl(Uri.fromFile(file).toString());
537
		String mimetype = android.webkit.MimeTypeMap.getSingleton()
538
				.getMimeTypeFromExtension(extension);
539
		myIntent.setDataAndType(Uri.fromFile(file), mimetype);
540
		// myIntent.setData(Uri.fromFile(file));
541
		try {
524 542
			startActivity(myIntent);
543
		} catch (Exception e) {
544
			Toast.makeText(this, "Could not open file.", Toast.LENGTH_SHORT)
545
					.show();
525 546
		}
526
		catch(Exception e){
527
			Toast.makeText(this, "Could not open file.", Toast.LENGTH_SHORT).show();
528
		}
529
	}
530

  
531
	private boolean writeFile(byte[] data){
532
		String directoryName = Environment.getExternalStorageDirectory().getPath() + DOWNLOAD_DIRECTORY;
533
		File f = new File(directoryName);
534

  
535
		if(!f.isDirectory()){
536
			if(!f.mkdir()){
537
				return false;
538
			}
539
		}
540

  
541
		String filename = directoryName + "/" + objects.getCName();
542
		File object = new File(filename);
543
		BufferedOutputStream bos = null;
544

  
545
		try{
546
			FileOutputStream fos = new FileOutputStream(object);
547
			bos = new BufferedOutputStream(fos);
548
			bos.write(data);
549
		}
550
		catch(FileNotFoundException e){
551
			e.printStackTrace();
552
		}
553
		catch(IOException e){
554
			e.printStackTrace();
555
		}
556
		finally{
557
			if(bos != null){
558
				try {
559
					bos.flush();
560
					bos.close();
561
				} catch (IOException e) {
562
					// TODO Auto-generated catch block
563
					e.printStackTrace();
564
				}
565
			}
566
		}
567
		return true;
568 547
	}
569 548

  
570
	//Task's
549
	// Task's
571 550

  
572
	private class ContainerObjectDeleteTask extends AsyncTask<Void, Void, HttpBundle> {
551
	private class ContainerObjectDeleteTask extends
552
			AsyncTask<Void, Void, HttpBundle> {
573 553

  
574 554
		private CloudServersException exception;
575 555

  
576
		protected void onPreExecute(){
556
		protected void onPreExecute() {
577 557
			showDialog();
578 558
			app.setDeleteingObject(true);
579 559
			deleteObjTask = new DeleteObjectListenerTask();
......
582 562

  
583 563
		@Override
584 564
		protected HttpBundle doInBackground(Void... arg0) {
585
			HttpBundle bundle = null;	
565
			HttpBundle bundle = null;
586 566
			try {
587
				bundle = (new ContainerObjectManager(getContext())).deleteObject(containerNames, objects.getCName() );
567
				bundle = (new ContainerObjectManager(getContext()))
568
						.deleteObject(containerNames, objects.getCName());
588 569
			} catch (CloudServersException e) {
589 570
				exception = e;
590 571
			}
591
			
572

  
592 573
			return bundle;
593 574
		}
594 575

  
......
600 581
			if (response != null) {
601 582
				int statusCode = response.getStatusLine().getStatusCode();
602 583
				if (statusCode == 204) {
603
					//handled by listener
584
					// handled by listener
604 585
				} else {
605 586
					CloudServersException cse = parseCloudServersException(response);
606 587
					if ("".equals(cse.getMessage())) {
607
						showError("There was a problem deleting your File.", bundle);
588
						showError("There was a problem deleting your File.",
589
								bundle);
608 590
					} else {
609
						showError("There was a problem deleting your file: " + cse.getMessage(), bundle);
591
						showError("There was a problem deleting your file: "
592
								+ cse.getMessage(), bundle);
610 593
					}
611 594
				}
612 595
			} else if (exception != null) {
613
				showError("There was a problem deleting your file: " + exception.getMessage(), bundle);				
614
			}			
596
				showError("There was a problem deleting your file: "
597
						+ exception.getMessage(), bundle);
598
			}
615 599
		}
616 600
	}
617 601

  
618
	private class ContainerObjectDownloadTask extends AsyncTask<Void, Void, HttpBundle> {
602
	private class ContainerObjectDownloadTask extends
603
			AsyncTask<Void, Void, HttpBundle> {
619 604

  
620 605
		private CloudServersException exception;
621 606

  
622 607
		@Override
623
		protected void onPreExecute(){
608
		protected void onPreExecute() {
624 609
			showDialog();
625 610
			app.setDownloadingObject(true);
626 611
			downloadObjTask = new DownloadObjectListenerTask();
......
629 614

  
630 615
		@Override
631 616
		protected HttpBundle doInBackground(Void... arg0) {
632
			HttpBundle bundle = null;	
617
			HttpBundle bundle = null;
633 618
			try {
634
				bundle = (new ContainerObjectManager(getContext())).getObject(containerNames, objects.getCName());
619
				bundle = (new ContainerObjectManager(getContext())).getObject(
620
						containerNames, objects.getCName());
635 621
			} catch (CloudServersException e) {
636 622
				exception = e;
637 623
			}
......
640 626

  
641 627
		@Override
642 628
		protected void onPostExecute(HttpBundle bundle) {
643
			app.setDownloadingObject(false);
644
			hideDialog();
629
			
630
			
645 631
			HttpResponse response = bundle.getResponse();
646 632
			if (response != null) {
647 633
				int statusCode = response.getStatusLine().getStatusCode();
......
652 638
				} else {
653 639
					CloudServersException cse = parseCloudServersException(response);
654 640
					if ("".equals(cse.getMessage())) {
655
						showError("There was a problem downloading your File.", bundle);
641
						showError("There was a problem downloading your File.",
642
								bundle);
656 643
					} else {
657
						showError("There was a problem downloading your file: " + cse.getMessage(), bundle);
644
						showError("There was a problem downloading your file: "
645
								+ cse.getMessage(), bundle);
658 646
					}
659 647
				}
660 648
			} else if (exception != null) {
661
				showError("There was a problem downloading your file: " + exception.getMessage(), bundle);				
662
			}			
649
				showError("There was a problem downloading your file: "
650
						+ exception.getMessage(), bundle);
651
			}
652
			app.setDownloadingObject(false);
663 653
		}
664 654
	}
665
	
666
	private class DeleteObjectListenerTask extends
667
	AsyncTask<Void, Void, Void> {
668
		
655

  
656
	private class DeleteObjectListenerTask extends AsyncTask<Void, Void, Void> {
657

  
669 658
		@Override
670 659
		protected Void doInBackground(Void... arg1) {
671 660

  
672
			while(app.isDeletingObject()){
661
			while (app.isDeletingObject()) {
673 662
				// wait for process to finish
674 663
				// or have it be canceled
675
				if(deleteObjTask.isCancelled()){
664
				if (deleteObjTask.isCancelled()) {
676 665
					return null;
677 666
				}
678 667
			}
......
680 669
		}
681 670

  
682 671
		/*
683
		 * when no longer processing, time to load
684
		 * the new files
672
		 * when no longer processing, time to load the new files
685 673
		 */
686 674
		@Override
687 675
		protected void onPostExecute(Void arg1) {
......
690 678
			finish();
691 679
		}
692 680
	}
693
	
681

  
694 682
	private class DownloadObjectListenerTask extends
695
	AsyncTask<Void, Void, Void> {
696
		
683
			AsyncTask<Void, Void, Void> {
684

  
697 685
		@Override
698 686
		protected Void doInBackground(Void... arg1) {
699 687

  
700
			while(app.isDownloadingObject()){
688
			while (app.isDownloadingObject()) {
701 689
				// wait for process to finish
702 690
				// or have it be canceled
703
				if(downloadObjTask.isCancelled()){
691
				if (downloadObjTask.isCancelled()) {
704 692
					return null;
705 693
				}
706 694
			}
......
708 696
		}
709 697

  
710 698
		/*
711
		 * when no longer processing, time to load
712
		 * the new files
699
		 * when no longer processing, time to load the new files
713 700
		 */
714 701
		@Override
715 702
		protected void onPostExecute(Void arg1) {
716
			hideDialog();
703
			
717 704
			try {
718
				if(writeFile(EntityUtils.toByteArray(app.getDownloadedEntity()))){
705
				//TODO: run in background
706
				if (writeFile(app.getDownloadedEntity().getContent())) {
719 707
					downloadButton.setText("Open File");
720 708
					isDownloaded = true;
721
				}
722
				else{
723
					showAlert("Error", "There was a problem downloading your file.");
709
				} else {
710
					showAlert("Error",
711
							"There was a problem downloading your file.");
724 712
				}
725 713

  
726 714
			} catch (IOException e) {
......
730 718
				showAlert("Error", "There was a problem downloading your file.");
731 719
				e.printStackTrace();
732 720
			}
721
			hideDialog();
733 722
		}
734 723
	}
735 724

  
725
	private boolean writeFile(InputStream in) {
726
		String directoryName = Environment.getExternalStorageDirectory()
727
				.getPath();
728
		File f = new File(directoryName, DOWNLOAD_DIRECTORY);
729
		Log.i(LOG,directoryName);
730
		if (!f.isDirectory()) {
731
			if (!f.mkdir()) {
732
				return false;
733
			}
734
		}
735
		Log.i(LOG,objects.toString());
736
		//String filename = directoryName + "/" + objects.getName();
737
		StringTokenizer str = new StringTokenizer(objects.getCName(),"/");
738
		String path="";
739
		String fname="";
740
		int count = str.countTokens();
741
		Log.i(LOG,"object is: "+objects.getCName()+" "+count);
742
		for(int i=0;i<count;i++){
743
			if(i<(count-1)){
744
				path = path+str.nextToken()+"/";
745
			}
746
			else
747
				fname=str.nextToken();
748
		}
749
		Log.i(LOG,"Path is:"+path);
750
		Log.i(LOG,"Fname is:"+fname);
751
		File object;
752
		if("".equals(path)){
753
			object = new File(f,fname);
754
		}
755
		else{
756
			File t = new File(f,path);
757
			t.mkdirs();
758
			object = new File(t,fname);
759
		}
760
		
761
		
762
		BufferedOutputStream bos = null;
763

  
764
		try {
765
			FileOutputStream fos = new FileOutputStream(object);
766
			copy(in, fos);
767
		} catch (IOException e) {
768
			e.printStackTrace();
769
		} finally {
770
			if (bos != null) {
771
				try {
772
					bos.flush();
773
					bos.close();
774
				} catch (IOException e) {
775
					// TODO Auto-generated catch block
776
					e.printStackTrace();
777
				}
778
			}
779
		}
780
		return true;
781
	}
782

  
783
	public static long copy(InputStream input, OutputStream output) throws IOException {
784
		
785
		byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
786
		long count = 0;
787
		int n = 0;
788
		try{
789
			while (-1 != (n = input.read(buffer))) {
790
				output.write(buffer, 0, n);
791
				count += n;
792
				//monitor.setCurrent(count);
793
			}
794
		}
795
		finally{
796
			input.close();
797
			output.close();
798
		}
799
		return count;
800
	}
801

  
802
	
803

  
736 804
}

Also available in: Unified diff