KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > core > PackageFragment


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 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.jdt.internal.core;
12
13 import java.net.URL JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.HashSet JavaDoc;
16 import java.util.Map JavaDoc;
17
18 import org.eclipse.core.resources.IContainer;
19 import org.eclipse.core.resources.IFolder;
20 import org.eclipse.core.resources.IResource;
21 import org.eclipse.core.runtime.CoreException;
22 import org.eclipse.core.runtime.IPath;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.eclipse.core.runtime.OperationCanceledException;
25 import org.eclipse.core.runtime.Path;
26 import org.eclipse.jdt.core.IClassFile;
27 import org.eclipse.jdt.core.ICompilationUnit;
28 import org.eclipse.jdt.core.IJavaElement;
29 import org.eclipse.jdt.core.IJavaModelStatusConstants;
30 import org.eclipse.jdt.core.IJavaProject;
31 import org.eclipse.jdt.core.IPackageFragment;
32 import org.eclipse.jdt.core.IPackageFragmentRoot;
33 import org.eclipse.jdt.core.IParent;
34 import org.eclipse.jdt.core.ISourceManipulation;
35 import org.eclipse.jdt.core.JavaCore;
36 import org.eclipse.jdt.core.JavaModelException;
37 import org.eclipse.jdt.core.WorkingCopyOwner;
38 import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
39 import org.eclipse.jdt.internal.core.JavaModelManager.PerProjectInfo;
40 import org.eclipse.jdt.internal.core.util.MementoTokenizer;
41 import org.eclipse.jdt.internal.core.util.Messages;
42 import org.eclipse.jdt.internal.core.util.Util;
43
44 /**
45  * @see IPackageFragment
46  */

47 public class PackageFragment extends Openable implements IPackageFragment, SuffixConstants {
48     /**
49      * Constant empty list of class files
50      */

51     protected static final IClassFile[] NO_CLASSFILES = new IClassFile[] {};
52     /**
53      * Constant empty list of compilation units
54      */

55     protected static final ICompilationUnit[] NO_COMPILATION_UNITS = new ICompilationUnit[] {};
56     
57     public String JavaDoc[] names;
58
59 protected PackageFragment(PackageFragmentRoot root, String JavaDoc[] names) {
60     super(root);
61     this.names = names;
62 }
63 /**
64  * @see Openable
65  */

66 protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map JavaDoc newElements, IResource underlyingResource) throws JavaModelException {
67
68     // check whether this pkg can be opened
69
if (!underlyingResource.isAccessible()) throw newNotPresentException();
70     
71     // check that it is not excluded (https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
72
int kind = getKind();
73     if (kind == IPackageFragmentRoot.K_SOURCE && Util.isExcluded(this))
74         throw newNotPresentException();
75
76
77     // add compilation units/class files from resources
78
HashSet JavaDoc vChildren = new HashSet JavaDoc();
79     try {
80         PackageFragmentRoot root = getPackageFragmentRoot();
81         char[][] inclusionPatterns = root.fullInclusionPatternChars();
82         char[][] exclusionPatterns = root.fullExclusionPatternChars();
83         IResource[] members = ((IContainer) underlyingResource).members();
84         int length = members.length;
85         if (length > 0) {
86             IJavaProject project = getJavaProject();
87             String JavaDoc sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
88             String JavaDoc complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
89             for (int i = 0; i < length; i++) {
90                 IResource child = members[i];
91                 if (child.getType() != IResource.FOLDER
92                         && !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
93                     IJavaElement childElement;
94                     if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
95                         childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
96                         vChildren.add(childElement);
97                     } else if (kind == IPackageFragmentRoot.K_BINARY && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
98                         childElement = getClassFile(child.getName());
99                         vChildren.add(childElement);
100                     }
101                 }
102             }
103         }
104     } catch (CoreException e) {
105         throw new JavaModelException(e);
106     }
107     
108     if (kind == IPackageFragmentRoot.K_SOURCE) {
109         // add primary compilation units
110
ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
111         for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
112             ICompilationUnit primary = primaryCompilationUnits[i];
113             vChildren.add(primary);
114         }
115     }
116     
117     IJavaElement[] children = new IJavaElement[vChildren.size()];
118     vChildren.toArray(children);
119     info.setChildren(children);
120     return true;
121 }
122 /**
123  * Returns true if this fragment contains at least one java resource.
124  * Returns false otherwise.
125  */

126 public boolean containsJavaResources() throws JavaModelException {
127     return ((PackageFragmentInfo) getElementInfo()).containsJavaResources();
128 }
129 /**
130  * @see ISourceManipulation
131  */

132 public void copy(IJavaElement container, IJavaElement sibling, String JavaDoc rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
133     if (container == null) {
134         throw new IllegalArgumentException JavaDoc(Messages.operation_nullContainer);
135     }
136     IJavaElement[] elements= new IJavaElement[] {this};
137     IJavaElement[] containers= new IJavaElement[] {container};
138     IJavaElement[] siblings= null;
139     if (sibling != null) {
140         siblings= new IJavaElement[] {sibling};
141     }
142     String JavaDoc[] renamings= null;
143     if (rename != null) {
144         renamings= new String JavaDoc[] {rename};
145     }
146     getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
147 }
148 /**
149  * @see IPackageFragment
150  */

151 public ICompilationUnit createCompilationUnit(String JavaDoc cuName, String JavaDoc contents, boolean force, IProgressMonitor monitor) throws JavaModelException {
152     CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, cuName, contents, force);
153     op.runOperation(monitor);
154     return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
155 }
156 /**
157  * @see JavaElement
158  */

159 protected Object JavaDoc createElementInfo() {
160     return new PackageFragmentInfo();
161 }
162 /**
163  * @see ISourceManipulation
164  */

165 public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
166     IJavaElement[] elements = new IJavaElement[] {this};
167     getJavaModel().delete(elements, force, monitor);
168 }
169 public boolean equals(Object JavaDoc o) {
170     if (this == o) return true;
171     if (!(o instanceof PackageFragment)) return false;
172     
173     PackageFragment other = (PackageFragment) o;
174     return Util.equalArraysOrNull(this.names, other.names) &&
175             this.parent.equals(other.parent);
176 }
177 public boolean exists() {
178     // super.exist() only checks for the parent and the resource existence
179
// so also ensure that the package is not exceluded (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
180
return super.exists() && !Util.isExcluded(this);
181 }
182 /**
183  * @see IPackageFragment#getClassFile(String)
184  * @exception IllegalArgumentException if the name does not end with ".class"
185  */

186 public IClassFile getClassFile(String JavaDoc classFileName) {
187     if (!org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(classFileName)) {
188         throw new IllegalArgumentException JavaDoc(Messages.element_invalidClassFileName);
189     }
190     // don't hold on the .class file extension to save memory
191
// also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary
192
int length = classFileName.length() - 6;
193     char[] nameWithoutExtension = new char[length];
194     classFileName.getChars(0, length, nameWithoutExtension, 0);
195     return new ClassFile(this, new String JavaDoc(nameWithoutExtension));
196 }
197 /**
198  * Returns a the collection of class files in this - a folder package fragment which has a root
199  * that has its kind set to <code>IPackageFragmentRoot.K_Source</code> does not
200  * recognize class files.
201  *
202  * @see IPackageFragment#getClassFiles()
203  */

204 public IClassFile[] getClassFiles() throws JavaModelException {
205     if (getKind() == IPackageFragmentRoot.K_SOURCE) {
206         return NO_CLASSFILES;
207     }
208     
209     ArrayList JavaDoc list = getChildrenOfType(CLASS_FILE);
210     IClassFile[] array= new IClassFile[list.size()];
211     list.toArray(array);
212     return array;
213 }
214 /**
215  * @see IPackageFragment#getCompilationUnit(String)
216  * @exception IllegalArgumentException if the name does not end with ".java"
217  */

218 public ICompilationUnit getCompilationUnit(String JavaDoc cuName) {
219     if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(cuName)) {
220         throw new IllegalArgumentException JavaDoc(Messages.convention_unit_notJavaName);
221     }
222     return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
223 }
224 /**
225  * @see IPackageFragment#getCompilationUnits()
226  */

227 public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
228     if (getKind() == IPackageFragmentRoot.K_BINARY) {
229         return NO_COMPILATION_UNITS;
230     }
231     
232     ArrayList JavaDoc list = getChildrenOfType(COMPILATION_UNIT);
233     ICompilationUnit[] array= new ICompilationUnit[list.size()];
234     list.toArray(array);
235     return array;
236 }
237 /**
238  * @see IPackageFragment#getCompilationUnits(WorkingCopyOwner)
239  */

240 public ICompilationUnit[] getCompilationUnits(WorkingCopyOwner owner) {
241     ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, false/*don't add primary*/);
242     if (workingCopies == null) return JavaModelManager.NO_WORKING_COPY;
243     int length = workingCopies.length;
244     ICompilationUnit[] result = new ICompilationUnit[length];
245     int index = 0;
246     for (int i = 0; i < length; i++) {
247         ICompilationUnit wc = workingCopies[i];
248         if (equals(wc.getParent()) && !Util.isExcluded(wc)) { // 59933 - excluded wc shouldn't be answered back
249
result[index++] = wc;
250         }
251     }
252     if (index != length) {
253         System.arraycopy(result, 0, result = new ICompilationUnit[index], 0, index);
254     }
255     return result;
256 }
257 public String JavaDoc getElementName() {
258     if (this.names.length == 0)
259         return DEFAULT_PACKAGE_NAME;
260     return Util.concatWith(this.names, '.');
261 }
262 /**
263  * @see IJavaElement
264  */

265 public int getElementType() {
266     return PACKAGE_FRAGMENT;
267 }
268 /*
269  * @see JavaElement
270  */

271 public IJavaElement getHandleFromMemento(String JavaDoc token, MementoTokenizer memento, WorkingCopyOwner owner) {
272     switch (token.charAt(0)) {
273         case JEM_CLASSFILE:
274             if (!memento.hasMoreTokens()) return this;
275             String JavaDoc classFileName = memento.nextToken();
276             JavaElement classFile = (JavaElement)getClassFile(classFileName);
277             return classFile.getHandleFromMemento(memento, owner);
278         case JEM_COMPILATIONUNIT:
279             if (!memento.hasMoreTokens()) return this;
280             String JavaDoc cuName = memento.nextToken();
281             JavaElement cu = new CompilationUnit(this, cuName, owner);
282             return cu.getHandleFromMemento(memento, owner);
283     }
284     return null;
285 }
286 /**
287  * @see JavaElement#getHandleMementoDelimiter()
288  */

289 protected char getHandleMementoDelimiter() {
290     return JavaElement.JEM_PACKAGEFRAGMENT;
291 }
292 /**
293  * @see IPackageFragment#getKind()
294  */

295 public int getKind() throws JavaModelException {
296     return ((IPackageFragmentRoot)getParent()).getKind();
297 }
298 /**
299  * Returns an array of non-java resources contained in the receiver.
300  */

301 public Object JavaDoc[] getNonJavaResources() throws JavaModelException {
302     if (this.isDefaultPackage()) {
303         // We don't want to show non java resources of the default package (see PR #1G58NB8)
304
return JavaElementInfo.NO_NON_JAVA_RESOURCES;
305     } else {
306         return ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(getResource(), getPackageFragmentRoot());
307     }
308 }
309 /**
310  * @see IJavaElement#getPath()
311  */

312 public IPath getPath() {
313     PackageFragmentRoot root = this.getPackageFragmentRoot();
314     if (root.isArchive()) {
315         return root.getPath();
316     } else {
317         IPath path = root.getPath();
318         for (int i = 0, length = this.names.length; i < length; i++) {
319             String JavaDoc name = this.names[i];
320             path = path.append(name);
321         }
322         return path;
323     }
324 }
325 /**
326  * @see IJavaElement#getResource()
327  */

328 public IResource getResource() {
329     PackageFragmentRoot root = this.getPackageFragmentRoot();
330     if (root.isArchive()) {
331         return root.getResource();
332     } else {
333         int length = this.names.length;
334         if (length == 0) {
335             return root.getResource();
336         } else {
337             IPath path = new Path(this.names[0]);
338             for (int i = 1; i < length; i++)
339                 path = path.append(this.names[i]);
340             return ((IContainer)root.getResource()).getFolder(path);
341         }
342     }
343 }
344 /**
345  * @see IJavaElement#getUnderlyingResource()
346  */

347 public IResource getUnderlyingResource() throws JavaModelException {
348     IResource rootResource = this.parent.getUnderlyingResource();
349     if (rootResource == null) {
350         //jar package fragment root that has no associated resource
351
return null;
352     }
353     // the underlying resource may be a folder or a project (in the case that the project folder
354
// is atually the package fragment root)
355
if (rootResource.getType() == IResource.FOLDER || rootResource.getType() == IResource.PROJECT) {
356         IContainer folder = (IContainer) rootResource;
357         String JavaDoc[] segs = this.names;
358         for (int i = 0; i < segs.length; ++i) {
359             IResource child = folder.findMember(segs[i]);
360             if (child == null || child.getType() != IResource.FOLDER) {
361                 throw newNotPresentException();
362             }
363             folder = (IFolder) child;
364         }
365         return folder;
366     } else {
367         return rootResource;
368     }
369 }
370 public int hashCode() {
371     int hash = this.parent.hashCode();
372     for (int i = 0, length = this.names.length; i < length; i++)
373         hash = Util.combineHashCodes(this.names[i].hashCode(), hash);
374     return hash;
375 }
376 /**
377  * @see IParent
378  */

379 public boolean hasChildren() throws JavaModelException {
380     return getChildren().length > 0;
381 }
382 /**
383  * @see IPackageFragment#hasSubpackages()
384  */

385 public boolean hasSubpackages() throws JavaModelException {
386     IJavaElement[] packages= ((IPackageFragmentRoot)getParent()).getChildren();
387     int namesLength = this.names.length;
388     nextPackage: for (int i= 0, length = packages.length; i < length; i++) {
389         String JavaDoc[] otherNames = ((PackageFragment) packages[i]).names;
390         if (otherNames.length <= namesLength) continue nextPackage;
391         for (int j = 0; j < namesLength; j++)
392             if (!this.names[j].equals(otherNames[j]))
393                 continue nextPackage;
394         return true;
395     }
396     return false;
397 }
398 /**
399  * @see IPackageFragment#isDefaultPackage()
400  */

401 public boolean isDefaultPackage() {
402     return this.names.length == 0;
403 }
404 /**
405  * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
406  */

407 public void move(IJavaElement container, IJavaElement sibling, String JavaDoc rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
408     if (container == null) {
409         throw new IllegalArgumentException JavaDoc(Messages.operation_nullContainer);
410     }
411     IJavaElement[] elements= new IJavaElement[] {this};
412     IJavaElement[] containers= new IJavaElement[] {container};
413     IJavaElement[] siblings= null;
414     if (sibling != null) {
415         siblings= new IJavaElement[] {sibling};
416     }
417     String JavaDoc[] renamings= null;
418     if (rename != null) {
419         renamings= new String JavaDoc[] {rename};
420     }
421     getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
422 }
423 /**
424  * @see ISourceManipulation#rename(String, boolean, IProgressMonitor)
425  */

426 public void rename(String JavaDoc newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
427     if (newName == null) {
428         throw new IllegalArgumentException JavaDoc(Messages.element_nullName);
429     }
430     IJavaElement[] elements= new IJavaElement[] {this};
431     IJavaElement[] dests= new IJavaElement[] {this.getParent()};
432     String JavaDoc[] renamings= new String JavaDoc[] {newName};
433     getJavaModel().rename(elements, dests, renamings, force, monitor);
434 }
435 /**
436  * Debugging purposes
437  */

438 protected void toStringChildren(int tab, StringBuffer JavaDoc buffer, Object JavaDoc info) {
439     if (tab == 0) {
440         super.toStringChildren(tab, buffer, info);
441     }
442 }
443 /**
444  * Debugging purposes
445  */

446 protected void toStringInfo(int tab, StringBuffer JavaDoc buffer, Object JavaDoc info, boolean showResolvedInfo) {
447     buffer.append(this.tabString(tab));
448     if (this.names.length == 0) {
449         buffer.append("<default>"); //$NON-NLS-1$
450
} else {
451         toStringName(buffer);
452     }
453     if (info == null) {
454         buffer.append(" (not open)"); //$NON-NLS-1$
455
} else {
456         if (tab > 0) {
457             buffer.append(" (...)"); //$NON-NLS-1$
458
}
459     }
460 }
461 /*
462  * @see IJavaElement#getAttachedJavadoc(IProgressMonitor)
463  */

464 public String JavaDoc getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
465     PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.getJavaProject().getProject());
466     String JavaDoc cachedJavadoc = null;
467     synchronized (projectInfo.javadocCache) {
468         cachedJavadoc = (String JavaDoc) projectInfo.javadocCache.get(this);
469     }
470     if (cachedJavadoc != null) {
471         return cachedJavadoc;
472     }
473     URL JavaDoc baseLocation= getJavadocBaseLocation();
474     if (baseLocation == null) {
475         return null;
476     }
477     StringBuffer JavaDoc pathBuffer = new StringBuffer JavaDoc(baseLocation.toExternalForm());
478
479     if (!(pathBuffer.charAt(pathBuffer.length() - 1) == '/')) {
480         pathBuffer.append('/');
481     }
482     String JavaDoc packPath= this.getElementName().replace('.', '/');
483     pathBuffer.append(packPath).append('/').append(JavadocConstants.PACKAGE_FILE_NAME);
484     
485     if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
486     final String JavaDoc contents = getURLContents(String.valueOf(pathBuffer));
487     if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
488     if (contents == null) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this));
489     synchronized (projectInfo.javadocCache) {
490         projectInfo.javadocCache.put(this, contents);
491     }
492     return contents;
493 }
494 }
495
Popular Tags