Skip to main content
summaryrefslogtreecommitdiffstats
blob: 67fa0e511ca64c3f6acadb87471846127afb27fb (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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*******************************************************************************
 * Copyright (c) 2004 - 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.bugzilla.ui.tasklist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.Proxy;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

import javax.security.auth.login.LoginException;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.mylar.internal.bugzilla.core.AbstractReportFactory;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaException;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaPlugin;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaReportSubmitForm;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaRepositoryUtil;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylar.internal.bugzilla.core.PossibleBugzillaFailureException;
import org.eclipse.mylar.internal.bugzilla.core.AbstractReportFactory.UnrecognizedBugzillaError;
import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants.BugzillaServerVersion;
import org.eclipse.mylar.internal.bugzilla.ui.WebBrowserDialog;
import org.eclipse.mylar.internal.bugzilla.ui.search.BugzillaResultCollector;
import org.eclipse.mylar.internal.bugzilla.ui.search.BugzillaSearchHit;
import org.eclipse.mylar.internal.bugzilla.ui.search.RepositoryQueryResultsFactory;
import org.eclipse.mylar.internal.bugzilla.ui.tasklist.BugzillaCategorySearchOperation.ICategorySearchListener;
import org.eclipse.mylar.internal.bugzilla.ui.wizard.NewBugzillaReportWizard;
import org.eclipse.mylar.internal.core.util.DateUtil;
import org.eclipse.mylar.internal.core.util.MylarStatusHandler;
import org.eclipse.mylar.internal.core.util.ZipFileUtil;
import org.eclipse.mylar.internal.tasklist.AbstractRepositoryReport;
import org.eclipse.mylar.internal.tasklist.ReportAttachment;
import org.eclipse.mylar.internal.tasklist.RepositoryReport;
import org.eclipse.mylar.internal.tasklist.ui.views.TaskRepositoriesView;
import org.eclipse.mylar.internal.tasklist.ui.wizards.AbstractAddExistingTaskWizard;
import org.eclipse.mylar.internal.tasklist.ui.wizards.AbstractRepositorySettingsPage;
import org.eclipse.mylar.internal.tasklist.ui.wizards.ExistingTaskWizardPage;
import org.eclipse.mylar.internal.tasklist.util.TaskDataExportJob;
import org.eclipse.mylar.provisional.core.MylarPlugin;
import org.eclipse.mylar.provisional.tasklist.AbstractQueryHit;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryConnector;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryQuery;
import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask;
import org.eclipse.mylar.provisional.tasklist.IRemoteContextDelegate;
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.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

/**
 * @author Mik Kersten
 * @author Rob Elves
 */
public class BugzillaRepositoryConnector extends AbstractRepositoryConnector {

	private static final int MAX_URL_LENGTH = 2000;

	private static final String CHANGED_BUGS_START_DATE_SHORT = "yyyy-MM-dd";

	private static final String CHANGED_BUGS_START_DATE_LONG = "yyyy-MM-dd HH:mm:ss";

	private static final String CHANGED_BUGS_CGI_ENDDATE = "&chfieldto=Now";

	private static final String CHANGED_BUGS_CGI_QUERY = "/buglist.cgi?query_format=advanced&chfieldfrom=";

	private static final String ZIPFILE_EXTENSION = ".zip";

	private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";

	private static final String LABEL_JOB_SUBMIT = "Submitting to Bugzilla repository";

	private static final String DESCRIPTION_DEFAULT = "<needs synchronize>";

	private static final String CLIENT_LABEL = "Bugzilla (supports uncustomized 2.18-2.22)";

	private List<String> supportedVersions;

	public BugzillaRepositoryConnector() {
		super();
	}

	public String getLabel() {
		return CLIENT_LABEL;
	}

	public AbstractRepositorySettingsPage getSettingsPage() {
		return new BugzillaRepositorySettingsPage(this);
	}

	public String getRepositoryType() {
		return BugzillaPlugin.REPOSITORY_KIND;
	}

	public void saveBugReport(RepositoryReport bugzillaBug) {
		String handle = AbstractRepositoryTask.getHandle(bugzillaBug.getRepositoryUrl(), bugzillaBug.getId());
		ITask task = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);
		if (task instanceof BugzillaTask) {
			BugzillaTask bugzillaTask = (BugzillaTask) task;
			bugzillaTask.setBugReport((RepositoryReport) bugzillaBug);

			if (bugzillaBug.hasChanges()) {
				bugzillaTask.setSyncState(RepositoryTaskSyncState.OUTGOING);
			} else {
				bugzillaTask.setSyncState(RepositoryTaskSyncState.SYNCHRONIZED);
			}
		}

		saveOffline(bugzillaBug, true);

	}

	private RepositoryReport downloadReport(final BugzillaTask bugzillaTask) {
		TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository(
				BugzillaPlugin.REPOSITORY_KIND, bugzillaTask.getRepositoryUrl());
		Proxy proxySettings = MylarTaskListPlugin.getDefault().getProxySettings();
		try {
			return BugzillaRepositoryUtil.getBug(repository.getUrl(), repository.getUserName(), repository
					.getPassword(), proxySettings, repository.getCharacterEncoding(), AbstractRepositoryTask
					.getTaskIdAsInt(bugzillaTask.getHandleIdentifier()));
		} catch (final LoginException e) {
			PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
				public void run() {
					MessageDialog.openError(Display.getDefault().getActiveShell(), "Report Download Failed",
							"Ensure proper repository configuration of " + bugzillaTask.getRepositoryUrl() + " in "
									+ TaskRepositoriesView.NAME + ".");
				}
			});
		} catch (final UnrecognizedBugzillaError e) {
			PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
				public void run() {
					WebBrowserDialog.openAcceptAgreement(null, "Report Download Failed", "Unrecognized response from "
							+ bugzillaTask.getRepositoryUrl(), e.getMessage());
				}
			});
		} catch (final Exception e) {
			if (PlatformUI.getWorkbench() != null && !PlatformUI.getWorkbench().isClosing()) {
				PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
					public void run() {

						if (e instanceof FileNotFoundException) {
							MessageDialog.openError(Display.getDefault().getActiveShell(), "Report Download Failed",
									"Resource not found: " + e.getMessage());
							return;
						}

						((ApplicationWindow) PlatformUI.getWorkbench().getActiveWorkbenchWindow())
								.setStatus("Download of bug: " + bugzillaTask + " from "
										+ bugzillaTask.getRepositoryUrl() + " failed due to exception: " + e);
					}
				});
			}
		}
		return null;
	}

	public ITask createTaskFromExistingKey(TaskRepository repository, String id) {
		int bugId = -1;
		try {
			if (id != null) {
				bugId = Integer.parseInt(id);
			} else {
				return null;
			}
		} catch (NumberFormatException nfe) {
			if (!forceSyncExecForTesting) {
				MessageDialog.openInformation(null, MylarTaskListPlugin.TITLE_DIALOG, "Invalid report id: " + id);
			}
			return null;
		}

		String handle = AbstractRepositoryTask.getHandle(repository.getUrl(), bugId);
		ITask task = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);

		if (task == null) {
			task = new BugzillaTask(handle, DESCRIPTION_DEFAULT, true);
			MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(task);
		}

		// MylarTaskListPlugin.BgetTaskListManager().getTaskList().addTaskToArchive(newTask);
		if (task instanceof AbstractRepositoryTask) {
			synchronize((AbstractRepositoryTask) task, true, null);
		}
		return task;
	}

	public IWizard getNewQueryWizard(TaskRepository repository) {
		return new NewBugzillaQueryWizard(repository);
	}

	public IWizard getEditQueryWizard(TaskRepository repository, AbstractRepositoryQuery query) {
		if (!(query instanceof BugzillaRepositoryQuery)) {
			return null;
		}
		return new EditBugzillaQueryWizard(repository, (BugzillaRepositoryQuery) query);
	}

	public IWizard getAddExistingTaskWizard(TaskRepository repository) {

		// TODO create a propper subclass for Bugzilla
		return new AbstractAddExistingTaskWizard(repository) {

			private ExistingTaskWizardPage page;

			public void addPages() {
				super.addPages();
				this.page = new ExistingTaskWizardPage();
				addPage(page);
			}

			protected String getTaskId() {
				return page.getTaskId();
			}
		};
	}

	public void openEditQueryDialog(AbstractRepositoryQuery query) {
		if (!(query instanceof BugzillaRepositoryQuery)) {
			return;
		}
		// BugzillaRepositoryQuery queryCategory = (BugzillaRepositoryQuery)
		// query;
		//
		// if (queryCategory.isCustomQuery()) {
		// // BugzillaCustomRepositoryQuery queryCategory =
		// // (BugzillaCustomRepositoryQuery) query;
		// BugzillaCustomQueryDialog sqd = new
		// BugzillaCustomQueryDialog(Display.getCurrent().getActiveShell(),
		// queryCategory.getQueryUrl(), queryCategory.getDescription(),
		// queryCategory.getMaxHits() + "");
		// if (sqd.open() == Dialog.OK) {
		// MylarTaskListPlugin.getTaskListManager().getTaskList().renameContainer(queryCategory,
		// sqd.getName());
		// // queryCategory.setDescription(sqd.getName());
		// queryCategory.setQueryUrl(sqd.getUrl());
		// int maxHits = -1;
		// try {
		// maxHits = Integer.parseInt(sqd.getMaxHits());
		// } catch (Exception e) {
		// }
		// queryCategory.setMaxHits(maxHits);
		//
		// synchronize(queryCategory, null);
		// }
		// } else {
		// // BugzillaRepositoryQuery queryCategory = (BugzillaRepositoryQuery)
		// // query;
		// BugzillaQueryDialog queryDialog = new
		// BugzillaQueryDialog(Display.getCurrent().getActiveShell(),
		// queryCategory.getRepositoryUrl(), queryCategory.getQueryUrl(),
		// queryCategory.getDescription(),
		// queryCategory.getMaxHits() + "");
		// if (queryDialog.open() == Dialog.OK) {
		// MylarTaskListPlugin.getTaskListManager().getTaskList().renameContainer(queryCategory,
		// queryDialog.getName());
		// // queryCategory.setDescription(queryDialog.getName());
		// queryCategory.setQueryUrl(queryDialog.getUrl());
		// queryCategory.setRepositoryUrl(queryDialog.getRepository().getUrl());
		// int maxHits = -1;
		// try {
		// maxHits = Integer.parseInt(queryDialog.getMaxHits());
		// } catch (Exception e) {
		// }
		// queryCategory.setMaxHits(maxHits);
		//
		// new SynchronizeReportsAction(queryCategory).run();
		// }
		// }

		try {
			TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository(
					query.getRepositoryKind(), query.getRepositoryUrl());
			if (repository == null)
				return;

			IWizard wizard = this.getEditQueryWizard(repository, query);

			Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
			if (wizard != null && shell != null && !shell.isDisposed()) {
				WizardDialog dialog = new WizardDialog(shell, wizard);
				dialog.create();
				dialog.setTitle("Edit Bugzilla Query");
				dialog.setBlockOnOpen(true);
				if (dialog.open() == Dialog.CANCEL) {
					dialog.close();
					return;
				}
			}
		} catch (Exception e) {
			MylarStatusHandler.fail(e, e.getMessage(), true);
		}
	}

	private static void offlineStatusChange(AbstractRepositoryReport report, RepositoryTaskSyncState state) {

		// RepositoryTaskSyncState state = null;
		// if (status == BugzillaOfflineStatus.SAVED_WITH_OUTGOING_CHANGES) {
		// state = RepositoryTaskSyncState.OUTGOING;
		// } else if (status == BugzillaOfflineStatus.SAVED) {
		// state = RepositoryTaskSyncState.SYNCHRONIZED;
		// } else if (status ==
		// BugzillaOfflineStatus.SAVED_WITH_INCOMMING_CHANGES) {
		// // if (forceSynch) {
		// state = RepositoryTaskSyncState.INCOMING;
		// // } else {
		// // User opened (forceSynch = false) so no need to denote
		// // incomming
		// // state = RepositoryTaskSyncState.SYNCHRONIZED;
		// // }
		// } else if (status == BugzillaOfflineStatus.CONFLICT) {
		// state = RepositoryTaskSyncState.CONFLICT;
		// } else if (status == BugzillaOfflineStatus.DELETED) {
		// state = RepositoryTaskSyncState.SYNCHRONIZED;
		// }
		if (report == null || state == null) {
			return;
		}

		String handle = AbstractRepositoryTask.getHandle(report.getRepositoryUrl(), report.getId());
		ITask task = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);
		if (task != null && task instanceof BugzillaTask) {
			final BugzillaTask bugTask = (BugzillaTask) task;
			if (bugTask.getSyncState() != state) {
				bugTask.setSyncState(state);
				PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
					public void run() {
						MylarTaskListPlugin.getTaskListManager().getTaskList().notifyRepositoryInfoChanged(bugTask);
					}
				});
			}
		}
	}

	public void submitBugReport(final RepositoryReport bugReport, final BugzillaReportSubmitForm form,
			IJobChangeListener listener) {

		if (forceSyncExecForTesting) {
			internalSubmitBugReport(bugReport, form);
		} else {
			// TODO: get rid of this idiom?
			final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
				protected void execute(final IProgressMonitor monitor) throws CoreException {
					internalSubmitBugReport(bugReport, form);
				}
			};

			Job job = new Job(LABEL_JOB_SUBMIT) {
				@Override
				protected IStatus run(IProgressMonitor monitor) {
					try {
						op.run(monitor);
					} catch (final Throwable throwable) {
						PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
							public void run() {
								// TODO: clean up exception handling
								if (throwable.getCause() instanceof BugzillaException) {
									MessageDialog.openError(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
											"Bugzilla could not post your bug.");
								} else if (throwable.getCause() instanceof PossibleBugzillaFailureException) {
									// String attributes = "";
									// if (bugReport != null) {
									// for (AbstractRepositoryTaskAttribute
									// attribute : bugReport.getAttributes()) {
									// attributes += attribute.getID() + "=" +
									// attribute.getValue() + " | ";
									// }
									// MylarStatusHandler.log(attributes,
									// BugzillaRepositoryConnector.class);
									// }
									WebBrowserDialog.openAcceptAgreement(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
											"Possible problem posting Bugzilla report.\n"
													+ throwable.getCause().getMessage(), form.getError());
								} else if (throwable.getCause() instanceof LoginException) {
									MessageDialog.openError(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
											"Bugzilla could not post your bug since your login name or password is incorrect."
													+ " Ensure proper repository configuration in "
													+ TaskRepositoriesView.NAME + ".");
								} else {
									MylarStatusHandler.fail(throwable, "could not post bug", false);
									MessageDialog.openError(null, IBugzillaConstants.TITLE_MESSAGE_DIALOG,
											"Could not post bug.  Check repository credentials and connectivity.\n\n"
													+ throwable);
								}
							}
						});
						return new Status(Status.INFO, "org.eclipse.mylar.internal.bugzilla.ui", Status.INFO,
								"Failed to submit bug", throwable);
					}
					return Status.OK_STATUS;
				}
			};
			job.addJobChangeListener(listener);
			job.schedule();
		}
	}

	private void internalSubmitBugReport(RepositoryReport bugReport, BugzillaReportSubmitForm form) {
		try {
			form.submitReportToRepository();
			removeReport(bugReport);
			String handle = AbstractRepositoryTask.getHandle(bugReport.getRepositoryUrl(), bugReport.getId());

			ITask task = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);
			if (task != null) {
				Set<AbstractRepositoryQuery> queriesWithHandle = MylarTaskListPlugin.getTaskListManager().getTaskList()
						.getQueriesForHandle(task.getHandleIdentifier());
				synchronize(queriesWithHandle, null, Job.SHORT, 0, true);

				if (task instanceof AbstractRepositoryTask) {
					synchronize((AbstractRepositoryTask) task, true, null);
				}
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// /**
	// * Saves the given report to the offlineReportsFile, or, if it already
	// * exists in the file, updates it.
	// *
	// * @param bug
	// * The bug to add/update.
	// * @param saveChosen
	// * This is used to determine a refresh from a user save
	// */
	// public BugzillaOfflineStatus saveOffline(final BugzillaReport bug, final
	// boolean forceSynch) {
	//
	// BugzillaOfflineStatus status = BugzillaOfflineStatus.ERROR;
	//
	// // if (!forceSyncExecForTesting) {
	// // Display.getDefault().asyncExec(new Runnable() {
	// // public void run() {
	// // internalSaveOffline(bug, forceSynch);
	// // }
	// // });
	// // } else {
	// internalSaveOffline(bug, forceSynch);
	// // }
	// return status;
	// }

	// TODO: pull up
	public void saveOffline(final RepositoryReport report, final boolean forceSynch) {
		// If there is already an offline report for this bug, update the file.

		if (((AbstractRepositoryReport) report).isSavedOffline()) {
			MylarTaskListPlugin.getDefault().getOfflineReportsFile().update();
		} else {
			try {
				// 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;
				// }
				RepositoryTaskSyncState offlineStatus = MylarTaskListPlugin.getDefault().getOfflineReportsFile().add(
						report, forceSynch);
				((AbstractRepositoryReport) report).setOfflineState(true);
				offlineStatusChange(report, offlineStatus);

			} catch (CoreException e) {
				MylarStatusHandler.fail(e, e.getMessage(), false);
			}
			// file.sort(OfflineTaskManager.lastSel);
		}
	}

//	public static List<BugzillaReport> getOfflineBugs() {
//		OfflineReportManager file = BugzillaUiPlugin.getDefault().getOfflineReportsFile();
//		return file.elements();
//	}

	public static void removeReport(RepositoryReport bug) {
		bug.setOfflineState(false);
		// offlineStatusChange(bug, BugzillaOfflineStatus.DELETED, false);
		offlineStatusChange(bug, RepositoryTaskSyncState.SYNCHRONIZED);
		ArrayList<RepositoryReport> bugList = new ArrayList<RepositoryReport>();
		bugList.add(bug);
		MylarTaskListPlugin.getDefault().getOfflineReportsFile().remove(bugList);
	}

	@Override
	public boolean canCreateTaskFromKey() {
		return true;
	}

	@Override
	public boolean canCreateNewTask() {
		return true;
	}

	@Override
	public IWizard getNewTaskWizard(TaskRepository taskRepository) {
		return new NewBugzillaReportWizard(taskRepository);
	}

	public List<String> getSupportedVersions() {
		if (supportedVersions == null) {
			supportedVersions = new ArrayList<String>();
			for (BugzillaServerVersion version : BugzillaServerVersion.values()) {
				supportedVersions.add(version.toString());
			}
		}
		return supportedVersions;
	}

	/** public for testing purposes * */
	@Override
	public List<AbstractQueryHit> performQuery(final AbstractRepositoryQuery repositoryQuery, IProgressMonitor monitor,
			MultiStatus status) {
		TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository(
				repositoryQuery.getRepositoryKind(), repositoryQuery.getRepositoryUrl());

		final BugzillaCategorySearchOperation categorySearch = new BugzillaCategorySearchOperation(repository,
				repositoryQuery.getQueryUrl(), repositoryQuery.getMaxHits());

		final ArrayList<AbstractQueryHit> newHits = new ArrayList<AbstractQueryHit>();
		categorySearch.addResultsListener(new ICategorySearchListener() {
			public void searchCompleted(BugzillaResultCollector collector) {
				for (BugzillaSearchHit hit : collector.getResults()) {
					String description = hit.getId() + ": " + hit.getDescription();
					newHits.add(new BugzillaQueryHit(description, hit.getPriority(),
							repositoryQuery.getRepositoryUrl(), hit.getId(), null, hit.getState()));
				}
			}
		});

		categorySearch.execute(monitor);
		try {
			IStatus queryStatus = categorySearch.getStatus();
			if (!queryStatus.isOK()) {
				status.add(new Status(IStatus.OK, MylarTaskListPlugin.PLUGIN_ID, IStatus.OK, queryStatus.getMessage(),
						queryStatus.getException()));
			} else {
				status.add(queryStatus);
			}
		} catch (LoginException e) {
			// TODO: Set some form of disconnect status on Query?
			MylarStatusHandler.fail(e, "login failure for repository url: " + repository, false);
			status.add(new Status(IStatus.OK, MylarTaskListPlugin.PLUGIN_ID, IStatus.OK, "Could not log in", e));
		}

		return newHits;
	}

	@Override
	protected void updateOfflineState(AbstractRepositoryTask repositoryTask, boolean forceSync) {
		if (repositoryTask instanceof BugzillaTask) {
			BugzillaTask bugzillaTask = (BugzillaTask) repositoryTask;
			RepositoryReport downloadedReport = downloadReport(bugzillaTask);
			if (downloadedReport != null) {
				bugzillaTask.setBugReport(downloadedReport);
				saveOffline(downloadedReport, forceSync);
			}
		}
	}

	@Override
	public boolean attachContext(TaskRepository repository, AbstractRepositoryTask task, String longComment)
			throws IOException {
		if (!repository.hasCredentials()) {
			MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
					MylarTaskListPlugin.TITLE_DIALOG, "Repository credentials missing or invalid.");
			return false;
		} else {
			boolean result = false;
			MylarPlugin.getContextManager().saveContext(task.getHandleIdentifier());
			File sourceContextFile = MylarPlugin.getContextManager().getFileForContext(task.getHandleIdentifier());

			if (sourceContextFile != null && sourceContextFile.exists()) {
				File folder = sourceContextFile.getParentFile();
				if (folder != null && folder.exists() && folder.isDirectory()) {
					List<ITask> tasksToExport = new ArrayList<ITask>();
					tasksToExport.add(task);
					TaskDataExportJob job = new TaskDataExportJob(MylarPlugin.getDefault().getDataDirectory(), false,
							false, true, true, sourceContextFile.getName() + ZIPFILE_EXTENSION, tasksToExport);

					// IProgressService service =
					// PlatformUI.getWorkbench().getProgressService();

					try {
						// service.run(true, false, job);
						job.run(new NullProgressMonitor());

						File zippedContextFile = new File(MylarPlugin.getDefault().getDataDirectory() + File.separator
								+ sourceContextFile.getName() + ZIPFILE_EXTENSION);
						if (zippedContextFile != null && zippedContextFile.exists()) {
							result = BugzillaRepositoryUtil.uploadAttachment(repository.getUrl(), repository
									.getUserName(), repository.getPassword(), BugzillaTask.getTaskIdAsInt(task
									.getHandleIdentifier()), longComment, MYLAR_CONTEXT_DESCRIPTION, zippedContextFile,
									APPLICATION_OCTET_STREAM, false);
							if (result) {
								synchronize(task, false, null);
							}
						}

					} catch (InvocationTargetException e) {
						MylarStatusHandler.fail(e, "Could not export task context as zip file", true);
					} catch (InterruptedException e) {
						MylarStatusHandler.fail(e, "Could not export task context as zip file", true);
					}

				}
			}

			// if (sourceContextFile != null && sourceContextFile.exists()) {
			// result = BugzillaRepositoryUtil.uploadAttachment(repository,
			// BugzillaTask.getTaskIdAsInt(task
			// .getHandleIdentifier()), longComment, MYLAR_CONTEXT_DESCRIPTION,
			// sourceContextFile,
			// CONTENTTYPE_APPLICATION_XML, false);
			// if (result) {
			// synchronize(task, false, null);
			// }
			// }
			return result;
		}
	}

	@Override
	public Set<IRemoteContextDelegate> getAvailableContexts(TaskRepository repository, AbstractRepositoryTask task) {
		Set<IRemoteContextDelegate> contextDelegates = new HashSet<IRemoteContextDelegate>();
		if (task instanceof BugzillaTask) {
			BugzillaTask bugzillaTask = (BugzillaTask) task;
			if (bugzillaTask.getBugReport() != null) {
				for (ReportAttachment attachment : bugzillaTask.getBugReport().getAttachments()) {
					if (attachment.getDescription().equals(MYLAR_CONTEXT_DESCRIPTION)) {
						contextDelegates.add(new BugzillaRemoteContextDelegate(attachment));
					}
				}
				// for (Comment comment :
				// bugzillaTask.getBugReport().getComments()) {
				// if (comment.hasAttachment() &&
				// comment.getAttachmentDescription().equals(MYLAR_CONTEXT_DESCRIPTION))
				// {
				// contextDelegates.add(new
				// BugzillaRemoteContextDelegate(comment));
				// }
				// }
			}
		}
		return contextDelegates;
	}

	@Override
	public boolean retrieveContext(TaskRepository repository, AbstractRepositoryTask task,
			IRemoteContextDelegate remoteContextDelegate) throws IOException, GeneralSecurityException {
		boolean result = false;
		boolean wasActive = false;
		if (remoteContextDelegate instanceof BugzillaRemoteContextDelegate) {
			BugzillaRemoteContextDelegate contextDelegate = (BugzillaRemoteContextDelegate) remoteContextDelegate;

			if (task.isActive()) {
				wasActive = true;
				MylarTaskListPlugin.getTaskListManager().deactivateTask(task);
			}

			File destinationContextFile = MylarPlugin.getContextManager().getFileForContext(task.getHandleIdentifier());

			File destinationZipFile = new File(destinationContextFile.getPath() + ZIPFILE_EXTENSION);

			// if(destinationContextFile.exists()) {
			// destinationContextFile.delete();
			// }

			Proxy proxySettings = MylarTaskListPlugin.getDefault().getProxySettings();
			result = BugzillaRepositoryUtil.downloadAttachment(repository.getUrl(), repository.getUserName(),
					repository.getPassword(), proxySettings, contextDelegate.getId(), destinationZipFile, true);

			if (result) {

				ZipFileUtil.unzipFiles(destinationZipFile, MylarPlugin.getDefault().getDataDirectory());

				if (destinationContextFile.exists()) {

					MylarTaskListPlugin.getTaskListManager().getTaskList().notifyLocalInfoChanged(task);
					if (wasActive) {
						MylarTaskListPlugin.getTaskListManager().activateTask(task);
					}
				}
			}
		}
		return result;
	}

	public String getRepositoryUrlFromTaskUrl(String url) {
		if (url == null) {
			return null;
		} else {
			int index = url.indexOf(BugzillaRepositoryUtil.POST_ARGS_SHOW_BUG);
			if (index != -1) {
				return url.substring(0, index);
			} else {
				return null;
			}
		}
	}

	public void openRemoteTask(String repositoryUrl, String idString) {
		int id = -1;
		try {
			id = Integer.parseInt(idString);
		} catch (NumberFormatException e) {
			// ignore
		}
		if (id != -1) {
			IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
			OpenBugzillaReportJob job = new OpenBugzillaReportJob(repositoryUrl, id, page);
			job.schedule();
		}
	}

	@Override
	public Set<AbstractRepositoryTask> getChangedSinceLastSync(TaskRepository repository,
			Set<AbstractRepositoryTask> tasks) throws Exception {

		Set<AbstractRepositoryTask> changedTasks = new HashSet<AbstractRepositoryTask>();

		if (repository.getSyncTime() == null) {
			return tasks;
		}

		TimeZone timeZone = TimeZone.getTimeZone(repository.getTimeZoneId());

		if (!timeZone.getID().equals(repository.getTimeZoneId())) {
			MylarStatusHandler.log("Mylar: Specified time zone not available, using GMT. Check repository settings in "
					+ TaskRepositoriesView.NAME + ".", BugzillaRepositoryConnector.class);
		}

		String dateString = DateUtil.getZoneFormattedDate(timeZone, repository.getSyncTime(),
				CHANGED_BUGS_START_DATE_LONG);
		String urlQueryBase;
		String urlQueryString;

		try {
			urlQueryBase = repository.getUrl() + CHANGED_BUGS_CGI_QUERY
					+ URLEncoder.encode(dateString, repository.getCharacterEncoding()) + CHANGED_BUGS_CGI_ENDDATE;
		} catch (UnsupportedEncodingException e1) {
			MylarStatusHandler.log(e1, "Mylar: Check encoding settings in " + TaskRepositoriesView.NAME + ".");
			urlQueryBase = repository.getUrl() + CHANGED_BUGS_CGI_QUERY
					+ DateUtil.getZoneFormattedDate(timeZone, repository.getSyncTime(), CHANGED_BUGS_START_DATE_SHORT)
					+ CHANGED_BUGS_CGI_ENDDATE;
		}

		urlQueryString = new String(urlQueryBase);

		int queryCounter = -1;
		Iterator itr = tasks.iterator();
		while (itr.hasNext()) {
			queryCounter++;
			ITask task = (ITask) itr.next();

			String newurlQueryString = "&field0-0-" + queryCounter + "=bug_id&type0-0-" + queryCounter
					+ "=equals&value0-0-" + queryCounter + "="
					+ AbstractRepositoryTask.getTaskId(task.getHandleIdentifier());
			// try {
			if ((urlQueryString.length() + newurlQueryString.length() + IBugzillaConstants.CONTENT_TYPE_RDF.length()) > MAX_URL_LENGTH) {
				urlQueryString += IBugzillaConstants.CONTENT_TYPE_RDF;
				queryForChanged(repository, changedTasks, urlQueryString);
				queryCounter = 0;
				urlQueryString = new String(urlQueryBase);
				urlQueryString += "&field0-0-" + queryCounter + "=bug_id&type0-0-" + queryCounter + "=equals&value0-0-"
						+ queryCounter + "=" + AbstractRepositoryTask.getTaskId(task.getHandleIdentifier());
			} else if (!itr.hasNext()) {
				urlQueryString += newurlQueryString;
				urlQueryString += IBugzillaConstants.CONTENT_TYPE_RDF;
				queryForChanged(repository, changedTasks, urlQueryString);
			} else {
				urlQueryString += newurlQueryString;
			}
			// } catch (SocketTimeoutException e) {
			// MylarStatusHandler.log("Timeout occurred while retrieving reports
			// from " + repository.getUrl()
			// + ", will synchronize all reports.", this);
			// } catch (Exception e) {
			// MylarStatusHandler.log(e, "Mylar: Error retrieving reports from "
			// + repository.getUrl()
			// + ", will synchronize all reports.");
			// return tasks;
			// }
		}
		return changedTasks;
	}

	private void queryForChanged(TaskRepository repository, Set<AbstractRepositoryTask> changedTasks,
			String urlQueryString) throws Exception {
		RepositoryQueryResultsFactory queryFactory = RepositoryQueryResultsFactory.getInstance();
		BugzillaResultCollector collector = new BugzillaResultCollector();

		queryFactory.performQuery(repository.getUrl(), collector, urlQueryString, MylarTaskListPlugin.getDefault()
				.getProxySettings(), AbstractReportFactory.RETURN_ALL_HITS, repository.getCharacterEncoding());

		for (BugzillaSearchHit hit : collector.getResults()) {
			String handle = AbstractRepositoryTask.getHandle(repository.getUrl(), hit.getId());
			ITask correspondingTask = MylarTaskListPlugin.getTaskListManager().getTaskList().getTask(handle);
			if (correspondingTask != null && correspondingTask instanceof AbstractRepositoryTask) {
				changedTasks.add((AbstractRepositoryTask) correspondingTask);
			}
		}
	}
}

// if
// (!BugzillaUiPlugin.getDefault().getPreferenceStore().getString(IBugzillaConstants.SERVER_VERSION).equals(""))
// {
// MylarTaskListPlugin.getTaskListManager().addActivityListener(new
// ITaskActivityListener() {
//
// public void tasklistRead() {
// String oldVersionSetting =
// BugzillaPlugin.getDefault().getPreferenceStore().getString(
// IBugzillaConstants.SERVER_VERSION);
//
// Set<TaskRepository> existingBugzillaRepositories =
// MylarTaskListPlugin.getRepositoryManager()
// .getRepositories(BugzillaPlugin.REPOSITORY_KIND);
// for (TaskRepository repository : existingBugzillaRepositories) {
// MylarTaskListPlugin.getRepositoryManager().setVersion(repository,
// oldVersionSetting);
// }
// BugzillaPlugin.getDefault().getPreferenceStore().setValue(IBugzillaConstants.SERVER_VERSION,
// "");
// MylarTaskListPlugin.getTaskListManager().removeActivityListener(this);
// }
//
// public void taskActivated(ITask task) {
// // ignore
// }
//
// public void tasksActivated(List<ITask> tasks) {
// // ignore
// }
//
// public void taskDeactivated(ITask task) {
// // ignore
// }
//
// public void activityChanged(DateRangeContainer week) {
// // ignore
// }
// });
// }

Back to the top