KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.jdt.internal.core;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Enumeration JavaDoc;
15 import java.util.Map JavaDoc;
16
17 import org.eclipse.core.resources.*;
18 import org.eclipse.core.runtime.*;
19 import org.eclipse.jdt.core.*;
20 import org.eclipse.jdt.core.compiler.CharOperation;
21 import org.eclipse.jdt.internal.core.util.MementoTokenizer;
22 import org.eclipse.jdt.internal.core.util.Messages;
23 import org.eclipse.jdt.internal.core.util.Util;
24
25 /**
26  * @see IPackageFragmentRoot
27  */

28 public class PackageFragmentRoot extends Openable implements IPackageFragmentRoot {
29
30     /**
31      * The delimiter between the source path and root path in the
32      * attachment server property.
33      */

34     protected final static char ATTACHMENT_PROPERTY_DELIMITER= '*';
35     /*
36      * No source attachment property
37      */

38     public final static String JavaDoc NO_SOURCE_ATTACHMENT = ""; //$NON-NLS-1$
39

40     /**
41      * The resource associated with this root.
42      * (an IResource or a java.io.File (for external jar only))
43      */

44     protected Object JavaDoc resource;
45     
46 /**
47  * Constructs a package fragment root which is the root of the java package
48  * directory hierarchy.
49  */

50 protected PackageFragmentRoot(IResource resource, JavaProject project) {
51     super(project);
52     this.resource = resource;
53 }
54
55 /**
56  * @see IPackageFragmentRoot
57  */

58 public void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor) throws JavaModelException {
59     try {
60         verifyAttachSource(sourcePath);
61         if (monitor != null) {
62             monitor.beginTask(Messages.element_attachingSource, 2);
63         }
64         SourceMapper oldMapper= getSourceMapper();
65         IWorkspace workspace = ResourcesPlugin.getWorkspace();
66         boolean rootNeedsToBeClosed= false;
67
68         if (sourcePath == null) {
69             //source being detached
70
rootNeedsToBeClosed= true;
71             setSourceMapper(null);
72         /* Disable deltas (see 1GDTUSD)
73             // fire a delta to notify the UI about the source detachement.
74             JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
75             JavaModel model = (JavaModel) getJavaModel();
76             JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
77             attachedSourceDelta .sourceDetached(this); // this would be a PackageFragmentRoot
78             manager.registerResourceDelta(attachedSourceDelta );
79             manager.fire(); // maybe you want to fire the change later. Let us know about it.
80         */

81         } else {
82         /*
83             // fire a delta to notify the UI about the source attachement.
84             JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
85             JavaModel model = (JavaModel) getJavaModel();
86             JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
87             attachedSourceDelta .sourceAttached(this); // this would be a PackageFragmentRoot
88             manager.registerResourceDelta(attachedSourceDelta );
89             manager.fire(); // maybe you want to fire the change later. Let us know about it.
90          */

91
92             //check if different from the current attachment
93
IPath storedSourcePath= getSourceAttachmentPath();
94             IPath storedRootPath= getSourceAttachmentRootPath();
95             if (monitor != null) {
96                 monitor.worked(1);
97             }
98             if (storedSourcePath != null) {
99                 if (!(storedSourcePath.equals(sourcePath) && (rootPath != null && rootPath.equals(storedRootPath)) || storedRootPath == null)) {
100                     rootNeedsToBeClosed= true;
101                 }
102             }
103             // check if source path is valid
104
Object JavaDoc target = JavaModel.getTarget(workspace.getRoot(), sourcePath, false);
105             if (target == null) {
106                 throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, sourcePath));
107             }
108             SourceMapper mapper = createSourceMapper(sourcePath, rootPath);
109             if (rootPath == null && mapper.rootPath != null) {
110                 // as a side effect of calling the SourceMapper constructor, the root path was computed
111
rootPath = new Path(mapper.rootPath);
112             }
113             setSourceMapper(mapper);
114         }
115         if (sourcePath == null) {
116             Util.setSourceAttachmentProperty(getPath(), null); //remove the property
117
} else {
118             //set the property to the path of the mapped source
119
Util.setSourceAttachmentProperty(
120                 getPath(),
121                 sourcePath.toString()
122                 + (rootPath == null ? "" : (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString()))); //$NON-NLS-1$
123
}
124         if (rootNeedsToBeClosed) {
125             if (oldMapper != null) {
126                 oldMapper.close();
127             }
128             BufferManager manager= BufferManager.getDefaultBufferManager();
129             Enumeration JavaDoc openBuffers= manager.getOpenBuffers();
130             while (openBuffers.hasMoreElements()) {
131                 IBuffer buffer= (IBuffer) openBuffers.nextElement();
132                 IOpenable possibleMember= buffer.getOwner();
133                 if (isAncestorOf((IJavaElement) possibleMember)) {
134                     buffer.close();
135                 }
136             }
137             if (monitor != null) {
138                 monitor.worked(1);
139             }
140         }
141     } catch (JavaModelException e) {
142         Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed
143
throw e;
144     } finally {
145         if (monitor != null) {
146             monitor.done();
147         }
148     }
149 }
150
151 /**
152  * @see Openable
153  */

154 protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map JavaDoc newElements, IResource underlyingResource) throws JavaModelException {
155     
156     // check whether this pkg fragment root can be opened
157
IStatus status = validateOnClasspath();
158     if (!status.isOK()) throw newJavaModelException(status);
159     if (!resourceExists()) throw newNotPresentException();
160
161     ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
162     return computeChildren(info, newElements);
163 }
164
165 SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) {
166     SourceMapper mapper = new SourceMapper(
167         sourcePath,
168         rootPath == null ? null : rootPath.toOSString(),
169         getJavaProject().getOptions(true)); // cannot use workspace options if external jar is 1.5 jar and workspace options are 1.4 options
170
return mapper;
171 }
172 /*
173  * @see org.eclipse.jdt.core.IPackageFragmentRoot#delete
174  */

175 public void delete(
176     int updateResourceFlags,
177     int updateModelFlags,
178     IProgressMonitor monitor)
179     throws JavaModelException {
180
181     DeletePackageFragmentRootOperation op = new DeletePackageFragmentRootOperation(this, updateResourceFlags, updateModelFlags);
182     op.runOperation(monitor);
183 }
184
185 /**
186  * Compute the package fragment children of this package fragment root.
187  *
188  * @exception JavaModelException The resource associated with this package fragment root does not exist
189  */

190 protected boolean computeChildren(OpenableElementInfo info, Map JavaDoc newElements) throws JavaModelException {
191     // Note the children are not opened (so not added to newElements) for a regular package fragment root
192
// Howver they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren)
193
try {
194         // the underlying resource may be a folder or a project (in the case that the project folder
195
// is actually the package fragment root)
196
IResource underlyingResource = getResource();
197         if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
198             ArrayList JavaDoc vChildren = new ArrayList JavaDoc(5);
199             IContainer rootFolder = (IContainer) underlyingResource;
200             char[][] inclusionPatterns = fullInclusionPatternChars();
201             char[][] exclusionPatterns = fullExclusionPatternChars();
202             computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, inclusionPatterns, exclusionPatterns), CharOperation.NO_STRINGS, vChildren, inclusionPatterns, exclusionPatterns);
203             IJavaElement[] children = new IJavaElement[vChildren.size()];
204             vChildren.toArray(children);
205             info.setChildren(children);
206         }
207     } catch (JavaModelException e) {
208         //problem resolving children; structure remains unknown
209
info.setChildren(new IJavaElement[]{});
210         throw e;
211     }
212     return true;
213 }
214
215 /**
216  * Starting at this folder, create package fragments and add the fragments that are not exclused
217  * to the collection of children.
218  *
219  * @exception JavaModelException The resource associated with this package fragment does not exist
220  */

221 protected void computeFolderChildren(IContainer folder, boolean isIncluded, String JavaDoc[] pkgName, ArrayList JavaDoc vChildren, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
222
223     if (isIncluded) {
224         IPackageFragment pkg = getPackageFragment(pkgName);
225         vChildren.add(pkg);
226     }
227     try {
228         JavaProject javaProject = (JavaProject)getJavaProject();
229         JavaModelManager manager = JavaModelManager.getJavaModelManager();
230         IResource[] members = folder.members();
231         boolean hasIncluded = isIncluded;
232         int length = members.length;
233         if (length >0) {
234             String JavaDoc sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
235             String JavaDoc complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
236             for (int i = 0; i < length; i++) {
237                 IResource member = members[i];
238                 String JavaDoc memberName = member.getName();
239             
240                 switch(member.getType()) {
241                 
242                     case IResource.FOLDER:
243                         // recurse into sub folders even even parent not included as a sub folder could be included
244
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65637)
245
if (Util.isValidFolderNameForPackage(memberName, sourceLevel, complianceLevel)) {
246                             // eliminate binary output only if nested inside direct subfolders
247
if (javaProject.contains(member)) {
248                                 String JavaDoc[] newNames = Util.arrayConcat(pkgName, manager.intern(memberName));
249                                 boolean isMemberIncluded = !Util.isExcluded(member, inclusionPatterns, exclusionPatterns);
250                                 computeFolderChildren((IFolder) member, isMemberIncluded, newNames, vChildren, inclusionPatterns, exclusionPatterns);
251                             }
252                         }
253                         break;
254                     case IResource.FILE:
255                         // inclusion filter may only include files, in which case we still want to include the immediate parent package (lazily)
256
if (!hasIncluded
257                                 && Util.isValidCompilationUnitName(memberName, sourceLevel, complianceLevel)
258                                 && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns)) {
259                             hasIncluded = true;
260                             IPackageFragment pkg = getPackageFragment(pkgName);
261                             vChildren.add(pkg);
262                         }
263                         break;
264                 }
265             }
266         }
267     } catch(IllegalArgumentException JavaDoc e){
268         throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
269
} catch (CoreException e) {
270         throw new JavaModelException(e);
271     }
272 }
273
274 /*
275  * @see org.eclipse.jdt.core.IPackageFragmentRoot#copy
276  */

277 public void copy(
278     IPath destination,
279     int updateResourceFlags,
280     int updateModelFlags,
281     IClasspathEntry sibling,
282     IProgressMonitor monitor)
283     throws JavaModelException {
284         
285     CopyPackageFragmentRootOperation op =
286         new CopyPackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
287     op.runOperation(monitor);
288 }
289
290 /**
291  * Returns a new element info for this element.
292  */

293 protected Object JavaDoc createElementInfo() {
294     return new PackageFragmentRootInfo();
295 }
296
297 /**
298  * @see IPackageFragmentRoot
299  */

300 public IPackageFragment createPackageFragment(String JavaDoc pkgName, boolean force, IProgressMonitor monitor) throws JavaModelException {
301     CreatePackageFragmentOperation op = new CreatePackageFragmentOperation(this, pkgName, force);
302     op.runOperation(monitor);
303     return getPackageFragment(op.pkgName);
304 }
305
306 /**
307  * Returns the root's kind - K_SOURCE or K_BINARY, defaults
308  * to K_SOURCE if it is not on the classpath.
309  *
310  * @exception JavaModelException if the project and root do
311  * not exist.
312  */

313 protected int determineKind(IResource underlyingResource) throws JavaModelException {
314     IClasspathEntry entry = ((JavaProject)getJavaProject()).getClasspathEntryFor(underlyingResource.getFullPath());
315     if (entry != null) {
316         return entry.getContentKind();
317     }
318     return IPackageFragmentRoot.K_SOURCE;
319 }
320
321 /**
322  * Compares two objects for equality;
323  * for <code>PackageFragmentRoot</code>s, equality is having the
324  * same parent, same resources, and occurrence count.
325  *
326  */

327 public boolean equals(Object JavaDoc o) {
328     if (this == o)
329         return true;
330     if (!(o instanceof PackageFragmentRoot))
331         return false;
332     PackageFragmentRoot other = (PackageFragmentRoot) o;
333     return this.resource.equals(other.resource) &&
334             this.parent.equals(other.parent);
335 }
336
337 /**
338  * @see IJavaElement
339  */

340 public boolean exists() {
341     return super.exists() && validateOnClasspath().isOK();
342 }
343
344 private IClasspathEntry findSourceAttachmentRecommendation() {
345     try {
346         IPath rootPath = this.getPath();
347         IClasspathEntry entry;
348         IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
349         
350         // try on enclosing project first
351
JavaProject parentProject = (JavaProject) getJavaProject();
352         try {
353             entry = parentProject.getClasspathEntryFor(rootPath);
354             if (entry != null){
355                 Object JavaDoc target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
356                 if (target instanceof IResource) {
357                     if (target instanceof IFile) {
358                         IFile file = (IFile) target;
359                         if (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
360                             return entry;
361                         }
362                     } else if (target instanceof IContainer) {
363                         return entry;
364                     }
365                 } else if (target instanceof java.io.File JavaDoc){
366                     java.io.File JavaDoc file = JavaModel.getFile(target);
367                     if (file != null) {
368                         if (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
369                             return entry;
370                         }
371                     } else {
372                         // external directory
373
return entry;
374                     }
375                 }
376             }
377         } catch(JavaModelException e){
378             // ignore
379
}
380         
381         // iterate over all projects
382
IJavaModel model = getJavaModel();
383         IJavaProject[] jProjects = model.getJavaProjects();
384         for (int i = 0, max = jProjects.length; i < max; i++){
385             JavaProject jProject = (JavaProject) jProjects[i];
386             if (jProject == parentProject) continue; // already done
387
try {
388                 entry = jProject.getClasspathEntryFor(rootPath);
389                 if (entry != null){
390                     Object JavaDoc target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
391                     if (target instanceof IResource) {
392                         if (target instanceof IFile){
393                             IFile file = (IFile) target;
394                             if (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
395                                 return entry;
396                             }
397                         } else if (target instanceof IContainer) {
398                             return entry;
399                         }
400                     } else if (target instanceof java.io.File JavaDoc){
401                         java.io.File JavaDoc file = (java.io.File JavaDoc) target;
402                         if (file.isFile()) {
403                             if (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){
404                                 return entry;
405                             }
406                         } else {
407                             // external directory
408
return entry;
409                         }
410                     }
411                 }
412             } catch(JavaModelException e){
413                 // ignore
414
}
415         }
416     } catch(JavaModelException e){
417         // ignore
418
}
419
420     return null;
421 }
422
423 /*
424  * Returns the exclusion patterns from the classpath entry associated with this root.
425  */

426 public char[][] fullExclusionPatternChars() {
427     try {
428         if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null;
429         ClasspathEntry entry = (ClasspathEntry)getRawClasspathEntry();
430         if (entry == null) {
431             return null;
432         } else {
433             return entry.fullExclusionPatternChars();
434         }
435     } catch (JavaModelException e) {
436         return null;
437     }
438 }
439
440 /*
441  * Returns the inclusion patterns from the classpath entry associated with this root.
442  */

443 public char[][] fullInclusionPatternChars() {
444     try {
445         if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null;
446         ClasspathEntry entry = (ClasspathEntry)getRawClasspathEntry();
447         if (entry == null) {
448             return null;
449         } else {
450             return entry.fullInclusionPatternChars();
451         }
452     } catch (JavaModelException e) {
453         return null;
454     }
455 }
456 public String JavaDoc getElementName() {
457     if (this.resource instanceof IFolder)
458         return ((IFolder) this.resource).getName();
459     return ""; //$NON-NLS-1$
460
}
461 /**
462  * @see IJavaElement
463  */

464 public int getElementType() {
465     return PACKAGE_FRAGMENT_ROOT;
466 }
467 /**
468  * @see JavaElement#getHandleMemento()
469  */

470 protected char getHandleMementoDelimiter() {
471     return JavaElement.JEM_PACKAGEFRAGMENTROOT;
472 }
473 /*
474  * @see JavaElement
475  */

476 public IJavaElement getHandleFromMemento(String JavaDoc token, MementoTokenizer memento, WorkingCopyOwner owner) {
477     switch (token.charAt(0)) {
478         case JEM_PACKAGEFRAGMENT:
479             String JavaDoc pkgName;
480             if (memento.hasMoreTokens()) {
481                 pkgName = memento.nextToken();
482                 char firstChar = pkgName.charAt(0);
483                 if (firstChar == JEM_CLASSFILE || firstChar == JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) {
484                     token = pkgName;
485                     pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME;
486                 } else {
487                     token = null;
488                 }
489             } else {
490                 pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME;
491                 token = null;
492             }
493             JavaElement pkg = (JavaElement)getPackageFragment(pkgName);
494             if (token == null) {
495                 return pkg.getHandleFromMemento(memento, owner);
496             } else {
497                 return pkg.getHandleFromMemento(token, memento, owner);
498             }
499     }
500     return null;
501 }
502 /**
503  * @see JavaElement#getHandleMemento(StringBuffer)
504  */

505 protected void getHandleMemento(StringBuffer JavaDoc buff) {
506     IPath path;
507     IResource underlyingResource = getResource();
508     if (underlyingResource != null) {
509         // internal jar or regular root
510
if (getResource().getProject().equals(getJavaProject().getProject())) {
511             path = underlyingResource.getProjectRelativePath();
512         } else {
513             path = underlyingResource.getFullPath();
514         }
515     } else {
516         // external jar
517
path = getPath();
518     }
519     ((JavaElement)getParent()).getHandleMemento(buff);
520     buff.append(getHandleMementoDelimiter());
521     escapeMementoName(buff, path.toString());
522 }
523 /**
524  * @see IPackageFragmentRoot
525  */

526 public int getKind() throws JavaModelException {
527     return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
528 }
529
530 /**
531  * Returns an array of non-java resources contained in the receiver.
532  */

533 public Object JavaDoc[] getNonJavaResources() throws JavaModelException {
534     return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(getJavaProject(), getResource(), this);
535 }
536
537 /**
538  * @see IPackageFragmentRoot
539  */

540 public IPackageFragment getPackageFragment(String JavaDoc packageName) {
541     // tolerate package names with spaces (e.g. 'x . y') (http://bugs.eclipse.org/bugs/show_bug.cgi?id=21957)
542
String JavaDoc[] pkgName = Util.getTrimmedSimpleNames(packageName);
543     return getPackageFragment(pkgName);
544 }
545 public PackageFragment getPackageFragment(String JavaDoc[] pkgName) {
546     return new PackageFragment(this, pkgName);
547 }
548 /**
549  * Returns the package name for the given folder
550  * (which is a decendent of this root).
551  */

552 protected String JavaDoc getPackageName(IFolder folder) {
553     IPath myPath= getPath();
554     IPath pkgPath= folder.getFullPath();
555     int mySegmentCount= myPath.segmentCount();
556     int pkgSegmentCount= pkgPath.segmentCount();
557     StringBuffer JavaDoc pkgName = new StringBuffer JavaDoc(IPackageFragment.DEFAULT_PACKAGE_NAME);
558     for (int i= mySegmentCount; i < pkgSegmentCount; i++) {
559         if (i > mySegmentCount) {
560             pkgName.append('.');
561         }
562         pkgName.append(pkgPath.segment(i));
563     }
564     return pkgName.toString();
565 }
566
567 /**
568  * @see IJavaElement
569  */

570 public IPath getPath() {
571     return getResource().getFullPath();
572 }
573
574 /*
575  * @see IPackageFragmentRoot
576  */

577 public IClasspathEntry getRawClasspathEntry() throws JavaModelException {
578
579     IClasspathEntry rawEntry = null;
580     JavaProject project = (JavaProject)this.getJavaProject();
581     project.getResolvedClasspath(); // force the reverse rawEntry cache to be populated
582
Map JavaDoc rootPathToRawEntries = project.getPerProjectInfo().rootPathToRawEntries;
583     if (rootPathToRawEntries != null) {
584         rawEntry = (IClasspathEntry) rootPathToRawEntries.get(this.getPath());
585     }
586     if (rawEntry == null) {
587         throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this));
588     }
589     return rawEntry;
590 }
591
592 /*
593  * @see IJavaElement
594  */

595 public IResource getResource() {
596     return (IResource)this.resource;
597 }
598
599 /**
600  * @see IPackageFragmentRoot
601  */

602 public IPath getSourceAttachmentPath() throws JavaModelException {
603     if (getKind() != K_BINARY) return null;
604     
605     // 1) look source attachment property (set iff attachSource(...) was called
606
IPath path = getPath();
607     String JavaDoc serverPathString= Util.getSourceAttachmentProperty(path);
608     if (serverPathString != null) {
609         int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
610         if (index < 0) {
611             // no root path specified
612
return new Path(serverPathString);
613         } else {
614             String JavaDoc serverSourcePathString= serverPathString.substring(0, index);
615             return new Path(serverSourcePathString);
616         }
617     }
618
619     // 2) look at classpath entry
620
IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
621     IPath sourceAttachmentPath;
622     if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null)
623         return sourceAttachmentPath;
624     
625     // 3) look for a recommendation
626
entry = findSourceAttachmentRecommendation();
627     if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null) {
628         return sourceAttachmentPath;
629     }
630     
631     return null;
632 }
633
634 /**
635  * For use by <code>AttachSourceOperation</code> only.
636  * Sets the source mapper associated with this root.
637  */

638 public void setSourceMapper(SourceMapper mapper) throws JavaModelException {
639     ((PackageFragmentRootInfo) getElementInfo()).setSourceMapper(mapper);
640 }
641
642
643
644 /**
645  * @see IPackageFragmentRoot
646  */

647 public IPath getSourceAttachmentRootPath() throws JavaModelException {
648     if (getKind() != K_BINARY) return null;
649     
650     // 1) look source attachment property (set iff attachSource(...) was called
651
IPath path = getPath();
652     String JavaDoc serverPathString= Util.getSourceAttachmentProperty(path);
653     if (serverPathString != null) {
654         int index = serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
655         if (index == -1) return null;
656         String JavaDoc serverRootPathString= IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
657         if (index != serverPathString.length() - 1) {
658             serverRootPathString= serverPathString.substring(index + 1);
659         }
660         return new Path(serverRootPathString);
661     }
662
663     // 2) look at classpath entry
664
IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
665     IPath sourceAttachmentRootPath;
666     if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
667         return sourceAttachmentRootPath;
668     
669     // 3) look for a recomendation
670
entry = findSourceAttachmentRecommendation();
671     if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
672         return sourceAttachmentRootPath;
673     
674     return null;
675 }
676
677 /**
678  * @see JavaElement
679  */

680 public SourceMapper getSourceMapper() {
681     SourceMapper mapper;
682     try {
683         PackageFragmentRootInfo rootInfo = (PackageFragmentRootInfo) getElementInfo();
684         mapper = rootInfo.getSourceMapper();
685         if (mapper == null) {
686             // first call to this method
687
IPath sourcePath= getSourceAttachmentPath();
688             IPath rootPath= getSourceAttachmentRootPath();
689             if (sourcePath == null)
690                 mapper = createSourceMapper(getPath(), rootPath); // attach root to itself
691
else
692                 mapper = createSourceMapper(sourcePath, rootPath);
693             rootInfo.setSourceMapper(mapper);
694         }
695     } catch (JavaModelException e) {
696         // no source can be attached
697
mapper = null;
698     }
699     return mapper;
700 }
701
702 /**
703  * @see IJavaElement
704  */

705 public IResource getUnderlyingResource() throws JavaModelException {
706     if (!exists()) throw newNotPresentException();
707     return getResource();
708 }
709
710 /**
711  * @see IParent
712  */

713 public boolean hasChildren() throws JavaModelException {
714     // a package fragment root always has the default package as a child
715
return true;
716 }
717
718 public int hashCode() {
719     return this.resource.hashCode();
720 }
721
722 /**
723  * @see IPackageFragmentRoot
724  */

725 public boolean isArchive() {
726     return false;
727 }
728
729 /**
730  * @see IPackageFragmentRoot
731  */

732 public boolean isExternal() {
733     return false;
734 }
735
736 /*
737  * Validate whether this package fragment root is on the classpath of its project.
738  */

739 protected IStatus validateOnClasspath() {
740     
741     IPath path = this.getPath();
742     try {
743         // check package fragment root on classpath of its project
744
JavaProject project = (JavaProject) getJavaProject();
745         IClasspathEntry entry = project.getClasspathEntryFor(path);
746         if (entry != null) {
747             return Status.OK_STATUS;
748         }
749     } catch(JavaModelException e){
750         // could not read classpath, then assume it is outside
751
return e.getJavaModelStatus();
752     }
753     return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
754 }
755 /*
756  * @see org.eclipse.jdt.core.IPackageFragmentRoot#move
757  */

758 public void move(
759     IPath destination,
760     int updateResourceFlags,
761     int updateModelFlags,
762     IClasspathEntry sibling,
763     IProgressMonitor monitor)
764     throws JavaModelException {
765
766     MovePackageFragmentRootOperation op =
767         new MovePackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
768     op.runOperation(monitor);
769 }
770
771 /**
772  * @private Debugging purposes
773  */

774 protected void toStringInfo(int tab, StringBuffer JavaDoc buffer, Object JavaDoc info, boolean showResolvedInfo) {
775     buffer.append(this.tabString(tab));
776     IPath path = getPath();
777     if (getJavaProject().getElementName().equals(path.segment(0))) {
778         if (path.segmentCount() == 1) {
779             buffer.append("<project root>"); //$NON-NLS-1$
780
} else {
781             buffer.append(path.removeFirstSegments(1).makeRelative());
782         }
783     } else {
784         if (isExternal()) {
785             buffer.append(path.toOSString());
786         } else {
787             buffer.append(path);
788         }
789     }
790     if (info == null) {
791         buffer.append(" (not open)"); //$NON-NLS-1$
792
}
793 }
794
795 /**
796  * Possible failures: <ul>
797  * <li>ELEMENT_NOT_PRESENT - the root supplied to the operation
798  * does not exist
799  * <li>INVALID_ELEMENT_TYPES - the root is not of kind K_BINARY
800  * <li>RELATIVE_PATH - the path supplied to this operation must be
801  * an absolute path
802  * </ul>
803  */

804 protected void verifyAttachSource(IPath sourcePath) throws JavaModelException {
805     if (!exists()) {
806         throw newNotPresentException();
807     } else if (this.getKind() != K_BINARY) {
808         throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
809     } else if (sourcePath != null && !sourcePath.isAbsolute()) {
810         throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, sourcePath));
811     }
812 }
813
814 }
815
Popular Tags