Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: be980aab70dafb7ea2de42df274b6b2d7d9913f9 (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
/*****************************************************************************
 * Copyright (c) 2016 CEA LIST and others.
 *
 * All rights reserved. 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:
 *   CEA LIST - Initial API and implementation
 *
 *****************************************************************************/

package org.eclipse.papyrus.releng.tools.internal.popup.actions;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.cbi.targetplatform.pde.Converter;
import org.eclipse.cbi.targetplatform.ui.internal.TargetplatformActivator;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.core.runtime.jobs.JobGroup;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.papyrus.releng.tools.internal.Activator;
import org.eclipse.papyrus.releng.tools.internal.Messages;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import com.google.inject.Injector;


/**
 * A global handler, enabled on a set of IResources (Project/Folder/File), which recursively:
 *
 * - Finds all *.tpd files
 * - Updates them from the selected Simrel/B3 model
 * - Generates all *.target files
 * - Generates an Eclipse-Server version for each *.target file (In an eclipse/*.target folder)
 *
 * The Eclipse-Server version of the target is similar to the default one, except it uses
 * the file:/ protocol instead of http:// for all access to download.eclipse.org,
 * for improved performances when building on Eclipse Servers
 *
 * @author Camille Letavernier
 *
 */
public class GenerateTargetsHandler extends AbstractHandler {

	/**
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 *
	 * @param event
	 * @return
	 * @throws ExecutionException
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection sSelection = (IStructuredSelection) selection;
			Iterator<?> iterator = sSelection.iterator();

			List<IFile> tpdFiles = new ArrayList<>();

			try {

				while (iterator.hasNext()) {
					Object next = iterator.next();

					if (next instanceof IResource) {
						collectTPDFiles((IResource) next, tpdFiles);
					}
				}

				final Shell activeShell = HandlerUtil.getActiveShell(event);

				if (!tpdFiles.isEmpty()) {
					new UpdateDependencies().updateDependencies(tpdFiles, activeShell); // Update all TPD Files from Simrel

					String jobTitle = String.format(Messages.GenerateTargetsHandler_GenerateTargetFile, tpdFiles.size());
					Job topLevelJob = new Job(jobTitle) {
						/**
						 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
						 *
						 * @param monitor
						 * @return
						 */
						@Override
						protected IStatus run(IProgressMonitor monitor) {
							int maxThreads = 2; // Multi-threading is not really relevant, most time is spent in downloading artifacts

							JobGroup tpdConverters = new JobGroup(Messages.GenerateTargetsHandler_GenerateTarget, maxThreads, tpdFiles.size());
							for (IFile tpdFile : tpdFiles) {
								generate(tpdFile, tpdConverters); // Generate *.target files
							}

							try {
								tpdConverters.join(0, monitor);
							} catch (InterruptedException e) {
								return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.GenerateTargetsHandler_UnexpectedException, e);
							}

							return tpdConverters.getResult();
						}
					};

					topLevelJob.setUser(true);
					topLevelJob.addJobChangeListener(new JobChangeAdapter() {
						/**
						 * @see org.eclipse.core.runtime.jobs.JobChangeAdapter#done(org.eclipse.core.runtime.jobs.IJobChangeEvent)
						 *
						 * @param event
						 */
						@Override
						public void done(IJobChangeEvent event) {
							if (Display.getCurrent() != null) {
								done(event.getResult());
							} else {
								Display.getDefault().asyncExec(() -> {
									done(event.getResult());
								});
							}
						}

						void done(IStatus status) {
							String title = Messages.GenerateTargetsHandler_GenerateTarget;
							switch (status.getCode()) {
							case IStatus.OK:
							case IStatus.INFO:
								MessageDialog.openInformation(activeShell, title, Messages.GenerateTargetsHandler_OperationComplete);
								break;
							case IStatus.CANCEL:
								MessageDialog.openInformation(activeShell, title, Messages.GenerateTargetsHandler_OperationCanceled);
								break;
							case IStatus.ERROR:
								MessageDialog.openError(activeShell, title, Messages.GenerateTargetsHandler_OperationCompleteWithError);
								break;
							case IStatus.WARNING:
								MessageDialog.openWarning(activeShell, title, Messages.GenerateTargetsHandler_OperationCompleteWithWarning);
								break;
							}
						}
					});
					topLevelJob.schedule();

				}
			} catch (CoreException e) {
				Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.GenerateTargetsHandler_UnexpectedException, e));
			}

		}

		return null;

	}

	/**
	 * Finds all *.tpd files, recursively, in the given IResource (IFile, IFolder, IProject...)
	 * The collected *.tpd IFiles are stored in the result List
	 *
	 * @param resource
	 * @param result
	 * @throws CoreException
	 */
	protected void collectTPDFiles(IResource resource, List<IFile> result) throws CoreException {
		if (resource instanceof IFile) {
			IFile file = (IFile) resource;
			if ("tpd".equals(file.getFileExtension())) { //$NON-NLS-1$
				result.add(file);
			}
		} else if (resource instanceof IContainer) {
			collectTPDFiles((IContainer) resource, result);
		}
	}

	/**
	 * Finds all *.tpd files, recursively, in the given IContainer (IFolder, IProject...)
	 * The collected *.tpd IFiles are stored in the result List
	 *
	 * @param resource
	 * @param result
	 * @throws CoreException
	 */
	protected void collectTPDFiles(IContainer parent, List<IFile> result) throws CoreException {
		for (IResource child : parent.members()) {
			collectTPDFiles(child, result);
		}
	}

	/**
	 * Inits a job for converting a single *.tpd file to a *.target file
	 * Also creates an Eclipse Server version of each *.target file (Using file:/ protocol instead of http://)
	 *
	 * @param file
	 *            A *.tpd IFile
	 * @param jobGroup
	 *            The job group used to managed all *.tpd to *.target conversion jobs
	 * @throws CoreException
	 */
	protected void generate(IFile file, JobGroup jobGroup) {
		// The Converter currently only supports File URIs (No platform resource)
		// URI tpdURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true);

		String filePath = file.getLocation().toFile().getAbsolutePath();
		URI tpdURI = URI.createFileURI(filePath);

		Converter converter = new Converter();

		Injector injector = TargetplatformActivator.getInstance().getInjector(TargetplatformActivator.ORG_ECLIPSE_CBI_TARGETPLATFORM_TARGETPLATFORM);
		injector.injectMembers(converter);

		Job job = new Job(Messages.GenerateTargetsHandler_GenerateTargetPlatformFor + file.getLocation().lastSegment()) {

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				Diagnostic result = converter.generateTargetDefinitionFile(tpdURI, new NullProgressMonitor());
				if (result.getSeverity() >= Diagnostic.WARNING) {
					Activator.getDefault().getLog().log(BasicDiagnostic.toIStatus(result));
				}

				try {
					file.getParent().refreshLocal(IResource.DEPTH_ONE, null);
					generateEclipseTarget(file);
				} catch (CoreException ex) {
					return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.GenerateTargetsHandler_UnexpectedException, ex);
				}

				return BasicDiagnostic.toIStatus(result);
			}
		};

		job.setJobGroup(jobGroup);
		job.schedule();
	}

	/**
	 * Generates an Eclipse-Server version of the *.target file for the given *.tpd file (Assuming the
	 * standard *.target file has already been generated)
	 *
	 * The Eclipse-Server version of the target is similar to the default one, except it uses
	 * the file:/ protocol instead of http:// for all access to download.eclipse.org,
	 * for improved performances when building on Eclipse Servers
	 *
	 * @param tpdFile
	 * @throws CoreException
	 */
	protected void generateEclipseTarget(IFile tpdFile) throws CoreException {
		String targetSuffix = "eclipse"; //$NON-NLS-1$

		IContainer parent = tpdFile.getParent();

		String fileName = tpdFile.getFullPath().removeFileExtension().addFileExtension("target").lastSegment(); //$NON-NLS-1$

		IFile portableTargetFile = parent.getFile(new Path(fileName));

		IFolder eclipseFolder = parent.getParent().getFolder(new Path(targetSuffix));
		if (!eclipseFolder.exists()) {
			eclipseFolder.create(true, true, new NullProgressMonitor());
		}

		IFile eclipseTargetFile = eclipseFolder.getFile(fileName.replaceAll("portable", targetSuffix)); //$NON-NLS-1$

		InputStream convertedStream = convert(portableTargetFile.getContents(), "http://download.eclipse.org/", "file:/home/data/httpd/download.eclipse.org/"); //$NON-NLS-1$ //$NON-NLS-2$
		convertedStream = convert(convertedStream, "https://download.eclipse.org/", "file:/home/data/httpd/download.eclipse.org/"); //$NON-NLS-1$ //$NON-NLS-2$

		if (eclipseTargetFile.exists()) {

			eclipseTargetFile.setContents(convertedStream, IResource.NONE, null);
		} else {
			eclipseTargetFile.create(convertedStream, true, null);
		}

		eclipseFolder.refreshLocal(IResource.DEPTH_ONE, null);
	}

	/**
	 * Returns an InputStream similar to the source stream, replacing all occurrences of the source pattern
	 * with the target pattern
	 *
	 * @param source
	 * @param sourcePattern
	 * @param targetPattern
	 * @return
	 * @throws CoreException
	 */
	protected InputStream convert(InputStream source, String sourcePattern, String targetPattern) throws CoreException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(source));

		StringBuilder builder = new StringBuilder();
		String line;

		String patternSt = sourcePattern.replaceAll("\\.", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
		Pattern pattern = Pattern.compile(patternSt);

		try {
			while ((line = reader.readLine()) != null) {
				Matcher matcher = pattern.matcher(line);
				String newLine = matcher.replaceAll(targetPattern);
				builder.append(newLine).append("\n"); //$NON-NLS-1$
			}
		} catch (IOException ex) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.GenerateTargetsHandler_UnexpectedError, ex));
		}

		ByteArrayInputStream result = new ByteArrayInputStream(builder.toString().getBytes());

		return result;
	}

}

Back to the top