Skip to main content
summaryrefslogtreecommitdiffstats
blob: fa7a23288ec9bdb1eb36507f7831bad3cbacf3dc (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
/*******************************************************************************
 * Copyright (c) 2001, 2004 IBM Corporation 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:
 * IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.wst.validation.internal;

import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jem.util.UIContextDetermination;
import org.eclipse.jem.util.logger.LogEntry;
import org.eclipse.jem.util.logger.proxy.Logger;
import org.eclipse.wst.validation.internal.operations.IWorkbenchContext;
import org.eclipse.wst.validation.internal.plugin.ValidationPlugin;

/**
 * This class manages resource change events for the validation framework.
 */
public class EventManager implements IResourceChangeListener {
	private static EventManager _inst = null;
	private boolean _shutdown = false; // false means that eclipse is not shutting down, and true
	// means that it is shutting down. Used in two methods:
	// shutdown(),and resourceChanged(IResourceChangeEvent)
	private IResourceDeltaVisitor _postAutoBuildVisitor = null;
	private boolean _isActive = false; // has the registry been read?

	private EventManager() {
		super();
	}

	public static EventManager getManager() {
		if (_inst == null) {
			_inst = new EventManager();
		}
		return _inst;
	}

	public void opening(IProject project) {
		if (project == null || !ValidationPlugin.isActivated()) {
			return;
		}

		// When the project is opened, check for any orphaned tasks
		// or tasks whose owners need to be updated.
		ConfigurationManager.getManager().opening(project);
	}

	public void closing(IProject project) {
		if (project == null || !ValidationPlugin.isActivated()) {
			return;
		}

		try {
			boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
			// If it's not migrated, then it hasn't been loaded, and we don't want to load the
			// validator and its prerequisite plugins until they're needed.
			if (isMigrated) {
				ValidatorMetaData[] vmds = ConfigurationManager.getManager().getProjectConfiguration(project).getValidators();
				for (int i = 0; i < vmds.length; i++) {
					ValidatorMetaData vmd = vmds[i];

					if (!vmd.isActive()) {
						// If this validator has not been activated, or if it has been shut down,
						// don't activate it again.
						continue;
					}

					IWorkbenchContext helper = null;
					try {
						helper = vmd.getHelper(project);
						helper.closing();
					} catch (InstantiationException exc) {
						// Remove the vmd from the reader's list
						ValidationRegistryReader.getReader().disableValidator(vmd);

						// Log the reason for the disabled validator
						Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
						if (logger.isLoggingLevel(Level.SEVERE)) {
							LogEntry entry = ValidationPlugin.getLogEntry();
							entry.setSourceID("EventManager::closing(IProject)"); //$NON-NLS-1$
							entry.setTargetException(exc);
							logger.write(Level.SEVERE, entry);
						}

						continue;
					} catch (Throwable exc) {
						// If there is a problem with this particular helper, log the error and
						// continue
						// with the next validator.
						Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
						if (logger.isLoggingLevel(Level.SEVERE)) {
							LogEntry entry = ValidationPlugin.getLogEntry();
							entry.setSourceID("EventManager::closing(IProject)"); //$NON-NLS-1$
							entry.setTargetException(exc);
							logger.write(Level.SEVERE, entry);
						}
						continue;
					}
				}

				ConfigurationManager.getManager().closing(project);
			}
		} catch (InvocationTargetException exc) {
			Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
			if (logger.isLoggingLevel(Level.SEVERE)) {
				LogEntry entry = ValidationPlugin.getLogEntry();
				entry.setSourceIdentifier("EventManager::closing(" + project.getName() + ")"); //$NON-NLS-1$  //$NON-NLS-2$
				entry.setTargetException(exc);
				logger.write(Level.SEVERE, entry);

				if (exc.getTargetException() != null) {
					entry.setTargetException(exc);
					logger.write(Level.SEVERE, entry);
				}
			}
		}
	}

	public void deleting(IProject project) {
		if (project == null) {
			return;
		}

		try {
			boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
			// If it's not migrated, then it hasn't been loaded, and we don't want to load the
			// validator and its prerequisite plugins until they're needed.
			if (isMigrated) {
				ValidatorMetaData[] vmds = ConfigurationManager.getManager().getProjectConfiguration(project).getValidators();
				for (int i = 0; i < vmds.length; i++) {
					ValidatorMetaData vmd = vmds[i];

					if (!vmd.isActive()) {
						// If this validator has not been activated, or if it has been shut down,
						// don't activate it again.
						continue;
					}

					IWorkbenchContext helper = null;
					try {
						helper = vmd.getHelper(project);
						helper.deleting();
					} catch (InstantiationException exc) {
						// Remove the vmd from the reader's list
						ValidationRegistryReader.getReader().disableValidator(vmd);

						// Log the reason for the disabled validator
						Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
						if (logger.isLoggingLevel(Level.SEVERE)) {
							LogEntry entry = ValidationPlugin.getLogEntry();
							entry.setSourceID("EventManager::deleting(IProject)"); //$NON-NLS-1$
							entry.setTargetException(exc);
							logger.write(Level.SEVERE, entry);
						}

						continue;
					} catch (Throwable exc) {
						// If there is a problem with this particular helper, log the error and
						// continue
						// with the next validator.
						Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
						if (logger.isLoggingLevel(Level.SEVERE)) {
							LogEntry entry = ValidationPlugin.getLogEntry();
							entry.setSourceID("EventManager::deleting(IProject)"); //$NON-NLS-1$
							entry.setTargetException(exc);
							logger.write(Level.SEVERE, entry);
						}
						continue;
					}
				}

				ConfigurationManager.getManager().deleting(project);
			}
		} catch (InvocationTargetException exc) {
			Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
			if (logger.isLoggingLevel(Level.SEVERE)) {
				LogEntry entry = ValidationPlugin.getLogEntry();
				entry.setSourceIdentifier("EventManager::deleting(" + project.getName() + ")"); //$NON-NLS-1$  //$NON-NLS-2$
				entry.setTargetException(exc);
				logger.write(Level.SEVERE, entry);

				if (exc.getTargetException() != null) {
					entry.setTargetException(exc);
					logger.write(Level.SEVERE, entry);
				}
			}
		}
	}

	/**
	 * If a project's description changes, The project may have changed its nature. Update the cache
	 * to reflect the new natures. The project could be opening. Migrate.
	 */
	private void postAutoChange(IResourceDelta delta) {
		if (_postAutoBuildVisitor == null) {
			_postAutoBuildVisitor = new IResourceDeltaVisitor() {
				public boolean visit(IResourceDelta subdelta) throws CoreException {
					if (subdelta == null)
						return true;

					IResource resource = subdelta.getResource();
					if (resource instanceof IProject) {
						IProject project = (IProject) resource;
						if ((subdelta.getFlags() & IResourceDelta.DESCRIPTION) == IResourceDelta.DESCRIPTION) {
							try {
								ConfigurationManager.getManager().resetProjectNature(project); // flush
								// existing
								// "enabled
								// validator"
								// settings
								// and
								// reset
								// to
								// default
							} catch (InvocationTargetException exc) {
								Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
								if (logger.isLoggingLevel(Level.SEVERE)) {
									LogEntry entry = ValidationPlugin.getLogEntry();
									entry.setSourceIdentifier("EventManager::postAutoChange"); //$NON-NLS-1$
									entry.setTargetException(exc);
									logger.write(Level.SEVERE, entry);

									if (exc.getTargetException() != null) {
										entry.setTargetException(exc);
										logger.write(Level.SEVERE, entry);
									}
								}
							}
							return false;
						}

						if ((subdelta.getFlags() & IResourceDelta.OPEN) == IResourceDelta.OPEN) {
							if (project.isOpen()) {
								// Project was just opened. If project.isOpen() had returned false,
								// project
								// would just have been closed.
								opening(project);
							}
							// closing is called by PRE_CLOSE in resourceChanged
							//							else {
							//								closing(project);
							//							}
						}
					}

					return true;
				}
			};
		}

		try {
			delta.accept(_postAutoBuildVisitor, true);
		} catch (CoreException exc) {
			exc.printStackTrace();
		}
	}

	/**
	 * Notifies this manager that some resource changes have happened on the platform. If the change
	 * is a project deletion, that project should be removed from the cache.
	 * 
	 * @see IResourceDelta
	 * @see IResource
	 */
	public void resourceChanged(IResourceChangeEvent event) {
		if (_shutdown && (!isActive())) {
			// If we're shutting down, and nothing has been activated, don't need to
			// do anything.
			return;
		}

		/*
		 * StringBuffer buffer = new StringBuffer(); buffer.append("IResourceChangeEvent type = ");
		 * buffer.append(event.getType()); buffer.append(", resource = ");
		 * buffer.append(event.getResource()); buffer.append(", source = ");
		 * buffer.append(event.getSource()); buffer.append(", delta = ");
		 * buffer.append(event.getDelta()); System.out.println(buffer.toString());
		 */

		if (event.getSource() instanceof IWorkspace) {
			if ((event.getType() == IResourceChangeEvent.PRE_DELETE) && (event.getResource() instanceof IProject)) {
				deleting((IProject) event.getResource());
			} else if ((event.getType() == IResourceChangeEvent.PRE_CLOSE) && (event.getResource() instanceof IProject)) {
				closing((IProject) event.getResource());
			} else if (event.getType() == IResourceChangeEvent.POST_BUILD) {
				postAutoChange(event.getDelta());
			}

		}
	}

	/**
	 * Notifies this manager that the ValidationPlugin is shutting down. (Usually implies that
	 * either the plugin could not load, or that the workbench is shutting down.)
	 * 
	 * The manager will then notify all active helpers of the shutdown, so that they may perform any
	 * last-minute writes to disk, cleanup, etc.
	 */
	public void shutdown() {
		try {
			_shutdown = true; // resourceChanged(IResourceChangeEvent) needs to know when a shutdown
			// has started.

			/*
			 * if( !isHeadless() && ConfigurationManager.getManager().isGlobalMigrated()) {
			 * GlobalConfiguration gp = ConfigurationManager.getManager().getGlobalConfiguration();
			 * gp.store(); // First, see if any validators are loaded. If none are, there is nothing
			 * to // clean up. if(gp.numberOfValidators() == 0) { return; } }
			 */

			// If the validators are loaded, then for every project in the workbench,
			// we must see if it has been loaded. If it has, every enabled IWorkbenchContext
			// must be called to clean up. If the project hasn't been loaded, then no
			// IWorkbenchContext built anything, and there's nothing to clean up.
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			IWorkspaceRoot workspaceRoot = workspace.getRoot();
			IProject[] projects = workspaceRoot.getProjects();
			ProjectConfiguration prjp = null;
			IProject project = null;
			for (int i = 0; i < projects.length; i++) {
				project = projects[i];
				if (!project.isOpen()) {
					// If the project isn't opened, there's nothing to clean up.
					// If the project was opened, it would have been migrated, and there's something
					// to clean up.
					continue;
				}

				try {
					boolean isMigrated = ConfigurationManager.getManager().isMigrated(project);
					// If it's not migrated, then it hasn't been loaded, and we don't want to load
					// the
					// validator and its prerequisite plugins until they're needed.
					if (isMigrated) {
						prjp = ConfigurationManager.getManager().getProjectConfiguration(project);
						prjp.store();

						ValidatorMetaData[] vmdList = prjp.getEnabledValidators();
						// if vmdList is null, IProject has never been loaded, so nothing to clean
						// up
						if (vmdList != null) {
							for (int j = 0; j < vmdList.length; j++) {
								ValidatorMetaData vmd = vmdList[j];

								if (!vmd.isActive()) {
									// If this validator has not been activated, or if it has been
									// shut down, don't activate it again.
									continue;
								}

								IWorkbenchContext helper = vmd.getHelper(project);
								if (helper != null) {
									try {
										helper.shutdown();
									} catch (Throwable exc) {
										// Since we're shutting down, ignore the exception.
									}
								}
							}
						}
					}
				} catch (InvocationTargetException exc) {
					Logger logger = ValidationPlugin.getPlugin().getMsgLogger();
					if (logger.isLoggingLevel(Level.SEVERE)) {
						LogEntry entry = ValidationPlugin.getLogEntry();
						entry.setSourceIdentifier("EventManager::shutdown(" + project.getName() + ")"); //$NON-NLS-1$  //$NON-NLS-2$
						entry.setTargetException(exc);
						logger.write(Level.SEVERE, entry);

						if (exc.getTargetException() != null) {
							entry.setTargetException(exc);
							logger.write(Level.SEVERE, entry);
						}
					}
				}
			}
		} catch (Throwable exc) {
			// Since we're shutting down, ignore the exception.
		}
	}

	public boolean isActive() {
		// Have to use this convoluted technique for the shutdown problem.
		// i.e., when eclipse is shut down, if validation plugin hasn't been loaded,
		// the EventManager is activated for the first time, and it
		// sends many exceptions to the .log. At first, I wrote a
		// static method on ValidationRegistryReader, which returned true
		// if the registry had been read, and false otherwise. However,
		// that didn't solve the exception problem, because eclipse's
		// class loader failed to load the ValidationRegistryReader class.
		//
		// The fix is to keep all shutdown mechanisms in this class.
		// Track everything in here.
		return _isActive;
	}

	/**
	 * This method should only be called by the ValidationRegistryReader once the registry has been
	 * read.
	 */
	public void setActive(boolean b) {
		_isActive = b;
	}

	/**
	 * This method should be used to determine if the workbench is running in UI or Headless
	 */
	public static boolean isHeadless() {
		boolean ret = UIContextDetermination.getCurrentContext() == UIContextDetermination.HEADLESS_CONTEXT;
		return ret;
		//return UIContextDetermination.getCurrentContext() ==
		// UIContextDetermination.HEADLESS_CONTEXT;
	}
}

Back to the top