KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > core > util > PDEJavaHelper


1 /*******************************************************************************
2  * Copyright (c) 2005, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.internal.core.util;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Collection JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.ListIterator JavaDoc;
17
18 import org.eclipse.core.resources.IProject;
19 import org.eclipse.core.resources.IResource;
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IPath;
22 import org.eclipse.core.runtime.Path;
23 import org.eclipse.jdt.core.IJavaElement;
24 import org.eclipse.jdt.core.IJavaProject;
25 import org.eclipse.jdt.core.IPackageFragment;
26 import org.eclipse.jdt.core.IPackageFragmentRoot;
27 import org.eclipse.jdt.core.IType;
28 import org.eclipse.jdt.core.JavaCore;
29 import org.eclipse.jdt.core.JavaModelException;
30 import org.eclipse.jdt.core.search.IJavaSearchScope;
31 import org.eclipse.jdt.core.search.SearchEngine;
32 import org.eclipse.jdt.launching.JavaRuntime;
33 import org.eclipse.osgi.service.resolver.ExportPackageDescription;
34 import org.eclipse.osgi.service.resolver.ImportPackageSpecification;
35 import org.eclipse.pde.core.plugin.IPluginLibrary;
36 import org.eclipse.pde.core.plugin.IPluginModelBase;
37 import org.eclipse.pde.core.plugin.PluginRegistry;
38 import org.eclipse.pde.internal.core.ClasspathUtilCore;
39 import org.eclipse.pde.internal.core.PDECore;
40 import org.eclipse.pde.internal.core.SearchablePluginsManager;
41
42 public class PDEJavaHelper {
43     
44     /*static class Requestor extends TypeNameRequestor {
45         int count = 0;
46         
47         public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
48                 char[][] enclosingTypeNames, String path) {
49             count += 1;
50         }
51         
52         public boolean hasMatches() {
53             return count > 0;
54         }
55     }*/

56     
57     public static boolean isOnClasspath(String JavaDoc fullyQualifiedName, IJavaProject project) {
58         if (fullyQualifiedName.indexOf('$') != -1)
59             fullyQualifiedName = fullyQualifiedName.replace('$', '.');
60         try {
61             IType type = project.findType(fullyQualifiedName);
62             return type != null && type.exists();
63         } catch (JavaModelException e) {
64         }
65         return false;
66         /*try {
67             Requestor requestor = new Requestor();
68             new SearchEngine().searchAllTypeNames(
69                     fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf('.')).toCharArray(),
70                     SearchPattern.R_EXACT_MATCH|SearchPattern.R_CASE_SENSITIVE,
71                     fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf('.') + 1).toCharArray(),
72                     SearchPattern.R_EXACT_MATCH|SearchPattern.R_CASE_SENSITIVE,
73                     IJavaSearchConstants.TYPE,
74                     SearchEngine.createJavaSearchScope(new IJavaElement[] {project}),
75                     requestor,
76                     IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH,
77                     new NullProgressMonitor());
78             return requestor.hasMatches();
79         } catch (JavaModelException e) {
80         }
81         return false;*/

82     }
83     
84     public static IJavaSearchScope getSearchScope(IJavaProject project) {
85         return SearchEngine.createJavaSearchScope(getNonJRERoots(project));
86     }
87
88     public static IJavaSearchScope getSearchScope(IProject project) {
89         return getSearchScope(JavaCore.create(project));
90     }
91     public static IPackageFragmentRoot[] getNonJRERoots(IJavaProject project) {
92         ArrayList JavaDoc result = new ArrayList JavaDoc();
93         try {
94             IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
95             for (int i = 0; i < roots.length; i++) {
96                 if (!isJRELibrary(roots[i])) {
97                     result.add(roots[i]);
98                 }
99             }
100         } catch (JavaModelException e) {
101         }
102         return (IPackageFragmentRoot[]) result.toArray(new IPackageFragmentRoot[result.size()]);
103     }
104     
105     public static boolean isJRELibrary(IPackageFragmentRoot root) {
106         try {
107             IPath path = root.getRawClasspathEntry().getPath();
108             if (path.equals(new Path(JavaRuntime.JRE_CONTAINER))
109                     || path.equals(new Path(JavaRuntime.JRELIB_VARIABLE))) {
110                 return true;
111             }
112         } catch (JavaModelException e) {
113         }
114         return false;
115     }
116     
117     
118     /**
119      * @param packageName - the name of the package
120      * @param pluginID - the id of the containing plug-in - can be null if <code>project</code> is not null
121      * @param project - if null will search for an external package fragment, otherwise will search in project
122      * @return
123      */

124     public static IPackageFragment getPackageFragment(String JavaDoc packageName, String JavaDoc pluginID, IProject project) {
125         if (project == null)
126             return getExternalPackageFragment(packageName, pluginID);
127         
128         IJavaProject jp = JavaCore.create(project);
129         if (jp != null)
130             try {
131                 IPackageFragmentRoot[] roots = jp.getAllPackageFragmentRoots();
132                 for (int i = 0; i < roots.length; i++) {
133                     IPackageFragment frag = roots[i].getPackageFragment(packageName);
134                     if (frag.exists()) {
135                         return frag;
136                     }
137                 }
138             } catch (JavaModelException e) {
139             }
140         return null;
141     }
142     
143     private static IPackageFragment getExternalPackageFragment(String JavaDoc packageName, String JavaDoc pluginID) {
144         if (pluginID == null)
145             return null;
146         IPluginModelBase base = null;
147         try {
148             IPluginModelBase plugin = PluginRegistry.findModel(pluginID);
149             if (plugin == null)
150                 return null;
151             ImportPackageSpecification[] packages = plugin.getBundleDescription().getImportPackages();
152             for (int i =0; i < packages.length; i++)
153                 if (packages[i].getName().equals(packageName)) {
154                     ExportPackageDescription desc = (ExportPackageDescription) packages[i].getSupplier();
155                     if (desc != null)
156                         base = PluginRegistry.findModel(desc.getExporter().getSymbolicName());
157                     break;
158                 }
159             if (base == null)
160                 return null;
161             IResource res = base.getUnderlyingResource();
162             if (res != null) {
163                 IJavaProject jp = JavaCore.create(res.getProject());
164                 if (jp != null)
165                     try {
166                         IPackageFragmentRoot[] roots = jp.getAllPackageFragmentRoots();
167                         for (int i = 0; i < roots.length; i++) {
168                             IPackageFragment frag = roots[i].getPackageFragment(packageName);
169                             if (frag.exists())
170                                 return frag;
171                         }
172                     } catch (JavaModelException e) {
173                     }
174             }
175             IProject proj = PDECore.getWorkspace().getRoot().getProject(SearchablePluginsManager.PROXY_PROJECT_NAME);
176             if (proj == null)
177                 return searchWorkspaceForPackage(packageName, base);
178             IJavaProject jp = JavaCore.create(proj);
179             IPath path = new Path(base.getInstallLocation());
180             // if model is in jar form
181
if (!path.toFile().isDirectory()) {
182                 IPackageFragmentRoot root = jp.findPackageFragmentRoot(path);
183                 if (root != null) {
184                     IPackageFragment frag = root.getPackageFragment(packageName);
185                     if (frag.exists())
186                         return frag;
187                 }
188             // else model is in folder form, try to find model's libraries on filesystem
189
} else {
190                 IPluginLibrary[] libs = base.getPluginBase().getLibraries();
191                 for (int i = 0; i < libs.length; i++) {
192                     if (IPluginLibrary.RESOURCE.equals(libs[i].getType()))
193                         continue;
194                     String JavaDoc libName = ClasspathUtilCore.expandLibraryName(libs[i].getName());
195                     IPackageFragmentRoot root = jp.findPackageFragmentRoot(path.append(libName));
196                     if (root != null) {
197                         IPackageFragment frag = root.getPackageFragment(packageName);
198                         if (frag.exists())
199                             return frag;
200                     }
201                 }
202             }
203         } catch (JavaModelException e){
204         }
205         return searchWorkspaceForPackage(packageName, base);
206     }
207     
208     private static IPackageFragment searchWorkspaceForPackage(String JavaDoc packageName, IPluginModelBase base) {
209         IPluginLibrary[] libs = base.getPluginBase().getLibraries();
210         ArrayList JavaDoc libPaths = new ArrayList JavaDoc();
211         IPath path = new Path(base.getInstallLocation());
212         if (libs.length == 0) {
213             libPaths.add(path);
214         }
215         for (int i = 0; i < libs.length; i++) {
216             if (IPluginLibrary.RESOURCE.equals(libs[i].getType()))
217                 continue;
218             String JavaDoc libName = ClasspathUtilCore.expandLibraryName(libs[i].getName());
219             libPaths.add(path.append(libName));
220         }
221         IProject[] projects = PDECore.getWorkspace().getRoot().getProjects();
222         for (int i = 0; i < projects.length; i++) {
223             try {
224                 if(!projects[i].hasNature(JavaCore.NATURE_ID) || !projects[i].isOpen())
225                     continue;
226                 IJavaProject jp = JavaCore.create(projects[i]);
227                 ListIterator JavaDoc li = libPaths.listIterator();
228                 while (li.hasNext()) {
229                     IPackageFragmentRoot root = jp.findPackageFragmentRoot((IPath)li.next());
230                     if (root != null) {
231                         IPackageFragment frag = root.getPackageFragment(packageName);
232                         if (frag.exists())
233                             return frag;
234                     }
235                 }
236             } catch (CoreException e) {
237             }
238         }
239         return null;
240     }
241     
242     /**
243      * @param jProject
244      * @param existingPackages
245      * @param allowJava
246      * @return
247      */

248     public static IPackageFragment[] getPackageFragments (IJavaProject jProject, Collection JavaDoc existingPackages, boolean allowJava) {
249         HashMap JavaDoc map = getPackageFragmentsHash(jProject, existingPackages,
250                 allowJava);
251         return (IPackageFragment[]) map.values().toArray(new IPackageFragment[map.size()]);
252     }
253
254     /**
255      * @param jProject
256      * @param existingPackages
257      * @param allowJava
258      * @return
259      */

260     public static HashMap JavaDoc getPackageFragmentsHash(IJavaProject jProject,
261             Collection JavaDoc existingPackages, boolean allowJava) {
262         HashMap JavaDoc map = new HashMap JavaDoc();
263         try {
264             IPackageFragmentRoot[] roots = getRoots(jProject);
265             for (int i = 0; i < roots.length; i++) {
266                 IJavaElement[] children = roots[i].getChildren();
267                 for (int j = 0; j < children.length; j++) {
268                     IPackageFragment fragment = (IPackageFragment)children[j];
269                     String JavaDoc name = fragment.getElementName();
270                     if (name.length() == 0)
271                         name = "."; //$NON-NLS-1$
272
if ((fragment.hasChildren() || fragment.getNonJavaResources().length > 0 )&& !existingPackages.contains(name)) {
273                         if (!name.equals("java") || !name.startsWith("java.") || allowJava) //$NON-NLS-1$ //$NON-NLS-2$
274
map.put(fragment.getElementName(), fragment);
275                     }
276                 }
277             }
278         } catch (JavaModelException e) {
279         }
280         return map;
281     }
282     
283     private static IPackageFragmentRoot[] getRoots(IJavaProject jProject) {
284         ArrayList JavaDoc result = new ArrayList JavaDoc();
285         try {
286             IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
287             for (int i = 0; i < roots.length; i++) {
288                 if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE
289                         || jProject.getProject().equals(roots[i].getCorrespondingResource())
290                         || (roots[i].isArchive() && !roots[i].isExternal())) {
291                     result.add(roots[i]);
292                 }
293             }
294         } catch (JavaModelException e) {
295         }
296         return (IPackageFragmentRoot[])result.toArray(new IPackageFragmentRoot[result.size()]);
297     }
298     
299     /**
300      * @param project
301      * @return
302      */

303     public static String JavaDoc getJavaSourceLevel(IProject project) {
304         return getJavaLevel(project, JavaCore.COMPILER_SOURCE);
305     }
306     
307     /**
308      * @param project
309      * @return
310      */

311     public static String JavaDoc getJavaComplianceLevel(IProject project) {
312         return getJavaLevel(project, JavaCore.COMPILER_COMPLIANCE);
313     }
314     
315     /**
316      * Precedence order from high to low: (1) Project specific option;
317      * (2) General preference option; (3) Default option; (4) Java 1.3
318      * @param project
319      * @param optionName
320      * @return
321      */

322     public static String JavaDoc getJavaLevel(IProject project, String JavaDoc optionName) {
323         // Returns the corresponding java project
324
// No need to check for null, will return null
325
IJavaProject javaProject = JavaCore.create(project);
326         String JavaDoc value = null;
327         // Preferred to use the project
328
if ((javaProject != null) &&
329                 javaProject.exists()) {
330             // Get the project specific option if one exists. Rolls up to the
331
// general preference option if no project specific option exists.
332
value = javaProject.getOption(optionName, true);
333             if (value != null) {
334                 return value;
335             }
336         }
337         // Get the general preference option
338
value = JavaCore.getJavaCore().getPluginPreferences().getString(optionName);
339         if (value != null) {
340             return value;
341         }
342         // Get the default option
343
value = JavaCore.getOption(optionName);
344         if (value != null) {
345             return value;
346         }
347         // Return the default
348
return JavaCore.VERSION_1_3;
349     }
350     
351 }
352
Popular Tags