Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 445898e6ddc04413ab090e6ec84837fe9fd3a9a9 (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
/*******************************************************************************
 * Copyright (c) 2000, 2017 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.team.internal.ui;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.IProjectSetSerializer;
import org.eclipse.team.core.ProjectSetCapability;
import org.eclipse.team.core.RepositoryProviderType;
import org.eclipse.team.core.Team;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.core.TeamPlugin;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.XMLMemento;

public class ProjectSetImporter {
	/**
	 * Imports a psf file based on a file content. This may be used when psf
	 * file is imported from any other location that local filesystem.
	 *
	 * @param psfContents
	 *            the content of the psf file.
	 * @param filename
	 *            the name of the source file. This is included in case the
	 *            provider needs to deduce relative paths
	 * @param shell
	 * @param monitor
	 * @return list of new projects
	 * @throws InvocationTargetException
	 */
	public static IProject[] importProjectSetFromString(String psfContents,
			String filename, Shell shell, IProgressMonitor monitor)
			throws InvocationTargetException {
		XMLMemento xmlMemento = stringToXMLMemento(psfContents);
		return importProjectSet(xmlMemento, filename, shell, monitor);
	}

	/**
	 * Imports a psf file.
	 *
	 * @param filename
	 * @param shell
	 * @param monitor
	 * @return list of new projects
	 * @throws InvocationTargetException
	 */
	public static IProject[] importProjectSet(String filename, Shell shell,
			IProgressMonitor monitor) throws InvocationTargetException {
		XMLMemento xmlMemento = filenameToXMLMemento(filename);
		return importProjectSet(xmlMemento, filename, shell, monitor);
	}

	private static IProject[] importProjectSet(XMLMemento xmlMemento,
			String filename, Shell shell, IProgressMonitor monitor)
			throws InvocationTargetException {
		try {
			String version = xmlMemento.getString("version"); //$NON-NLS-1$

			List<IProject> newProjects = new ArrayList<>();
			if (version.equals("1.0")){ //$NON-NLS-1$
				IProjectSetSerializer serializer = Team.getProjectSetSerializer("versionOneSerializer"); //$NON-NLS-1$
				if (serializer != null) {
					IProject[] projects = serializer.addToWorkspace(new String[0], filename, shell, monitor);
					if (projects != null)
						newProjects.addAll(Arrays.asList(projects));
				}
			} else {
				UIProjectSetSerializationContext context = new UIProjectSetSerializationContext(shell, filename);
				List<TeamException> errors = new ArrayList<TeamException>();
				IMemento[] providers = xmlMemento.getChildren("provider"); //$NON-NLS-1$
				for (IMemento provider : providers) {
					ArrayList<String> referenceStrings= new ArrayList<>();
					IMemento[] projects = provider.getChildren("project"); //$NON-NLS-1$
					for (IMemento project : projects) {
						referenceStrings.add(project.getString("reference")); //$NON-NLS-1$
					}
					try {
						String id = provider.getString("id"); //$NON-NLS-1$
						TeamCapabilityHelper.getInstance().processRepositoryId(id,
								PlatformUI.getWorkbench().getActivitySupport());
						RepositoryProviderType providerType = RepositoryProviderType.getProviderType(id);
						if (providerType == null) {
							// The provider type is absent. Perhaps there is another provider that can import this type
							providerType = TeamPlugin.getAliasType(id);
						}
						if (providerType == null) {
							throw new TeamException(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_0, new String[] { id }), null));
						}
						ProjectSetCapability serializer = providerType.getProjectSetCapability();
						ProjectSetCapability.ensureBackwardsCompatible(providerType, serializer);
						if (serializer != null) {
							IProject[] allProjects = serializer.addToWorkspace(referenceStrings.toArray(new String[referenceStrings.size()]), context, monitor);
							if (allProjects != null)
								newProjects.addAll(Arrays.asList(allProjects));
						}
					} catch (TeamException e) {
						errors.add(e);
					}
				}
				if (!errors.isEmpty()) {
					TeamException[] exceptions= errors.toArray(new TeamException[errors.size()]);
					IStatus[] status= new IStatus[exceptions.length];
					for (int i= 0; i < exceptions.length; i++) {
						status[i]= exceptions[i].getStatus();
					}
					throw new TeamException(new MultiStatus(TeamUIPlugin.ID, 0, status, TeamUIMessages.ProjectSetImportWizard_1, null));
				}

				//try working sets
				IMemento[] sets = xmlMemento.getChildren("workingSets"); //$NON-NLS-1$
				IWorkingSetManager wsManager = PlatformUI.getWorkbench().getWorkingSetManager();
				boolean replaceAll = false;
				boolean mergeAll = false;
				boolean skipAll = false;

				for (IMemento set : sets) {
					IWorkingSet newWs = wsManager.createWorkingSet(set);
					if (newWs != null) {
						IWorkingSet oldWs = wsManager.getWorkingSet(newWs
								.getName());
						if (oldWs == null) {
							wsManager.addWorkingSet(newWs);
						} else if (replaceAll) {
							replaceWorkingSet(wsManager, newWs, oldWs);
						} else if (mergeAll) {
							mergeWorkingSets(newWs, oldWs);
						} else if (!skipAll) {
							// a working set with the same name has been found
							String title = TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_title;
							String msg = NLS
									.bind(
											TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_message,
											newWs.getName());
							String[] buttons = new String[] {
									TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_replace,
									TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_merge,
									TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_skip,
									IDialogConstants.CANCEL_LABEL };
							final AdviceDialog dialog = new AdviceDialog(
									shell, title, null, msg,
									MessageDialog.QUESTION, buttons, 0);

							shell.getDisplay().syncExec(() -> dialog.open());

							switch (dialog.getReturnCode()) {
							case 0: // overwrite
								replaceWorkingSet(wsManager, newWs, oldWs);
								replaceAll = dialog.applyToAll;
								break;
							case 1: // combine
								mergeWorkingSets(newWs, oldWs);
								mergeAll = dialog.applyToAll;
								break;
							case 2: // skip
								skipAll = dialog.applyToAll;
								break;
							case 3: // cancel
							default:
								throw new OperationCanceledException();
							}
						}
					}
				}
			}

			return newProjects.toArray(new IProject[newProjects.size()]);
		} catch (TeamException e) {
			throw new InvocationTargetException(e);
		}
	}

	private static XMLMemento filenameToXMLMemento(String filename) throws InvocationTargetException {
		InputStreamReader reader = null;
		try {
			reader = new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8);
			return XMLMemento.createReadRoot(reader);
		} catch (FileNotFoundException e) {
			throw new InvocationTargetException(e);
		} catch (WorkbenchException e) {
			throw new InvocationTargetException(e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new InvocationTargetException(e);
				}
			}
		}
	}

	private static XMLMemento stringToXMLMemento(String stringContents)
			throws InvocationTargetException {
		try (StringReader reader = new StringReader(stringContents)) {
			return XMLMemento.createReadRoot(reader);
		} catch (WorkbenchException e) {
			throw new InvocationTargetException(e);
		}
	}

	/**
	 * Check if given file is a valid psf file
	 *
	 * @param filename
	 * @return <code>true</code> is file is a valid psf file
	 */
	public static boolean isValidProjectSetFile(String filename) {
		try {
			return filenameToXMLMemento(filename).getString("version") != null; //$NON-NLS-1$
		} catch (InvocationTargetException e) {
			return false;
		}
	}

	/**
	 * Check if given string is a valid project set
	 *
	 * @param psfContent
	 * @return <code>true</code> if psfContent is a valid project set
	 */
	public static boolean isValidProjectSetString(String psfContent) {
		if (psfContent == null) {
			return false;
		}
		try {
			return stringToXMLMemento(psfContent).getString("version") != null; //$NON-NLS-1$
		} catch (InvocationTargetException e) {
			return false;
		}
	}

	private static void mergeWorkingSets(IWorkingSet newWs, IWorkingSet oldWs) {
		IAdaptable[] oldElements = oldWs.getElements();
		IAdaptable[] newElements = newWs.getElements();

		Set<IAdaptable> combinedElements = new HashSet<IAdaptable>();
		combinedElements.addAll(Arrays.asList(oldElements));
		combinedElements.addAll(Arrays.asList(newElements));

		oldWs.setElements(combinedElements.toArray(new IAdaptable[0]));
	}

	private static void replaceWorkingSet(IWorkingSetManager wsManager, IWorkingSet newWs, IWorkingSet oldWs) {
		if (oldWs != null)
			wsManager.removeWorkingSet(oldWs);
		wsManager.addWorkingSet(newWs);
	}

	private static class AdviceDialog extends MessageDialog {
		boolean applyToAll;
		public AdviceDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex) {
			super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex);
		}
		@Override
		protected Control createCustomArea(Composite parent) {
			final Button checkBox = new Button(parent, SWT.CHECK);
			checkBox.setText(TeamUIMessages.ImportProjectSetDialog_duplicatedWorkingSet_applyToAll);
			checkBox.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					applyToAll = checkBox.getSelection();
				}
			});
			return checkBox;
		}
	}

}

Back to the top