Skip to main content
summaryrefslogtreecommitdiffstats
blob: f9a5c635a7d3656c7975b2928b31daaaea625bc5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*******************************************************************************
 * Copyright (c) 2003 - 2006 University Of British Columbia and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University Of British Columbia - initial API and implementation
 *******************************************************************************/
package org.eclipse.mylar.internal.tasklist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.mylar.internal.core.util.DateUtil;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask;
import org.eclipse.mylar.provisional.tasklist.ITask;
import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.provisional.tasklist.TaskRepository;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask.RepositoryTaskSyncState;
import org.eclipse.ui.PlatformUI;

/**
 * Class to persist the data for the offline reports list
 */
public class OfflineReportsFile {

	public enum BugzillaOfflineStatus {
		SAVED, SAVED_WITH_OUTGOING_CHANGES, DELETED, SAVED_WITH_INCOMMING_CHANGES, CONFLICT, ERROR
	}

	/** The file that the offline reports are written to */
	private File file;

	/** A list of offline reports */
	private ArrayList<RepositoryReport> list = new ArrayList<RepositoryReport>();

	/** The bug id of the most recently created offline report. */
	protected int latestNewBugId = 0;

	private boolean updateLocalCopy = false;

	/**
	 * Constructor that reads the offline reports data persisted in the plugin's
	 * state directory, if it exists.
	 * 
	 * @param file
	 *            The file where the offline reports are persisted
	 * @throws IOException
	 *             Error opening or closing the offline reports file
	 * @throws ClassNotFoundException
	 * @throws ClassNotFoundException
	 *             Error deserializing objects from the offline reports file
	 */
	public OfflineReportsFile(File file, boolean read) throws IOException, ClassNotFoundException {
		this.file = file;
		if (read && file.exists()) {
			readFile();
		}
	}

	
	
	/**
	 * Add an offline report to the offline reports list
	 * 
	 * @param entry
	 *            The bug to add
	 */
	public RepositoryTaskSyncState add(final RepositoryReport entry, boolean forceSync) throws CoreException {

		RepositoryTaskSyncState status = RepositoryTaskSyncState.SYNCHRONIZED;

		try {

			String handle = AbstractRepositoryTask.getHandle(entry.getRepositoryUrl(), entry.getId());
			ITask task = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);
			
			if (task != null && task instanceof AbstractRepositoryTask) {
				AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask) task;
				
				TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository(repositoryTask.getRepositoryKind(), repositoryTask.getRepositoryUrl());
				
				if(repository == null) {
					throw new Exception("No repository associated with task. Unable to retrieve timezone information.");
				}
				
				TimeZone repositoryTimeZone = DateUtil.getTimeZone(repository.getTimeZoneId());				
				
				int index = -1;
				if ((index = find(entry.getRepositoryUrl(), entry.getId())) >= 0) {
					RepositoryReport oldBug = list.get(index);

					if (repositoryTask.getLastSynchronized() == null
							|| entry.getLastModified(repositoryTimeZone).compareTo(repositoryTask.getLastSynchronized()) > 0 || forceSync) {

						if (oldBug.hasChanges()) {

							PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
								public void run() {
									updateLocalCopy = MessageDialog
											.openQuestion(
													null,
													"Update Local Copy",
													"Local copy of Report "
															+ entry.getId()
															+ " on "
															+ entry.getRepositoryUrl()
															+ " has changes.\nWould you like to override local changes? \n\nNote: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost.");
								}
							});

							if (!updateLocalCopy) {
								((RepositoryReport) entry).setNewComment(((RepositoryReport) oldBug).getNewComment());
								((RepositoryReport) entry).setHasChanged(true);
								status = RepositoryTaskSyncState.CONFLICT;
							} else {
								((RepositoryReport) entry).setHasChanged(false);
								status = RepositoryTaskSyncState.SYNCHRONIZED;
							}
						} else {
							if (forceSync) {
								status = RepositoryTaskSyncState.SYNCHRONIZED;
							} else {
								status = RepositoryTaskSyncState.INCOMING;
							}
						}
						list.remove(index);
						if (entry.hasChanges() && status != RepositoryTaskSyncState.CONFLICT) {
							status = RepositoryTaskSyncState.OUTGOING;
						}
						list.add(entry);
						writeFile();
					}
				} else {
					// report doesn't exist in offline reports
					list.add(entry);
					writeFile();
				}
				repositoryTask.setLastSynchronized(entry.getLastModified(repositoryTimeZone));
			}
		} catch (Exception e) {
			e.printStackTrace();
			IStatus runtimestatus = new Status(IStatus.ERROR, MylarTaskListPlugin.PLUGIN_ID, IStatus.OK,
					"failed to add offline report", e);
			throw new CoreException(runtimestatus);
		}
		return status;
	}
	

	// DO NOT REMOVE
	// /**
	// * Add an offline report to the offline reports list
	// *
	// * @param entry
	// * The bug to add
	// */
	// public BugzillaOfflineStatus add(BugzillaReport entry, boolean
	// saveChosen) throws CoreException {
	//
	// BugzillaOfflineStatus status = BugzillaOfflineStatus.SAVED;
	//
	// try {
	//
	// // check for bug and do a compare
	// int index = -1;
	// if ((index = find(entry.getRepositoryUrl(), entry.getId())) >= 0) {
	// BugzillaReport oldBug = list.get(index);
	// if (oldBug instanceof BugzillaReport && entry instanceof BugzillaReport
	// && !saveChosen) {
	// CompareConfiguration config = new CompareConfiguration();
	// config.setLeftEditable(false);
	// config.setRightEditable(false);
	// config.setLeftLabel("Local Bug Report");
	// config.setRightLabel("Remote Bug Report");
	// config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(
	// ISharedImages.IMG_OBJ_ELEMENT));
	// config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(
	// ISharedImages.IMG_OBJ_ELEMENT));
	// final BugzillaCompareInput in = new BugzillaCompareInput(config);
	// oldBug.setOfflineState(true);
	// in.setLeft((BugzillaReport) oldBug);
	// in.setRight((BugzillaReport) entry);
	// in.setTitle("Bug #" + oldBug.getId());
	//
	// try {
	// in.run(null);
	// // running in new job inside a job causes shell to popup
	// // up, losing focus
	// // PlatformUI.getWorkbench().getProgressService().run(true,
	// // true, in);
	// } catch (InterruptedException x) {
	// // cancelled by user
	// // TODO: Check how errors are handled
	// return BugzillaOfflineStatus.ERROR;
	// } catch (InvocationTargetException x) {
	// BugzillaPlugin.log(x);
	// MessageDialog.openError(null, "Compare Failed",
	// x.getTargetException().getMessage());
	// return BugzillaOfflineStatus.ERROR;
	// }
	//
	// ITask dirtyTask = getDirtyTask(oldBug);
	//					
	//					
	// if (in.getCompareResult() == null) {
	// status = BugzillaOfflineStatus.SAVED;
	// } else if (oldBug.hasChanges() || dirtyTask != null) {
	// if (!MessageDialog
	// .openQuestion(
	// null,
	// "Update Local Copy",
	// "Local copy of Report "
	// + entry.getId() + " on "+entry.getRepositoryUrl()
	// + " has changes.\nWould you like to override local changes? \n\nNote: if
	// you select No, only the new comment will be saved with the updated bug,
	// all other changes will be lost.")) {
	// ((BugzillaReport) entry).setNewComment(((BugzillaReport)
	// oldBug).getNewComment());
	// ((BugzillaReport) entry).setHasChanged(true);
	// status = BugzillaOfflineStatus.CONFLICT;
	// } else {
	// ((BugzillaReport) entry).setHasChanged(false);
	// status = BugzillaOfflineStatus.SAVED;
	// }
	// if(dirtyTask != null) {
	// TaskUiUtil.closeEditorInActivePage(dirtyTask);
	// TaskUiUtil.openEditor(dirtyTask, false);
	// }
	// } else {
	// DiffNode node = (DiffNode) in.getCompareResult();
	// IDiffElement[] children = node.getChildren();
	// if (children.length != 0) {
	// for (IDiffElement element : children) {
	// if (((DiffNode) element).getKind() == Differencer.CHANGE) {
	// if(reopenEditors(oldBug)) {
	// status = BugzillaOfflineStatus.SAVED;
	// } else {
	// status = BugzillaOfflineStatus.SAVED_WITH_INCOMMING_CHANGES;
	// }
	// break;
	// }
	// }
	// } else {
	// status = BugzillaOfflineStatus.SAVED; // do we
	// // ever get
	// // here?
	// }
	// }
	//
	// // Display.getDefault().asyncExec(new Runnable(){
	// // public void run() {
	// //
	// // CompareUI.openCompareDialog(in);
	// // }
	// // });
	// }
	// list.remove(index);
	// }
	// if (entry.hasChanges() && status != BugzillaOfflineStatus.CONFLICT) {
	// status = BugzillaOfflineStatus.SAVED_WITH_OUTGOING_CHANGES;
	// }
	// // add the entry to the list and write the file to disk
	// list.add(entry);
	// writeFile();
	// } catch (Exception e) {
	// e.printStackTrace();
	// IStatus runtimestatus = new Status(IStatus.ERROR,
	// BugzillaUiPlugin.PLUGIN_ID, IStatus.OK,
	// "failed to add offline report", e);
	// throw new CoreException(runtimestatus);
	// }
	// return status;
	// }

	/**
	 * Updates the offline reports list. Used when existing offline reports are
	 * modified and saved.
	 */
	public void update() {
		// check for bug and do a compare
		writeFile();
	}

	/**
	 * @return The id that a new offline bug should use. The value changes each
	 *         time this method is called.
	 */
	public int getNextOfflineBugId() {
		latestNewBugId++;
		return latestNewBugId;
	}

	/**
	 * Find a bug in the offline reports list.
	 * 
	 * @param id
	 *            The bug id that we are looking for
	 * @return The index of the bug in the array if it exists, else -1. Locally
	 *         created bugs are ignored.
	 */
	public int find(String repositoryUrl, int id) {
		for (int i = 0; i < list.size(); i++) {
			RepositoryReport currBug = list.get(i);
			if (currBug != null && currBug.getRepositoryUrl() != null
					&& (currBug.getRepositoryUrl().equals(repositoryUrl) && currBug.getId() == id)
					&& !currBug.isLocallyCreated())
				return i;
		}
		return -1;
	}

	// TODO: move to plugin
	public static RepositoryReport findBug(String repositoryUrl, int bugId) {
		int location = MylarTaskListPlugin.getDefault().getOfflineReportsFile().find(repositoryUrl, bugId);
		if (location != -1) {
			return MylarTaskListPlugin.getDefault().getOfflineReportsFile().elements().get(location);
		}
		return null;
	}

	/**
	 * Get the list of offline reports
	 * 
	 * @return The list of offline reports
	 */
	public ArrayList<RepositoryReport> elements() {
		return list;
	}

	/**
	 * Write the offline reports to disk
	 */
	private void writeFile() {
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(file));

			// Write the size of the list so that we can read it back in easier
			out.writeInt(list.size());

			out.writeInt(latestNewBugId);

			// write each element in the array list
			for (int i = 0; i < list.size(); i++) {
				RepositoryReport item = list.get(i);
				out.writeObject(item);
			}
			out.close();
		} catch (IOException e) {
			// put up a message and log the error if there is a problem writing
			// to the file
			MessageDialog.openError(null, "I/O Error", "Could not write to offline reports file.");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// ignore
				}
			}
		}
	}

	/**
	 * Read the offline reports in from the file on disk
	 * 
	 * @throws IOException
	 *             Error opening or closing the offline reports file
	 * @throws ClassNotFoundException
	 * @throws ClassNotFoundException
	 *             Error deserializing objects from the offline reports file
	 */
	private void readFile() throws IOException, ClassNotFoundException {

		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream(file));

			// get the number of offline reports in the file
			int size = in.readInt();

			// get the bug id of the most recently created offline report
			latestNewBugId = in.readInt();

			// read in each of the offline reports in the file
			for (int nX = 0; nX < size; nX++) {
				// try {
				RepositoryReport item = (RepositoryReport) in.readObject();
				// add the offline report to the offlineReports list
				list.add(item);
				// } catch (ClassNotFoundException e) {
				//				
				// // // ignore this since we can't do anything
				// // BugzillaPlugin.log(new Status(Status.ERROR,
				// // IBugzillaConstants.PLUGIN_ID, Status.ERROR,
				// // "Unable to read bug object", e));
				//				
				// }
			}

		} finally {
			in.close();
		}
	}

	/**
	 * Remove some bugs from the offline reports list
	 * 
	 * @param indicesToRemove
	 *            An array of the indicies of the bugs to be removed
	 */
	public void remove(List<RepositoryReport> sel) {
		list.removeAll(sel);

		// rewrite the file so that the data is persistant
		writeFile();
	}

	/**
	 * Remove all of the items in the offline reports menu
	 */
	public void removeAll() {
		list.clear();

		// rewrite the file so that the data is persistant
		writeFile();
	}

}
// /**
// * Function to sort the offline reports list
// * @param sortOrder The way to sort the bugs in the offline reports list
// */
// public void sort(int sortOrder) {
// IBugzillaBug[] a = list.toArray(new IBugzillaBug[list.size()]);
//		
// // decide which sorting method to use and sort the offline reports
// switch(sortOrder) {
// case ID_SORT:
// Arrays.sort(a, new SortID());
// lastSel = ID_SORT;
// break;
// case TYPE_SORT:
// Arrays.sort(a, new SortType());
// lastSel = TYPE_SORT;
// break;
// }
//		
// // remove all of the elements from the list so that we can re-add
// // them in a sorted order
// list.clear();
//		
// // add the sorted elements to the list and the table
// for (int j = 0; j < a.length; j++) {
// add(a[j]);
// }
// }

// /**
// * Inner class to sort by bug id
// */
// private class SortID implements Comparator<IBugzillaBug> {
// public int compare(IBugzillaBug f1, IBugzillaBug f2) {
// Integer id1 = f1.getId();
// Integer id2 = f2.getId();
//
// if(id1 != null && id2 != null)
// return id1.compareTo(id2);
// else if(id1 == null && id2 != null)
// return -1;
// else if(id1 != null && id2 == null)
// return 1;
// else
// return 0;
// }
// }
//
// /**
// * Inner class to sort by bug type (locally created or from the server)
// */
// private class SortType implements Comparator<IBugzillaBug> {
// public int compare(IBugzillaBug f1, IBugzillaBug f2) {
// boolean isLocal1 = f1.isLocallyCreated();
// boolean isLocal2 = f2.isLocallyCreated();
//			
// if (isLocal1 && !isLocal2) {
// return -1;
// }
// else if (!isLocal1 && isLocal2) {
// return 1;
// }
//			
// // If they are both the same type, sort by ID
// Integer id1 = f1.getId();
// Integer id2 = f2.getId();
//
// if(id1 != null && id2 != null)
// return id1.compareTo(id2);
// else if(id1 == null && id2 != null)
// return -1;
// else if(id1 != null && id2 == null)
// return 1;
// else
// return 0;
// }
// }

// /**
// * Saves the given report to the offlineReportsFile, or, if it already
// * exists in the file, updates it.
// *
// * @param bug
// * The bug to add/update.
// */
// public static void saveOffline(IBugzillaBug bug, boolean saveChosen) throws
// CoreException {
// OfflineReportsFile file = BugzillaPlugin.getDefault().getOfflineReports();
// // If there is already an offline report for this bug, update the file.
// if (bug.isSavedOffline()) {
// file.update();
// }
// // If this bug has not been saved offline before, add it to the file.
// else {
// int index = -1;
// // If there is already an offline report with the same id, don't
// // save this report.
// if ((index = file.find(bug.getId())) >= 0) {
// removeReport(getOfflineBugs().get(index));
// // MessageDialog.openInformation(null, "Bug's Id is already
// // used.", "There is already a bug saved offline with an
// // identical id.");
// // return;
// }
// file.add(bug, saveChosen);
// bug.setOfflineState(true);
// // file.sort(OfflineReportsFile.lastSel);
// }
// }

// public static List<IBugzillaBug> getOfflineBugs() {
// OfflineReportsFile file = BugzillaPlugin.getDefault().getOfflineReports();
// return file.elements();
// }
//
// /**
// * Removes the given report from the offlineReportsFile.
// *
// * @param bug
// * The report to remove.
// */
// public static void removeReport(IBugzillaBug bug) {
// ArrayList<IBugzillaBug> bugList = new ArrayList<IBugzillaBug>();
// bugList.add(bug);
// BugzillaPlugin.getDefault().getOfflineReports().remove(bugList);
// }

Back to the top