Skip to main content
summaryrefslogtreecommitdiffstats
blob: f7910a56aceee95a871058cefa92643cd3127616 (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
/*******************************************************************************
 * 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.tasks.ui.wizards;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.internal.context.core.MylarContextManager;
import org.eclipse.mylar.internal.context.core.util.ZipFileUtil;
import org.eclipse.mylar.tasks.core.AbstractTaskContainer;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.TaskList;
import org.eclipse.mylar.tasks.core.TaskRepositoryManager;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

/**
 * @author Rob Elves Some code leveraged from TaskDataExportWizard
 */
public class TaskDataImportWizard extends Wizard implements IImportWizard {

	private final static String SETTINGS_SECTION = "org.eclipse.mylar.tasklist.ui.importWizard";

	private final static String WINDOW_TITLE = "Import";

	private TaskDataImportWizardPage importPage = null;

	public TaskDataImportWizard() {
		super();
		IDialogSettings masterSettings = TasksUiPlugin.getDefault().getDialogSettings();
		setDialogSettings(getSettingsSection(masterSettings));
		setNeedsProgressMonitor(true);
		setWindowTitle(WINDOW_TITLE);
	}

	/**
	 * Finds or creates a dialog settings section that is used to make the
	 * dialog control settings persistent
	 */
	public IDialogSettings getSettingsSection(IDialogSettings master) {
		IDialogSettings settings = master.getSection(SETTINGS_SECTION);
		if (settings == null) {
			settings = master.addNewSection(SETTINGS_SECTION);
		}
		return settings;
	}

	@Override
	public void addPages() {
		importPage = new TaskDataImportWizardPage();
		importPage.setWizard(this);
		addPage(importPage);
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// no initialization needed
	}

	@Override
	public boolean canFinish() {
		return importPage.isPageComplete();
	}

	/**
	 * Called when the user clicks finish. Saves the task data. Waits until all
	 * overwrite decisions have been made before starting to save files. If any
	 * overwrite is canceled, no files are saved and the user must adjust the
	 * dialog.
	 */
	@Override
	public boolean performFinish() {

		TasksUiPlugin.getTaskListManager().deactivateTask(
				TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask());

		File sourceDirFile = null;
		File sourceZipFile = null;
		File sourceTaskListFile = null;
		File sourceRepositoriesFile = null;
		File sourceActivationHistoryFile = null;
		List<File> contextFiles = new ArrayList<File>();
		List<String> zipFilesToExtract = new ArrayList<String>();
		boolean overwrite = importPage.overwrite();
		boolean zip = importPage.zip();

		if (zip) {

			String sourceZip = importPage.getSourceZipFile();
			sourceZipFile = new File(sourceZip);

			if (!sourceZipFile.exists()) {
				MessageDialog
						.openError(getShell(), "File not found", sourceZipFile.toString() + " could not be found.");
				return false;
			}

			Enumeration<? extends ZipEntry> entries;
			ZipFile zipFile;

			try {
				zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
				entries = zipFile.entries();
				while (entries.hasMoreElements()) {
					ZipEntry entry = entries.nextElement();

					if (entry.isDirectory()) {
						// ignore directories (shouldn't be any)
						continue;
					}
					if (!importPage.importTaskList() && entry.getName().endsWith(TasksUiPlugin.OLD_TASK_LIST_FILE)) {
						continue;
					}

					if (!importPage.importActivationHistory()
							&& entry.getName().endsWith(
									MylarContextManager.CONTEXT_HISTORY_FILE_NAME
											+ MylarContextManager.CONTEXT_FILE_EXTENSION_OLD)) {
						continue;
					}
					if (!importPage.importTaskContexts()
							&& entry.getName()
									.matches(".*-\\d*" + MylarContextManager.CONTEXT_FILE_EXTENSION_OLD + "$")) {
						continue;
					}

					File destContextFile = new File(TasksUiPlugin.getDefault().getDataDirectory() + File.separator
							+ entry.getName());

					if (!overwrite && destContextFile.exists()) {
						if (MessageDialog.openConfirm(getShell(), "File exists!", "Overwrite existing file?\n"
								+ destContextFile.getName())) {
							zipFilesToExtract.add(entry.toString());
						} else {
							// no overwrite
						}
					} else {
						zipFilesToExtract.add(entry.toString());
					}

				}

			} catch (IOException e) {
				MylarStatusHandler.fail(e, "Could not import files", true);
			}

		} else {
			// Get file paths to check for existence
			String sourceDir = importPage.getSourceDirectory();
			sourceDirFile = new File(sourceDir);
			if (!sourceDirFile.exists() || !sourceDirFile.isDirectory()) {
				MessageDialog.openError(getShell(), "Source location not found",
						"Resource could not be found or is not a folder.");
				return false;
			}

			// make sure selected files for import are there
			sourceTaskListFile = new File(sourceDir + File.separator + TasksUiPlugin.OLD_TASK_LIST_FILE);
			sourceRepositoriesFile = new File(sourceDir + File.separator + TaskRepositoryManager.OLD_REPOSITORIES_FILE);
			sourceActivationHistoryFile = new File(sourceDir + File.separator
					+ MylarContextManager.OLD_CONTEXT_HISTORY_FILE_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION_OLD);

			File[] children = sourceDirFile.listFiles();
			for (int i = 0; i < children.length; i++) {
				if (children[i].getAbsolutePath().matches(
						".*-\\d*" + MylarContextManager.CONTEXT_FILE_EXTENSION_OLD + "$")) {

					File destContextFile = new File(TasksUiPlugin.getDefault().getDataDirectory() + File.separator
							+ children[i].getName());

					if (!overwrite && destContextFile.exists()) {
						if (MessageDialog.openConfirm(getShell(), "Context exists!",
								"Overwrite existing task context?\n" + destContextFile.getName())) {
							contextFiles.add(children[i]);
						} else {
							// no overwrite
						}
					} else {
						contextFiles.add(children[i]);
					}
				}

			}

			if (importPage.importTaskList() && !sourceTaskListFile.exists()) {
				MessageDialog.openError(getShell(), "File not found", sourceTaskListFile.toString() + " not found.");
				return false;
			} else if (importPage.importActivationHistory() && !sourceActivationHistoryFile.exists()) {
				MessageDialog.openError(getShell(), "File not found", sourceActivationHistoryFile.toString()
						+ " not found.");
				return false;
			}

		}

		FileCopyJob job = new FileCopyJob(sourceDirFile, sourceZipFile, sourceTaskListFile, sourceRepositoriesFile,
				sourceActivationHistoryFile, contextFiles, zipFilesToExtract);

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

		try {
			service.run(true, false, job);
		} catch (InvocationTargetException e) {
			MylarStatusHandler.fail(e, "Could not import files", true);
		} catch (InterruptedException e) {
			MylarStatusHandler.fail(e, "Could not import files", true);
		}

		importPage.saveSettings();
		return true;
	}

	/** Job that performs the file copying and zipping */
	class FileCopyJob implements IRunnableWithProgress {

		private static final String JOB_LABEL = "Importing Data";

		private File sourceZipFile = null;

		private File sourceTaskListFile = null;

		private File sourceActivationHistoryFile = null;

		private File sourceRepositoriesFile = null;

		private boolean zip;

		private boolean importTaskList;

		private boolean importActivationHistory;

		private boolean importTaskContexts;

		private List<File> sourceContextFiles;

		private List<String> zipFilesToExtract;

		public FileCopyJob(File sourceFolder, File sourceZipFile, File sourceTaskListFile, File sourceRepositoriesFile,
				File sourceActivationHistoryFile, List<File> contextFiles, List<String> zipFiles) {

			this.sourceZipFile = sourceZipFile;
			this.sourceTaskListFile = sourceTaskListFile;
			this.sourceRepositoriesFile = sourceRepositoriesFile;
			this.sourceActivationHistoryFile = sourceActivationHistoryFile;
			this.sourceContextFiles = contextFiles;
			this.zipFilesToExtract = zipFiles;

			// Get parameters here to avoid accessing the UI thread
			this.zip = importPage.zip();
			this.importTaskList = importPage.importTaskList();
			this.importActivationHistory = importPage.importActivationHistory();
			this.importTaskContexts = importPage.importTaskContexts();

		}

		public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

			if (zip) {
				monitor.beginTask(JOB_LABEL, zipFilesToExtract.size() + 2);
				//ZipFile zipFile;

				try {
					//zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
					ZipFileUtil.unzipFiles(sourceZipFile, TasksUiPlugin.getDefault().getDataDirectory());
//					for (String zipFileStr : zipFilesToExtract) {
//						ZipEntry entry = zipFile.getEntry(zipFileStr);
//						if (entry == null) {
//							MylarStatusHandler.fail(new Exception("Import Exception"),
//									"Problem occured extracting from zip file.", true);
//							return;
//						}
//
//						File destinationFile = new File(TasksUiPlugin.getDefault().getDataDirectory() + File.separator
//								+ entry.getName());
//						if (destinationFile.exists()) {
//							destinationFile.delete();
//						}
//
//						copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(
//								destinationFile)));
//						monitor.worked(1);
//
//					}
					//zipFile.close();
				} catch (IOException ioe) {
					MylarStatusHandler.fail(new Exception("Import Exception"),
							"Problem occured extracting from zip file.", true);
					return;
				}
				readTaskListData();
				monitor.done();
				return;
			}

			int jobSize = 1;
			if (importTaskList)
				jobSize++;
			if (importActivationHistory)
				jobSize++;
			if (importTaskContexts)
				jobSize += sourceContextFiles.size();
			monitor.beginTask(JOB_LABEL, jobSize);

			if (true) {
				String destRepositoriesPath = TasksUiPlugin.getDefault().getDataDirectory() + File.separator
						+ TaskRepositoryManager.OLD_REPOSITORIES_FILE;
				File destRepositoriesFile = new File(destRepositoriesPath);

				if (destRepositoriesFile.exists()) {
					destRepositoriesFile.delete();
				}

				if (!copy(sourceRepositoriesFile, destRepositoriesFile)) {
					MylarStatusHandler.fail(new Exception("Import Exception"), "Could not import repositories file.",
							true);
				}
				monitor.worked(1);
			}

			if (importTaskList) {
				String destTaskListPath = TasksUiPlugin.getDefault().getDataDirectory() + File.separator
						+ TasksUiPlugin.OLD_TASK_LIST_FILE;
				File destTaskListFile = new File(destTaskListPath);

				if (destTaskListFile.exists()) {
					destTaskListFile.delete();
				}

				if (!copy(sourceTaskListFile, destTaskListFile)) {
					MylarStatusHandler
							.fail(new Exception("Import Exception"), "Could not import task list file.", true);
				}
				monitor.worked(1);

			}

			if (importActivationHistory) {
				try {
					File destActivationHistoryFile = new File(TasksUiPlugin.getDefault().getDataDirectory()
							+ File.separator + MylarContextManager.OLD_CONTEXT_HISTORY_FILE_NAME
							+ MylarContextManager.CONTEXT_FILE_EXTENSION_OLD);

					if (destActivationHistoryFile.exists()) {
						destActivationHistoryFile.delete();
					}

					copy(sourceActivationHistoryFile, destActivationHistoryFile);
					monitor.worked(1);

				} catch (RuntimeException e) {
					MylarStatusHandler.fail(e, "Could not import activity history context file", true);
				}
			}

			if (importTaskContexts) {
				boolean errorDisplayed = false;
				for (File sourceContextFile : sourceContextFiles) {

					File destContextFile = new File(TasksUiPlugin.getDefault().getDataDirectory() + File.separator
							+ sourceContextFile.getName());

					if (destContextFile.exists()) {
						destContextFile.delete();
					}

					if (!copy(sourceContextFile, destContextFile) && !errorDisplayed) {
						MylarStatusHandler.fail(new Exception("Import Exception: " + sourceContextFile.getPath()
								+ " -> " + destContextFile.getPath()),
								"Could not import one or more task context files.", true);
						errorDisplayed = true;
					}
					monitor.worked(1);
				}
			}
			readTaskListData();
			monitor.done();
		}
	}

	/** Returns all tasks in the task list root or a category in the task list */
	protected List<ITask> getAllTasks() {
		List<ITask> allTasks = new ArrayList<ITask>();
		TaskList taskList = TasksUiPlugin.getTaskListManager().getTaskList();

		allTasks.addAll(taskList.getRootTasks());

		for (AbstractTaskContainer category : taskList.getCategories()) {
			allTasks.addAll(category.getChildren());
		}

		return allTasks;
	}

	private boolean copy(File src, File dst) {

		try {
			InputStream in = new FileInputStream(src);
			OutputStream out = new FileOutputStream(dst);
			return copyInputStream(in, new BufferedOutputStream(out));
		} catch (FileNotFoundException e) {
			return false;
		}

	}

	private boolean copyInputStream(InputStream inputStream, BufferedOutputStream stream) {
		try {
			InputStream in = inputStream;
			OutputStream out = stream;

			// Transfer bytes from in to out
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			return true;
		} catch (IOException ioe) {
			return false;
		}
	}

	private void readTaskListData() {
		PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
			public void run() {
				TasksUiPlugin.getDefault().reloadDataDirectory(true);
			}
		});
	}

}

Back to the top