KickJava   Java API By Example, From Geeks To Geeks.

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


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.io.IOException JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.Map JavaDoc;
16 import java.util.zip.ZipEntry JavaDoc;
17 import java.util.zip.ZipFile JavaDoc;
18
19 import org.eclipse.core.resources.IContainer;
20 import org.eclipse.core.resources.IFile;
21 import org.eclipse.core.resources.IResource;
22 import org.eclipse.core.runtime.CoreException;
23 import org.eclipse.core.runtime.IPath;
24 import org.eclipse.core.runtime.IProgressMonitor;
25 import org.eclipse.core.runtime.IStatus;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.jdt.core.*;
28 import org.eclipse.jdt.core.compiler.IProblem;
29 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
30 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
31 import org.eclipse.jdt.internal.compiler.env.IBinaryType;
32 import org.eclipse.jdt.internal.compiler.env.IDependent;
33 import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
34 import org.eclipse.jdt.internal.core.util.MementoTokenizer;
35 import org.eclipse.jdt.internal.core.util.Util;
36
37 /**
38  * @see IClassFile
39  */

40
41 public class ClassFile extends Openable implements IClassFile, SuffixConstants {
42
43     protected String JavaDoc name;
44     protected BinaryType binaryType = null;
45     
46 /*
47  * Creates a handle to a class file.
48  */

49 protected ClassFile(PackageFragment parent, String JavaDoc nameWithoutExtension) {
50     super(parent);
51     this.name = nameWithoutExtension;
52 }
53
54 /*
55  * @see IClassFile#becomeWorkingCopy(IProblemRequestor, WorkingCopyOwner, IProgressMonitor)
56  */

57 public ICompilationUnit becomeWorkingCopy(IProblemRequestor problemRequestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
58     JavaModelManager manager = JavaModelManager.getJavaModelManager();
59     CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
60     JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
61     if (perWorkingCopyInfo == null) {
62         // close cu and its children
63
close();
64
65         BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
66         operation.runOperation(monitor);
67         
68         return workingCopy;
69     }
70     return perWorkingCopyInfo.workingCopy;
71 }
72
73 /**
74  * Creates the children elements for this class file adding the resulting
75  * new handles and info objects to the newElements table. Returns true
76  * if successful, or false if an error is encountered parsing the class file.
77  *
78  * @see Openable
79  * @see Signature
80  */

81 protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map JavaDoc newElements, IResource underlyingResource) throws JavaModelException {
82     // check whether the class file can be opened
83
IStatus status = validateClassFile();
84     if (!status.isOK()) throw newJavaModelException(status);
85     if (underlyingResource != null && !underlyingResource.isAccessible()) throw newNotPresentException();
86
87     IBinaryType typeInfo = getBinaryTypeInfo((IFile) underlyingResource);
88     if (typeInfo == null) {
89         // The structure of a class file is unknown if a class file format errors occurred
90
//during the creation of the diet class file representative of this ClassFile.
91
info.setChildren(new IJavaElement[] {});
92         return false;
93     }
94
95     // Make the type
96
IType type = getType();
97     info.setChildren(new IJavaElement[] {type});
98     newElements.put(type, typeInfo);
99     
100     // Read children
101
((ClassFileInfo) info).readBinaryChildren(this, (HashMap JavaDoc) newElements, typeInfo);
102     
103     return true;
104 }
105 /**
106  * @see ICodeAssist#codeComplete(int, ICompletionRequestor)
107  * @deprecated
108  */

109 public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException {
110     codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
111 }
112 /**
113  * @see ICodeAssist#codeComplete(int, ICompletionRequestor, WorkingCopyOwner)
114  * @deprecated
115  */

116 public void codeComplete(int offset, ICompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
117     if (requestor == null) {
118         throw new IllegalArgumentException JavaDoc("Completion requestor cannot be null"); //$NON-NLS-1$
119
}
120     codeComplete(offset, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), owner);
121 }
122
123 /* (non-Javadoc)
124  * @see org.eclipse.jdt.core.ICodeAssist#codeComplete(int, org.eclipse.jdt.core.CompletionRequestor)
125  */

126 public void codeComplete(int offset, CompletionRequestor requestor) throws JavaModelException {
127     codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
128 }
129
130 /* (non-Javadoc)
131  * @see org.eclipse.jdt.core.ICodeAssist#codeComplete(int, org.eclipse.jdt.core.CompletionRequestor, org.eclipse.jdt.core.WorkingCopyOwner)
132  */

133 public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
134     String JavaDoc source = getSource();
135     if (source != null) {
136         BinaryType type = (BinaryType) getType();
137         BasicCompilationUnit cu =
138             new BasicCompilationUnit(
139                 getSource().toCharArray(),
140                 null,
141                 type.sourceFileName((IBinaryType) type.getElementInfo()),
142                 getJavaProject()); // use project to retrieve corresponding .java IFile
143
codeComplete(cu, cu, offset, requestor, owner);
144     }
145 }
146
147 /**
148  * @see ICodeAssist#codeSelect(int, int)
149  */

150 public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
151     return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY);
152 }
153 /**
154  * @see ICodeAssist#codeSelect(int, int, WorkingCopyOwner)
155  */

156 public IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) throws JavaModelException {
157     IBuffer buffer = getBuffer();
158     char[] contents;
159     if (buffer != null && (contents = buffer.getCharacters()) != null) {
160         BinaryType type = (BinaryType) getType();
161         BasicCompilationUnit cu = new BasicCompilationUnit(contents, null, type.sourceFileName((IBinaryType) type.getElementInfo()));
162         return super.codeSelect(cu, offset, length, owner);
163     } else {
164         //has no associated souce
165
return new IJavaElement[] {};
166     }
167 }
168 /**
169  * Returns a new element info for this element.
170  */

171 protected Object JavaDoc createElementInfo() {
172     return new ClassFileInfo();
173 }
174 public boolean equals(Object JavaDoc o) {
175     if (!(o instanceof ClassFile)) return false;
176     ClassFile other = (ClassFile) o;
177     return this.name.equals(other.name) && this.parent.equals(other.parent);
178 }
179 public boolean exists() {
180     return super.exists() && validateClassFile().isOK();
181 }
182 public boolean existsUsingJarTypeCache() {
183     if (getPackageFragmentRoot().isArchive()) {
184         JavaModelManager manager = JavaModelManager.getJavaModelManager();
185         IType type = getType();
186         Object JavaDoc info = manager.getInfo(type);
187         if (info == JavaModelCache.NON_EXISTING_JAR_TYPE_INFO)
188             return false;
189         else if (info != null)
190             return true;
191         // info is null
192
JavaElementInfo parentInfo = (JavaElementInfo) manager.getInfo(getParent());
193         if (parentInfo != null) {
194             // if parent is open, this class file must be in its children
195
IJavaElement[] children = parentInfo.getChildren();
196             for (int i = 0, length = children.length; i < length; i++) {
197                 if (this.name.equals(((ClassFile) children[i]).name))
198                     return true;
199             }
200             return false;
201         }
202         try {
203             info = getJarBinaryTypeInfo((PackageFragment) getParent());
204         } catch (CoreException e) {
205             // leave info null
206
} catch (IOException JavaDoc e) {
207             // leave info null
208
} catch (ClassFormatException e) {
209             // leave info null
210
}
211         manager.putJarTypeInfo(type, info == null ? JavaModelCache.NON_EXISTING_JAR_TYPE_INFO : info);
212         return info != null;
213     } else
214         return exists();
215 }
216
217 /**
218  * Finds the deepest <code>IJavaElement</code> in the hierarchy of
219  * <code>elt</elt>'s children (including <code>elt</code> itself)
220  * which has a source range that encloses <code>position</code>
221  * according to <code>mapper</code>.
222  */

223 protected IJavaElement findElement(IJavaElement elt, int position, SourceMapper mapper) {
224     SourceRange range = mapper.getSourceRange(elt);
225     if (range == null || position < range.getOffset() || range.getOffset() + range.getLength() - 1 < position) {
226         return null;
227     }
228     if (elt instanceof IParent) {
229         try {
230             IJavaElement[] children = ((IParent) elt).getChildren();
231             for (int i = 0; i < children.length; i++) {
232                 IJavaElement match = findElement(children[i], position, mapper);
233                 if (match != null) {
234                     return match;
235                 }
236             }
237         } catch (JavaModelException npe) {
238             // elt doesn't exist: return the element
239
}
240     }
241     return elt;
242 }
243 /**
244  * @see ITypeRoot#findPrimaryType()
245  */

246 public IType findPrimaryType() {
247     IType primaryType= getType();
248     if (primaryType.exists()) {
249         return primaryType;
250     }
251     return null;
252 }
253 public String JavaDoc getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
254     return this.getType().getAttachedJavadoc(monitor);
255 }
256 /**
257  * Returns the <code>ClassFileReader</code>specific for this IClassFile, based
258  * on its underlying resource, or <code>null</code> if unable to create
259  * the diet class file.
260  * There are two cases to consider:<ul>
261  * <li>a class file corresponding to an IFile resource</li>
262  * <li>a class file corresponding to a zip entry in a JAR</li>
263  * </ul>
264  *
265  * @exception JavaModelException when the IFile resource or JAR is not available
266  * or when this class file is not present in the JAR
267  */

268 public IBinaryType getBinaryTypeInfo(IFile file) throws JavaModelException {
269     JavaElement pkg = (JavaElement) getParent();
270     if (pkg instanceof JarPackageFragment) {
271         try {
272             IBinaryType info = getJarBinaryTypeInfo((PackageFragment) pkg);
273             if (info == null) {
274                 throw newNotPresentException();
275             }
276             return info;
277         } catch (ClassFormatException cfe) {
278             //the structure remains unknown
279
if (JavaCore.getPlugin().isDebugging()) {
280                 cfe.printStackTrace(System.err);
281             }
282             return null;
283         } catch (IOException JavaDoc ioe) {
284             throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
285         } catch (CoreException e) {
286             if (e instanceof JavaModelException) {
287                 throw (JavaModelException)e;
288             } else {
289                 throw new JavaModelException(e);
290             }
291         }
292     } else {
293         byte[] contents = Util.getResourceContentsAsByteArray(file);
294         try {
295             return new ClassFileReader(contents, file.getFullPath().toString().toCharArray(), true/*fully initialize so as to not keep a reference to the byte array*/);
296         } catch (ClassFormatException cfe) {
297             //the structure remains unknown
298
return null;
299         }
300     }
301 }
302
303 public byte[] getBytes() throws JavaModelException {
304     JavaElement pkg = (JavaElement) getParent();
305     if (pkg instanceof JarPackageFragment) {
306         JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
307         ZipFile JavaDoc zip = null;
308         try {
309             zip = root.getJar();
310             String JavaDoc entryName = Util.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
311             ZipEntry JavaDoc ze = zip.getEntry(entryName);
312             if (ze != null) {
313                 return org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
314             }
315             throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
316         } catch (IOException JavaDoc ioe) {
317             throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
318         } catch (CoreException e) {
319             if (e instanceof JavaModelException) {
320                 throw (JavaModelException)e;
321             } else {
322                 throw new JavaModelException(e);
323             }
324         } finally {
325             JavaModelManager.getJavaModelManager().closeZipFile(zip);
326         }
327     } else {
328         IFile file = (IFile) getResource();
329         return Util.getResourceContentsAsByteArray(file);
330     }
331 }
332 private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg) throws CoreException, IOException JavaDoc, ClassFormatException {
333     JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
334     ZipFile JavaDoc zip = null;
335     try {
336         zip = root.getJar();
337         String JavaDoc entryName = Util.concatWith(pkg.names, getElementName(), '/');
338         ZipEntry JavaDoc ze = zip.getEntry(entryName);
339         if (ze != null) {
340             byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
341             String JavaDoc fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName;
342             return new ClassFileReader(contents, fileName.toCharArray(), true/*fully initialize so as to not keep a reference to the byte array*/);
343         }
344     } finally {
345         JavaModelManager.getJavaModelManager().closeZipFile(zip);
346     }
347     return null;
348 }
349 public IBuffer getBuffer() throws JavaModelException {
350     IStatus status = validateClassFile();
351     if (status.isOK()) {
352         return super.getBuffer();
353     } else {
354         // .class file not on classpath, create a new buffer to be nice (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=41444)
355
Object JavaDoc info = ((ClassFile) getClassFile()).getBinaryTypeInfo((IFile) getResource());
356         IBuffer buffer = openBuffer(null, info);
357         if (buffer != null && !(buffer instanceof NullBuffer))
358             return buffer;
359         if (status.getCode() == IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH)
360             return null; // don't throw a JavaModelException to be able to open .class file outside the classpath (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138507)
361
throw new JavaModelException((IJavaModelStatus) status);
362     }
363 }
364 /**
365  * @see IMember
366  */

367 public IClassFile getClassFile() {
368     return this;
369 }
370 /**
371  * @see IMember#getTypeRoot()
372  */

373 public ITypeRoot getTypeRoot() {
374     return this;
375 }
376 /**
377  * A class file has a corresponding resource unless it is contained
378  * in a jar.
379  *
380  * @see IJavaElement
381  */

382 public IResource getCorrespondingResource() throws JavaModelException {
383     IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
384     if (root.isArchive()) {
385         return null;
386     } else {
387         return getUnderlyingResource();
388     }
389 }
390 /**
391  * @see IClassFile
392  */

393 public IJavaElement getElementAt(int position) throws JavaModelException {
394     IJavaElement parentElement = getParent();
395     while (parentElement.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) {
396         parentElement = parentElement.getParent();
397     }
398     PackageFragmentRoot root = (PackageFragmentRoot) parentElement;
399     SourceMapper mapper = root.getSourceMapper();
400     if (mapper == null) {
401         return null;
402     } else {
403         // ensure this class file's buffer is open so that source ranges are computed
404
getBuffer();
405
406         IType type = getType();
407         return findElement(type, position, mapper);
408     }
409 }
410 public IJavaElement getElementAtConsideringSibling(int position) throws JavaModelException {
411     IPackageFragment fragment = (IPackageFragment)getParent();
412     PackageFragmentRoot root = (PackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
413     SourceMapper mapper = root.getSourceMapper();
414     if (mapper == null) {
415         return null;
416     } else {
417         int index = this.name.indexOf('$');
418         int prefixLength = index < 0 ? this.name.length() : index;
419         
420         IType type = null;
421         int start = -1;
422         int end = Integer.MAX_VALUE;
423         IJavaElement[] children = fragment.getChildren();
424         for (int i = 0; i < children.length; i++) {
425             String JavaDoc childName = children[i].getElementName();
426             
427             int childIndex = childName.indexOf('$');
428             int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex;
429             if (prefixLength == childPrefixLength && this.name.regionMatches(0, childName, 0, prefixLength)) {
430                 IClassFile classFile = (IClassFile) children[i];
431                 
432                 // ensure this class file's buffer is open so that source ranges are computed
433
classFile.getBuffer();
434                 
435                 SourceRange range = mapper.getSourceRange(classFile.getType());
436                 if (range == SourceMapper.UNKNOWN_RANGE) continue;
437                 int newStart = range.offset;
438                 int newEnd = newStart + range.length - 1;
439                 if(newStart > start && newEnd < end
440                         && newStart <= position && newEnd >= position) {
441                     type = classFile.getType();
442                     start = newStart;
443                     end = newEnd;
444                 }
445             }
446         }
447         if(type != null) {
448             return findElement(type, position, mapper);
449         }
450         return null;
451     }
452 }
453 public String JavaDoc getElementName() {
454     return this.name + SuffixConstants.SUFFIX_STRING_class;
455 }
456 /**
457  * @see IJavaElement
458  */

459 public int getElementType() {
460     return CLASS_FILE;
461 }
462 /*
463  * @see JavaElement
464  */

465 public IJavaElement getHandleFromMemento(String JavaDoc token, MementoTokenizer memento, WorkingCopyOwner owner) {
466     switch (token.charAt(0)) {
467         case JEM_TYPE:
468             if (!memento.hasMoreTokens()) return this;
469             String JavaDoc typeName = memento.nextToken();
470             JavaElement type = new BinaryType(this, typeName);
471             return type.getHandleFromMemento(memento, owner);
472     }
473     return null;
474 }
475 /**
476  * @see JavaElement#getHandleMemento()
477  */

478 protected char getHandleMementoDelimiter() {
479     return JavaElement.JEM_CLASSFILE;
480 }
481 /*
482  * @see IJavaElement
483  */

484 public IPath getPath() {
485     PackageFragmentRoot root = getPackageFragmentRoot();
486     if (root.isArchive()) {
487         return root.getPath();
488     } else {
489         return getParent().getPath().append(getElementName());
490     }
491 }
492 /*
493  * @see IJavaElement
494  */

495 public IResource getResource() {
496     PackageFragmentRoot root = this.getPackageFragmentRoot();
497     if (root.isArchive()) {
498         return root.getResource();
499     } else {
500         return ((IContainer)this.getParent().getResource()).getFile(new Path(this.getElementName()));
501     }
502 }
503 /**
504  * @see ISourceReference
505  */

506 public String JavaDoc getSource() throws JavaModelException {
507     IBuffer buffer = getBuffer();
508     if (buffer == null) {
509         return null;
510     }
511     return buffer.getContents();
512 }
513 /**
514  * @see ISourceReference
515  */

516 public ISourceRange getSourceRange() throws JavaModelException {
517     IBuffer buffer = getBuffer();
518     if (buffer != null) {
519         String JavaDoc contents = buffer.getContents();
520         if (contents == null) return null;
521         return new SourceRange(0, contents.length());
522     } else {
523         return null;
524     }
525 }
526 /*
527  * Returns the name of the toplevel type of this class file.
528  */

529 public String JavaDoc getTopLevelTypeName() {
530     String JavaDoc topLevelTypeName = getElementName();
531     int firstDollar = topLevelTypeName.indexOf('$');
532     if (firstDollar != -1) {
533         topLevelTypeName = topLevelTypeName.substring(0, firstDollar);
534     } else {
535         topLevelTypeName = topLevelTypeName.substring(0, topLevelTypeName.length()-SUFFIX_CLASS.length);
536     }
537     return topLevelTypeName;
538 }
539 /**
540  * @see IClassFile
541  */

542 public IType getType() {
543     if (this.binaryType == null) {
544         this.binaryType = new BinaryType(this, getTypeName());
545     }
546     return this.binaryType;
547 }
548 public String JavaDoc getTypeName() {
549     // Internal class file name doesn't contain ".class" file extension
550
int lastDollar = this.name.lastIndexOf('$');
551     return lastDollar > -1 ? Util.localTypeName(this.name, lastDollar, this.name.length()) : this.name;
552 }
553 /*
554  * @see IClassFile
555  */

556 public ICompilationUnit getWorkingCopy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
557     CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
558     JavaModelManager manager = JavaModelManager.getJavaModelManager();
559     JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
560         manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
561     if (perWorkingCopyInfo != null) {
562         return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
563
}
564     BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, null);
565     op.runOperation(monitor);
566     return workingCopy;
567 }
568 /**
569  * @see IClassFile
570  * @deprecated
571  */

572 public IJavaElement getWorkingCopy(IProgressMonitor monitor, org.eclipse.jdt.core.IBufferFactory factory) throws JavaModelException {
573     return getWorkingCopy(BufferFactoryWrapper.create(factory), monitor);
574 }
575 /**
576  * @see Openable
577  */

578 protected boolean hasBuffer() {
579     return true;
580 }
581 public int hashCode() {
582     return Util.combineHashCodes(this.name.hashCode(), this.parent.hashCode());
583 }
584 /**
585  * @see IClassFile
586  */

587 public boolean isClass() throws JavaModelException {
588     return getType().isClass();
589 }
590 /**
591  * @see IClassFile
592  */

593 public boolean isInterface() throws JavaModelException {
594     return getType().isInterface();
595 }
596 /**
597  * Returns true - class files are always read only.
598  */

599 public boolean isReadOnly() {
600     return true;
601 }
602 private IStatus validateClassFile() {
603     IPackageFragmentRoot root = getPackageFragmentRoot();
604     try {
605         if (root.getKind() != IPackageFragmentRoot.K_BINARY)
606             return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
607     } catch (JavaModelException e) {
608         return e.getJavaModelStatus();
609     }
610     IJavaProject project = getJavaProject();
611     return JavaConventions.validateClassFileName(getElementName(), project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
612 }
613 /**
614  * Opens and returns buffer on the source code associated with this class file.
615  * Maps the source code to the children elements of this class file.
616  * If no source code is associated with this class file,
617  * <code>null</code> is returned.
618  *
619  * @see Openable
620  */

621 protected IBuffer openBuffer(IProgressMonitor pm, Object JavaDoc info) throws JavaModelException {
622     SourceMapper mapper = getSourceMapper();
623     if (mapper != null) {
624         return mapSource(mapper, info instanceof IBinaryType ? (IBinaryType) info : null);
625     }
626     return null;
627 }
628 private IBuffer mapSource(SourceMapper mapper, IBinaryType info) {
629     char[] contents = mapper.findSource(getType(), info);
630     if (contents != null) {
631         // create buffer
632
IBuffer buffer = BufferManager.createBuffer(this);
633         if (buffer == null) return null;
634         BufferManager bufManager = getBufferManager();
635         bufManager.addBuffer(buffer);
636
637         // set the buffer source
638
if (buffer.getCharacters() == null){
639             buffer.setContents(contents);
640         }
641
642         // listen to buffer changes
643
buffer.addBufferChangedListener(this);
644
645         // do the source mapping
646
mapper.mapSource(getType(), contents, info);
647
648         return buffer;
649     } else {
650         // create buffer
651
IBuffer buffer = BufferManager.createNullBuffer(this);
652         if (buffer == null) return null;
653         BufferManager bufManager = getBufferManager();
654         bufManager.addBuffer(buffer);
655
656         // listen to buffer changes
657
buffer.addBufferChangedListener(this);
658         return buffer;
659     }
660 }
661 /* package */ static String JavaDoc simpleName(char[] className) {
662     if (className == null)
663         return null;
664     String JavaDoc simpleName = new String JavaDoc(unqualifiedName(className));
665     int lastDollar = simpleName.lastIndexOf('$');
666     if (lastDollar != -1)
667         return Util.localTypeName(simpleName, lastDollar, simpleName.length());
668     else
669         return simpleName;
670 }
671 /**
672  * Returns the Java Model representation of the given name
673  * which is provided in diet class file format, or <code>null</code>
674  * if the given name is <code>null</code>.
675  *
676  * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
677  * and corresponding Java Model format is "java.lang.Object".
678  */

679
680 public static char[] translatedName(char[] name) {
681     if (name == null)
682         return null;
683     int nameLength = name.length;
684     char[] newName= new char[nameLength];
685     for (int i= 0; i < nameLength; i++) {
686         if (name[i] == '/') {
687             newName[i]= '.';
688         } else {
689             newName[i]= name[i];
690         }
691     }
692     return newName;
693 }
694 /**
695  * Returns the Java Model representation of the given names
696  * which are provided in diet class file format, or <code>null</code>
697  * if the given names are <code>null</code>.
698  *
699  * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
700  * and corresponding Java Model format is "java.lang.Object".
701  */

702
703 /* package */ static char[][] translatedNames(char[][] names) {
704     if (names == null)
705         return null;
706     int length = names.length;
707     char[][] newNames = new char[length][];
708     for(int i = 0; i < length; i++) {
709         newNames[i] = translatedName(names[i]);
710     }
711     return newNames;
712 }
713 /**
714  * Returns the Java Model format of the unqualified class name for the
715  * given className which is provided in diet class file format,
716  * or <code>null</code> if the given className is <code>null</code>.
717  * (This removes the package name, but not enclosing type names).
718  *
719  * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
720  * and corresponding Java Model simple name format is "Object".
721  */

722
723 /* package */ static char[] unqualifiedName(char[] className) {
724     if (className == null)
725         return null;
726     int count = 0;
727     for (int i = className.length - 1; i > -1; i--) {
728         if (className[i] == '/') {
729             char[] name = new char[count];
730             System.arraycopy(className, i + 1, name, 0, count);
731             return name;
732         }
733         count++;
734     }
735     return className;
736 }
737
738 /**
739  * @see ICodeAssist#codeComplete(int, ICodeCompletionRequestor)
740  * @deprecated - should use codeComplete(int, ICompletionRequestor) instead
741  */

742 public void codeComplete(int offset, final org.eclipse.jdt.core.ICodeCompletionRequestor requestor) throws JavaModelException {
743     
744     if (requestor == null){
745         codeComplete(offset, (ICompletionRequestor)null);
746         return;
747     }
748     codeComplete(
749         offset,
750         new ICompletionRequestor(){
751             public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName, char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
752                 // ignore
753
}
754             public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
755                 requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
756             }
757             public void acceptError(IProblem error) {
758                 // was disabled in 1.0
759
}
760             public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
761                 requestor.acceptField(declaringTypePackageName, declaringTypeName, fieldName, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
762             }
763             public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
764                 requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
765             }
766             public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
767                 requestor.acceptKeyword(keywordName, completionStart, completionEnd);
768             }
769             public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
770                 requestor.acceptLabel(labelName, completionStart, completionEnd);
771             }
772             public void acceptLocalVariable(char[] localVarName,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
773                 // ignore
774
}
775             public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
776                 // skip parameter names
777
requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
778             }
779             public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
780                 // ignore
781
}
782             public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
783                 requestor.acceptModifier(modifierName, completionStart, completionEnd);
784             }
785             public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
786                 requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
787             }
788             public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
789                 requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
790             }
791             public void acceptVariableName(char[] typePackageName,char[] typeName,char[] varName,char[] completionName,int completionStart,int completionEnd, int relevance){
792                 // ignore
793
}
794         });
795 }
796 }
797
Popular Tags