Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 70a85f8616b9e4d81c5c84aff007d69a6b66a2d3 (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
/*******************************************************************************
 * Copyright (c) 2003, 2011 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.pde.internal.core;

import java.io.*;
import java.net.URL;
import java.util.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jdt.core.*;
import org.eclipse.pde.core.IBundleClasspathResolver;
import org.eclipse.pde.core.build.IBuild;
import org.eclipse.pde.core.build.IBuildEntry;
import org.eclipse.pde.core.plugin.*;
import org.eclipse.pde.internal.core.build.WorkspaceBuildModel;
import org.eclipse.pde.internal.core.project.PDEProject;

public class ClasspathHelper {

	private static final String DOT = "."; //$NON-NLS-1$
	private static final String FRAGMENT_ANNOTATION = "@fragment@"; //$NON-NLS-1$

	public static String getDevEntriesProperties(String fileName, boolean checkExcluded) {
		File file = new File(fileName);
		if (!file.exists()) {
			File directory = file.getParentFile();
			if (directory != null && (!directory.exists() || directory.isFile())) {
				directory.mkdirs();
			}
		}
		Properties properties = new Properties();
		// account for cascading workspaces
		TargetWeaver.weaveDevProperties(properties);
		IPluginModelBase[] models = PluginRegistry.getWorkspaceModels();
		for (int i = 0; i < models.length; i++) {
			String id = models[i].getPluginBase().getId();
			if (id == null)
				continue;
			String entry = writeEntry(getDevPaths(models[i], checkExcluded, null));
			if (entry.length() > 0) {
				String currentValue = (String) properties.get(id);
				if (!entry.equals(currentValue)) {
					if (currentValue != null)
						entry = currentValue.concat(",").concat(entry); //$NON-NLS-1$
					properties.put(id, entry);
				}
			}
		}
		properties.put("@ignoredot@", "true"); //$NON-NLS-1$ //$NON-NLS-2$

		FileOutputStream stream = null;
		try {
			stream = new FileOutputStream(fileName);
			properties.store(stream, ""); //$NON-NLS-1$
			stream.flush();
			return new URL("file:" + fileName).toString(); //$NON-NLS-1$
		} catch (IOException e) {
			PDECore.logException(e);
		} finally {
			try {
				if (stream != null)
					stream.close();
			} catch (IOException e) {
			}
		}
		return getDevEntries(checkExcluded);
	}

	public static String getDevEntriesProperties(String fileName, Map map) {
		File file = new File(fileName);
		if (!file.exists()) {
			File directory = file.getParentFile();
			if (directory != null && (!directory.exists() || directory.isFile())) {
				directory.mkdirs();
			}
		}
		Properties properties = new Properties();
		// account for cascading workspaces
		TargetWeaver.weaveDevProperties(properties);
		Iterator iter = map.values().iterator();
		while (iter.hasNext()) {
			IPluginModelBase model = (IPluginModelBase) iter.next();
			if (model.getUnderlyingResource() != null) {
				String entry = writeEntry(getDevPaths(model, true, map));
				if (entry.length() > 0) {
					String id = model.getPluginBase().getId();
					String currentValue = (String) properties.get(id);
					if (!entry.equals(currentValue)) {
						if (currentValue != null)
							entry = currentValue.concat(",").concat(entry); //$NON-NLS-1$
						properties.put(id, entry);
					}
				}
			}
		}
		properties.put("@ignoredot@", "true"); //$NON-NLS-1$ //$NON-NLS-2$

		FileOutputStream stream = null;
		try {
			stream = new FileOutputStream(fileName);
			properties.store(stream, ""); //$NON-NLS-1$
			stream.flush();
			return new URL("file:" + fileName).toString(); //$NON-NLS-1$
		} catch (IOException e) {
			PDECore.logException(e);
		} finally {
			try {
				if (stream != null)
					stream.close();
			} catch (IOException e) {
			}
		}
		return getDevEntries(true);
	}

	private static String getDevEntries(boolean checkExcluded) {
		IPluginModelBase[] models = PluginRegistry.getWorkspaceModels();
		ArrayList list = new ArrayList();
		for (int i = 0; i < models.length; i++) {
			String id = models[i].getPluginBase().getId();
			if (id == null || id.trim().length() == 0)
				continue;
			IPath[] paths = getDevPaths(models[i], checkExcluded, null);
			for (int j = 0; j < paths.length; j++) {
				list.add(paths[j]);
			}
		}
		String entry = writeEntry((IPath[]) list.toArray(new IPath[list.size()]));
		return entry.length() > 0 ? entry : "bin"; //$NON-NLS-1$
	}

	private static String writeEntry(IPath[] paths) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < paths.length; i++) {
			buffer.append(paths[i].toString());
			if (i < paths.length - 1)
				buffer.append(","); //$NON-NLS-1$
		}
		return buffer.toString();
	}

	// TODO remove - no longer used after bug 217870
	public static Dictionary getDevDictionary(IPluginModelBase model) {
		if (model.getUnderlyingResource() == null)
			return null;

		String id = model.getPluginBase().getId();
		if (id == null || id.trim().length() == 0)
			return null;
		IPath[] paths = getDevPaths(model, false, null);
		String entry = writeEntry(paths);
		Hashtable map = new Hashtable(2);
		map.put("@ignoredot@", "true"); //$NON-NLS-1$ //$NON-NLS-2$
		map.put(id, entry.length() > 0 ? entry : "bin"); //$NON-NLS-1$
		return map;
	}

	// creates a map whose key is a Path to the source directory/jar and the value is a Path output directory or jar.
	private static Map getClasspathMap(IProject project, boolean checkExcluded, boolean onlyJarsIfLinked, boolean absolutePaths) throws JavaModelException {
		List excluded = getFoldersToExclude(project, checkExcluded);
		IJavaProject jProject = JavaCore.create(project);
		HashMap map = new HashMap();
		IClasspathEntry[] entries = jProject.getRawClasspath();
		for (int i = 0; i < entries.length; i++) {
			// most of the paths we get will be project relative, so we need to make the paths relative
			// we will have problems adding an "absolute" path that is workspace relative
			IPath output = null, source = null;
			if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
				source = entries[i].getPath();
				output = entries[i].getOutputLocation();
				if (output == null)
					output = jProject.getOutputLocation();
			} else if (entries[i].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
				source = entries[i].getPath();
				output = entries[i].getPath();
				if (source.segmentCount() == 1)
					source = new Path(DOT);
			}
			if (output != null && !excluded.contains(output)) {
				IResource file = project.findMember(output.removeFirstSegments(1));
				// make the path either relative or absolute
				if (file != null) {
					boolean isLinked = file.isLinked(IResource.CHECK_ANCESTORS);
					if (entries[i].getEntryKind() != IClasspathEntry.CPE_SOURCE && !isLinked && onlyJarsIfLinked)
						continue;
					output = (isLinked || absolutePaths) ? file.getLocation().makeAbsolute() : output.makeRelative();
				} else
					continue;
				ArrayList list = (ArrayList) map.get(source);
				if (list == null)
					list = new ArrayList();
				list.add(output);
				map.put(source, list);
			}
		}

		// Add additional entries from contributed bundle classpath resolvers
		IBundleClasspathResolver[] resolvers = PDECore.getDefault().getClasspathContainerResolverManager().getBundleClasspathResolvers(project);
		for (int i = 0; i < resolvers.length; i++) {
			Map resolved = resolvers[i].getAdditionalClasspathEntries(jProject);
			Iterator resolvedIter = resolved.entrySet().iterator();
			while (resolvedIter.hasNext()) {
				Map.Entry resolvedEntry = (Map.Entry) resolvedIter.next();
				IPath ceSource = (IPath) resolvedEntry.getKey();
				ArrayList list = (ArrayList) map.get(ceSource);
				if (list == null) {
					list = new ArrayList();
					map.put(ceSource, list);
				}
				list.addAll((Collection) resolvedEntry.getValue());
			}
		}

		return map;
	}

	// find the corresponding paths for a library name.  Searches for source folders first, but includes any libraries on the buildpath with the same name
	private static IPath[] findLibrary(String libName, IProject project, Map classpathMap, IBuild build) {
		ArrayList paths = new ArrayList();
		IBuildEntry entry = (build != null) ? build.getEntry(IBuildEntry.JAR_PREFIX + libName) : null;
		if (entry != null) {
			String[] resources = entry.getTokens();
			for (int j = 0; j < resources.length; j++) {
				IResource res = project.findMember(resources[j]);
				if (res != null) {
					Collection list = (Collection) classpathMap.get(res.getFullPath());
					if (list != null) {
						Iterator li = list.iterator();
						while (li.hasNext())
							paths.add(li.next());
					}
				}
			}
		}

		// search for a library that exists in jar form on the buildpath
		IPath path = null;
		if (libName.equals(DOT))
			path = new Path(DOT);
		else {
			IResource res = project.findMember(libName);
			if (res != null)
				path = res.getFullPath();
			else
				path = new Path(libName);
		}

		Collection list = (Collection) classpathMap.get(path);
		if (list != null) {
			Iterator li = list.iterator();
			while (li.hasNext())
				paths.add(li.next());
		}
		return (IPath[]) paths.toArray(new IPath[paths.size()]);
	}

	private static IPath[] getDevPaths(IPluginModelBase model, boolean checkExcluded, Map pluginsMap) {
		ArrayList result = new ArrayList();
		IProject project = model.getUnderlyingResource().getProject();
		IPluginBase base = model.getPluginBase();
		IPluginLibrary[] libraries = base.getLibraries();
		try {
			if (project.hasNature(JavaCore.NATURE_ID)) {
				Map classpathMap = getClasspathMap(project, checkExcluded, !base.getId().equals(PDECore.getDefault().getModelManager().getSystemBundleId()), false);
				IFile file = PDEProject.getBuildProperties(project);
				IPath filePath = file.getLocation();
				boolean searchBuild = filePath != null && filePath.toFile().exists();
				if (searchBuild) {
					WorkspaceBuildModel bModel = new WorkspaceBuildModel(file);
					IBuild build = bModel.getBuild();
					// if it is a custom build, act like there is no build.properties (add everything)
					IBuildEntry entry = build.getEntry("custom"); //$NON-NLS-1$
					if (entry != null)
						searchBuild = false;
					else {
						if (libraries.length == 0) {
							IPath[] paths = findLibrary(DOT, project, classpathMap, build);
							if (paths.length == 0) {
								// No mapping for default library, if there are source folders just add their corresponding output folders to the build path.
								// This likely indicates an error in the build.properties, but to be friendly we should add the output folders so running/debugging
								// works (see bug 237025)
								if (!classpathMap.isEmpty()) {
									Iterator iterator = classpathMap.values().iterator();
									List collect = new ArrayList();
									while (iterator.hasNext()) {
										Collection list = (Collection) iterator.next();
										collect.addAll(list);
									}
									paths = (IPath[]) collect.toArray(new IPath[collect.size()]);
								}
							}
							for (int j = 0; j < paths.length; j++)
								addPath(result, project, paths[j]);
						} else {
							for (int i = 0; i < libraries.length; i++) {
								IPath[] paths = findLibrary(libraries[i].getName(), project, classpathMap, build);
								if (paths.length == 0 && !libraries[i].getName().equals(DOT)) {
									paths = findLibraryFromFragments(libraries[i].getName(), model, checkExcluded, pluginsMap);
								}
								for (int j = 0; j < paths.length; j++)
									addPath(result, project, paths[j]);
							}
						}
					}
				}
				if (!searchBuild) {
					// if no build.properties, add all output folders
					Iterator it = classpathMap.entrySet().iterator();
					while (it.hasNext()) {
						Map.Entry entry = (Map.Entry) it.next();
						ArrayList list = (ArrayList) entry.getValue();
						ListIterator li = list.listIterator();
						while (li.hasNext())
							addPath(result, project, (IPath) li.next());
					}
				}
			}
		} catch (JavaModelException e) {
		} catch (CoreException e) {
		}
		return (IPath[]) result.toArray(new IPath[result.size()]);
	}

	// looks for fragments for a plug-in.  Then searches the fragments for a specific library.  Will return paths which are absolute (required by runtime)
	private static IPath[] findLibraryFromFragments(String libName, IPluginModelBase model, boolean checkExcluded, Map plugins) {
		IFragmentModel[] frags = PDEManager.findFragmentsFor(model);
		for (int i = 0; i < frags.length; i++) {
			if (plugins != null && !plugins.containsKey(frags[i].getBundleDescription().getSymbolicName()))
				continue;
			// look in project first
			if (frags[i].getUnderlyingResource() != null) {
				try {
					IProject project = frags[i].getUnderlyingResource().getProject();
					Map classpathMap = getClasspathMap(project, checkExcluded, false, true);
					IFile file = PDEProject.getBuildProperties(project);
					IBuild build = null;
					if (file.exists()) {
						WorkspaceBuildModel bModel = new WorkspaceBuildModel(file);
						build = bModel.getBuild();
					}
					IPath[] paths = findLibrary(libName, project, classpathMap, build);
					if (paths.length > 0)
						return postfixFragmentAnnotation(paths);

				} catch (JavaModelException e) {
					continue;
				}
				// if external plugin, look in child directories for library
			} else {
				File file = new File(frags[i].getInstallLocation());
				if (file.isDirectory()) {
					file = new File(file, libName);
					if (file.exists())
						// Postfix fragment annotation for fragment path (fix bug 294211)
						return new IPath[] {new Path(file.getPath() + FRAGMENT_ANNOTATION)};
				}
			}
		}
		return new IPath[0];
	}

	/*
	 * Postfixes the fragment annotation for the paths that we know come
	 * from fragments.  This is needed to fix bug 294211.
	 */
	private static IPath[] postfixFragmentAnnotation(IPath[] paths) {
		for (int i = 0; i < paths.length; i++)
			paths[i] = new Path(paths[i].toString() + FRAGMENT_ANNOTATION);
		return paths;
	}

	private static void addPath(ArrayList result, IProject project, IPath path) {
		IPath resultPath = null;
		if (path.isAbsolute())
			resultPath = path;
		else if (path.segmentCount() > 0 && path.segment(0).equals(project.getName())) {
			IContainer bundleRoot = PDEProject.getBundleRoot(project);
			IPath rootPath = bundleRoot.getFullPath();
			// make path relative to bundle root
			path = path.makeRelativeTo(rootPath);
			if (path.segmentCount() == 0)
				resultPath = new Path(DOT);
			else {
				IResource resource = bundleRoot.findMember(path);
				if (resource != null)
					resultPath = path;
			}
		}

		if (resultPath != null && !result.contains(resultPath))
			result.add(resultPath);
	}

	private static List getFoldersToExclude(IProject project, boolean checkExcluded) {
		ArrayList list = new ArrayList();
		if (checkExcluded) {
			IEclipsePreferences pref = new ProjectScope(project).getNode(PDECore.PLUGIN_ID);
			if (pref != null) {
				String binExcludes = pref.get(ICoreConstants.SELFHOSTING_BIN_EXCLUDES, ""); //$NON-NLS-1$
				StringTokenizer tokenizer = new StringTokenizer(binExcludes, ","); //$NON-NLS-1$
				while (tokenizer.hasMoreTokens()) {
					list.add(new Path(tokenizer.nextToken().trim()));
				}
			}
		}
		return list;
	}

}

Back to the top