Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2000, 2013 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: IBM Corporation - initial API and implementation /
 
 package org.eclipse.jdt.internal.core;
 
 import java.net.URL;
 
 import  org.eclipse.core.resources.IResource;
 import  org.eclipse.core.runtime.*;
 import  org.eclipse.core.runtime.jobs.ISchedulingRule;
Root of Java element handle hierarchy.

See also:
IJavaElement
 
 public abstract class JavaElement extends PlatformObject implements IJavaElement {
 //	private static final QualifiedName PROJECT_JAVADOC= new QualifiedName(JavaCore.PLUGIN_ID, "project_javadoc_location"); //$NON-NLS-1$
 
 	private static final byte[] CLOSING_DOUBLE_QUOTE = new byte[] { 34 };
 	/* To handle the pre - HTML 5 format: <META http-equiv="Content-Type" content="text/html; charset=UTF-8">  */
 	private static final byte[] CHARSET = new byte[] { 99, 104, 97, 114, 115, 101, 116, 61 };
 	/* To handle the HTML 5 format: <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> */
 	private static final byte[] CHARSET_HTML5 = new byte[] { 99, 104, 97, 114, 115, 101, 116, 61, 34 };
 	private static final byte[] META_START = new byte[] { 60, 109, 101, 116, 97 };
 	private static final byte[] META_END = new byte[] { 34, 62 };
 	public static final char JEM_ESCAPE = '\\';
 	public static final char JEM_JAVAPROJECT = '=';
 	public static final char JEM_PACKAGEFRAGMENTROOT = '/';
 	public static final char JEM_PACKAGEFRAGMENT = '<';
 	public static final char JEM_FIELD = '^';
 	public static final char JEM_METHOD = '~';
 	public static final char JEM_INITIALIZER = '|';
 	public static final char JEM_COMPILATIONUNIT = '{';
 	public static final char JEM_CLASSFILE = '(';
 	public static final char JEM_TYPE = '[';
 	public static final char JEM_PACKAGEDECLARATION = '%';
 	public static final char JEM_IMPORTDECLARATION = '#';
 	public static final char JEM_COUNT = '!';
 	public static final char JEM_LOCALVARIABLE = '@';
 	public static final char JEM_TYPE_PARAMETER = ']';
 	public static final char JEM_ANNOTATION = '}';

This element's parent, or null if this element does not have a parent.
 
 	protected JavaElement parent;
 
 	protected static final JavaElement[] NO_ELEMENTS = new JavaElement[0];
 	protected static final Object NO_INFO = new Object();

Constructs a handle for a java element with the given parent element.

Parameters:
parent The parent of java element
Throws:
IllegalArgumentException if the type is not one of the valid Java element type constants
 
 	protected JavaElement(JavaElement parentthrows IllegalArgumentException {
 		this. = parent;
 	}

See also:
IOpenable
 
 	public void close() throws JavaModelException {
 		JavaModelManager.getJavaModelManager().removeInfoAndChildren(this);
 	}
This element is being closed. Do any necessary cleanup.
	protected abstract void closing(Object infothrows JavaModelException;
	/*
	 * Returns a new element info for this element.
	 */
	protected abstract Object createElementInfo();
Returns true if this handle represents the same Java element as the given handle. By default, two handles represent the same element if they are identical or if they represent the same type of element, have equal names, parents, and occurrence counts.

If a subclass has other requirements for equality, this method must be overridden.

See also:
Object.equals
	public boolean equals(Object o) {
		if (this == oreturn true;
		// Java model parent is null
		if (this. == nullreturn super.equals(o);
		// assume instanceof check is done in subclass
		JavaElement other = (JavaElemento;
		return getElementName().equals(other.getElementName()) &&
				this..equals(other.parent);
	}
	protected void escapeMementoName(StringBuffer bufferString mementoName) {
		for (int i = 0, length = mementoName.length(); i < lengthi++) {
			char character = mementoName.charAt(i);
			switch (character) {
				case :
				case :
				case :
			}
			buffer.append(character);
		}
	}

See also:
IJavaElement
	public boolean exists() {
		try {
			return true;
catch (JavaModelException e) {
			// element doesn't exist: return false
		}
		return false;
	}

Returns the ASTNode that corresponds to this JavaElement or null if there is no corresponding node.
		return null// works only inside a compilation unit
	}
Generates the element infos for this element, its ancestors (if they are not opened) and its children (if it is an Openable). Puts the newly created element info in the given map.
	protected abstract void generateInfos(Object infoHashMap newElements, IProgressMonitor pmthrows JavaModelException;

See also:
IJavaElement
	public IJavaElement getAncestor(int ancestorType) {
		IJavaElement element = this;
		while (element != null) {
			if (element.getElementType() == ancestorType)  return element;
			elementelement.getParent();
		}
		return null;
	}

See also:
IParent
		Object elementInfo = getElementInfo();
		if (elementInfo instanceof JavaElementInfo) {
			return ((JavaElementInfo)elementInfo).getChildren();
else {
			return ;
		}
	}
Returns a collection of (immediate) children of this node of the specified type.

Parameters:
type - one of the JEM_* constants defined by JavaElement
	public ArrayList getChildrenOfType(int typethrows JavaModelException {
		IJavaElement[] children = getChildren();
		int size = children.length;
		ArrayList list = new ArrayList(size);
		for (int i = 0; i < size; ++i) {
			JavaElement elt = (JavaElement)children[i];
			if (elt.getElementType() == type) {
				list.add(elt);
			}
		}
		return list;
	}

See also:
IMember
		return null;
	}

See also:
IMember
		return null;
	}
Returns the info for this handle. If this element is not already open, it and all of its parents are opened. Does not return null. NOTE: BinaryType infos are NOT rooted under JavaElementInfo.

Throws:
JavaModelException if the element is not present or not accessible
		return getElementInfo(null);
	}
Returns the info for this handle. If this element is not already open, it and all of its parents are opened. Does not return null. NOTE: BinaryType infos are NOT rooted under JavaElementInfo.

Throws:
JavaModelException if the element is not present or not accessible
	public Object getElementInfo(IProgressMonitor monitorthrows JavaModelException {
		JavaModelManager manager = JavaModelManager.getJavaModelManager();
		Object info = manager.getInfo(this);
		if (info != nullreturn info;
		return openWhenClosed(createElementInfo(), falsemonitor);
	}

See also:
IAdaptable
	public String getElementName() {
		return ""//$NON-NLS-1$
	}
	/*
	 * Creates a Java element handle from the given memento.
	 * The given token is the current delimiter indicating the type of the next token(s).
	 * The given working copy owner is used only for compilation unit handles.
	 */
	public abstract IJavaElement getHandleFromMemento(String tokenMementoTokenizer mementoWorkingCopyOwner owner);
	/*
	 * Creates a Java element handle from the given memento.
	 * The given working copy owner is used only for compilation unit handles.
	 */
		if (!memento.hasMoreTokens()) return this;
		String token = memento.nextToken();
		return getHandleFromMemento(tokenmementoowner);
	}

See also:
IJavaElement
	}

See also:
JavaElement.getHandleMemento()
		StringBuffer buff = new StringBuffer();
		return buff.toString();
	}
	protected void getHandleMemento(StringBuffer buff) {
	}
Returns the char that marks the start of this handles contribution to a memento.
	protected abstract char getHandleMementoDelimiter();

See also:
IJavaElement
		IJavaElement current = this;
		do {
			if (current instanceof IJavaModelreturn (IJavaModelcurrent;
while ((current = current.getParent()) != null);
		return null;
	}

See also:
IJavaElement
		IJavaElement current = this;
		do {
			if (current instanceof IJavaProjectreturn (IJavaProjectcurrent;
while ((current = current.getParent()) != null);
		return null;
	}
	/*
	 * @see IJavaElement
	 */
	public IOpenable getOpenable() {
	}
Return the first instance of IOpenable in the parent hierarchy of this element.

Subclasses that are not IOpenable's must override this method.

		return (IOpenable)this.;
	}

See also:
IJavaElement
	public IJavaElement getParent() {
		return this.;
	}
	/*
	 * @see IJavaElement#getPrimaryElement()
	 */
		return getPrimaryElement(true);
	}
	/*
	 * Returns the primary element. If checkOwner, and the cu owner is primary,
	 * return this element.
	 */
	public IJavaElement getPrimaryElement(boolean checkOwner) {
		return this;
	}
	public IResource getResource() {
		return resource();
	}
	public abstract IResource resource();
Returns the element that is located at the given source position in this element. This is a helper method for ICompilationUnit#getElementAt, and only works on compilation units and types. The position given is known to be within this element's source range already, and if no finer grained element is found at the position, this element is returned.
	protected IJavaElement getSourceElementAt(int positionthrows JavaModelException {
		if (this instanceof ISourceReference) {
			IJavaElement[] children = getChildren();
			for (int i = children.length-1; i >= 0; i--) {
				IJavaElement aChild = children[i];
				if (aChild instanceof SourceRefElement) {
					SourceRefElement child = (SourceRefElementchildren[i];
					ISourceRange range = child.getSourceRange();
					int start = range.getOffset();
					int end = start + range.getLength();
					if (start <= position && position <= end) {
						if (child instanceof IField) {
							// check muti-declaration case (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943)
							int declarationStart = start;
							SourceRefElement candidate = null;
							do {
								// check name range
								range = ((IField)child).getNameRange();
								if (position <= range.getOffset() + range.getLength()) {
									candidate = child;
else {
									return candidate == null ? child.getSourceElementAt(position) : candidate.getSourceElementAt(position);
								}
								child = --i>=0 ? (SourceRefElementchildren[i] : null;
while (child != null && child.getSourceRange().getOffset() == declarationStart);
							// position in field's type: use first field
							return candidate.getSourceElementAt(position);
else if (child instanceof IParent) {
							return child.getSourceElementAt(position);
else {
							return child;
						}
					}
				}
			}
else {
			// should not happen
			Assert.isTrue(false);
		}
		return this;
	}
Returns the SourceMapper facility for this element, or null if this element does not have a SourceMapper.
	}
	/* (non-Javadoc)
	 * @see org.eclipse.jdt.core.IJavaElement#getSchedulingRule()
	 */
	public ISchedulingRule getSchedulingRule() {
		IResource resource = resource();
		if (resource == null) {
			class NoResourceSchedulingRule implements ISchedulingRule {
				public IPath path;
				public NoResourceSchedulingRule(IPath path) {
					this. = path;
				}
				public boolean contains(ISchedulingRule rule) {
					if (rule instanceof NoResourceSchedulingRule) {
						return this..isPrefixOf(((NoResourceSchedulingRule)rule).);
else {
						return false;
					}
				}
				public boolean isConflicting(ISchedulingRule rule) {
					if (rule instanceof NoResourceSchedulingRule) {
						IPath otherPath = ((NoResourceSchedulingRule)rule).;
						return this..isPrefixOf(otherPath) || otherPath.isPrefixOf(this.);
else {
						return false;
					}
				}
			}
else {
			return resource;
		}
	}

See also:
IParent
	public boolean hasChildren() throws JavaModelException {
		// if I am not open, return true to avoid opening (case of a Java project, a compilation unit or a class file).
		// also see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
		Object elementInfo = JavaModelManager.getJavaModelManager().getInfo(this);
		if (elementInfo instanceof JavaElementInfo) {
			return ((JavaElementInfo)elementInfo).getChildren().length > 0;
else {
			return true;
		}
	}

Returns the hash code for this Java element. By default, the hash code for an element is a combination of its name and parent's hash code. Elements with other requirements must override this method.
	public int hashCode() {
		if (this. == nullreturn super.hashCode();
	}
Returns true if this element is an ancestor of the given element, otherwise false.
	public boolean isAncestorOf(IJavaElement e) {
		IJavaElement parentElemente.getParent();
		while (parentElement != null && !parentElement.equals(this)) {
			parentElementparentElement.getParent();
		}
		return parentElement != null;
	}

See also:
IJavaElement
	public boolean isReadOnly() {
		return false;
	}
Creates and returns a new not present exception for this element.
	}
	}
Creates and returns a new Java model exception for this element with the given status.
	public JavaModelException newJavaModelException(IStatus status) {
		if (status instanceof IJavaModelStatus)
			return new JavaModelException((IJavaModelStatusstatus);
		else
			return new JavaModelException(new JavaModelStatus(status.getSeverity(), status.getCode(), status.getMessage()));
	}
	/*
	 * Opens an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
	 * Returns the created element info.
	 */
	protected Object openWhenClosed(Object infoboolean forceAdd, IProgressMonitor monitorthrows JavaModelException {
		JavaModelManager manager = JavaModelManager.getJavaModelManager();
		boolean hadTemporaryCache = manager.hasTemporaryCache();
		try {
			HashMap newElements = manager.getTemporaryCache();
			generateInfos(infonewElementsmonitor);
			if (info == null) {
				info = newElements.get(this);
			}
			if (info == null) { // a source ref element could not be opened
				// close the buffer that was opened for the openable parent
			    // close only the openable's buffer (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62854)
			    Openable openable = (OpenablegetOpenable();
			    if (newElements.containsKey(openable)) {
			        openable.closeBuffer();
			    }
			}
			if (!hadTemporaryCache) {
				info = manager.putInfos(thisinfoforceAddnewElements);
			}
finally {
			if (!hadTemporaryCache) {
			}
		}
		return info;
	}
	public String readableName() {
		return getElementName();
	}
	public JavaElement resolved(Binding binding) {
		return this;
	}
	public JavaElement unresolved() {
		return this;
	}
	protected String tabString(int tab) {
		StringBuffer buffer = new StringBuffer();
		for (int i = tabi > 0; i--)
			buffer.append("  "); //$NON-NLS-1$
		return buffer.toString();
	}
Debugging purposes
	public String toDebugString() {
		StringBuffer buffer = new StringBuffer();
		this.toStringInfo(0, buffertrue/*show resolved info*/);
		return buffer.toString();
	}
Debugging purposes
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		toString(0, buffer);
		return buffer.toString();
	}
Debugging purposes
	protected void toString(int tabStringBuffer buffer) {
		Object info = this.toStringInfo(tabbuffer);
		if (tab == 0) {
		}
		toStringChildren(tabbufferinfo);
	}
Debugging purposes
		return toStringWithAncestors(true/*show resolved info*/);
	}
Debugging purposes
	public String toStringWithAncestors(boolean showResolvedInfo) {
		StringBuffer buffer = new StringBuffer();
		this.toStringInfo(0, buffershowResolvedInfo);
		return buffer.toString();
	}
Debugging purposes
	protected void toStringAncestors(StringBuffer buffer) {
		JavaElement parentElement = (JavaElement)getParent();
		if (parentElement != null && parentElement.getParent() != null) {
			buffer.append(" [in "); //$NON-NLS-1$
			parentElement.toStringInfo(0, bufferfalse/*don't show resolved info*/);
			parentElement.toStringAncestors(buffer);
			buffer.append("]"); //$NON-NLS-1$
		}
	}
Debugging purposes
	protected void toStringChildren(int tabStringBuffer bufferObject info) {
		if (info == null || !(info instanceof JavaElementInfo)) return;
		IJavaElement[] children = ((JavaElementInfo)info).getChildren();
		for (int i = 0; i < children.lengthi++) {
			buffer.append("\n"); //$NON-NLS-1$
			((JavaElement)children[i]).toString(tab + 1, buffer);
		}
	}
Debugging purposes
	public Object toStringInfo(int tabStringBuffer buffer) {
		Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
		this.toStringInfo(tabbufferinfotrue/*show resolved info*/);
		return info;
	}
Debugging purposes

Parameters:
showResolvedInfo TODO
	protected void toStringInfo(int tabStringBuffer bufferObject infoboolean showResolvedInfo) {
		buffer.append(tabString(tab));
		toStringName(buffer);
		if (info == null) {
			buffer.append(" (not open)"); //$NON-NLS-1$
		}
	}
Debugging purposes
	protected void toStringName(StringBuffer buffer) {
	}
		if (root == null) {
			return null;
		}
			IClasspathEntry entrynull;
			try {
				if (url != null) {
					return url;
				}
			}
			catch(JavaModelException jme) {
				// Proceed with raw classpath
			}
			entryroot.getRawClasspathEntry();
			switch (entry.getEntryKind()) {
				default:
					return null;
			}			
		}
		return null;
	}
	protected static URL getLibraryJavadocLocation(IClasspathEntry entrythrows JavaModelException {
		switch(entry.getEntryKind()) {
				break;
			default :
				throw new IllegalArgumentException("Entry must be of kind CPE_LIBRARY or CPE_VARIABLE"); //$NON-NLS-1$
		}
		IClasspathAttribute[] extraAttributesentry.getExtraAttributes();
		for (int i= 0; i < extraAttributes.lengthi++) {
			IClasspathAttribute attribextraAttributes[i];
				String value = attrib.getValue();
				try {
					return new URL(value);
catch (MalformedURLException e) {
				}
			}
		}
		return null;
	}
	/*
	 * @see IJavaElement#getAttachedJavadoc(IProgressMonitor)
	 */
	public String getAttachedJavadoc(IProgressMonitor monitorthrows JavaModelException {
		return null;
	}
	int getIndexOf(byte[] arraybyte[] toBeFoundint startint end) {
		if (array == null || toBeFound == null)
			return -1;
		final int toBeFoundLength = toBeFound.length;
		final int arrayLength = (end != -1 && end < array.length) ? end : array.length;
		if (arrayLength < toBeFoundLength)
			return -1;
		loop: for (int i = startmax = arrayLength - toBeFoundLength + 1; i < maxi++) {
			if (array[i] == toBeFound[0]) {
				for (int j = 1; j < toBeFoundLengthj++) {
					if (array[i + j] != toBeFound[j])
						continue loop;
				}
				return i;
			}
		}
		return -1;
	}
	/*
	 * We don't use getContentEncoding() on the URL connection, because it might leave open streams behind.
	 * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=117890
	 */
	protected String getURLContents(String docUrlValuethrows JavaModelException {
		InputStream stream = null;
		JarURLConnection connection2 = null;
		try {
			URL docUrl = new URL(docUrlValue);
			URLConnection connection = docUrl.openConnection();
			Class[] parameterTypes = new Class[]{int.class};
			Integer timeoutVal = new Integer(10000);
			// set the connect and read timeouts using reflection since these methods are not available in java 1.4
			Class URLClass = connection.getClass();
			try {
				Method connectTimeoutMethod = URLClass.getDeclaredMethod("setConnectTimeout"parameterTypes); //$NON-NLS-1$
				Method readTimeoutMethod = URLClass.getDeclaredMethod("setReadTimeout"parameterTypes); //$NON-NLS-1$
				connectTimeoutMethod.invoke(connectionnew Object[]{timeoutVal});
				readTimeoutMethod.invoke(connectionnew Object[]{timeoutVal});
catch (SecurityException e) {
				// ignore
catch (IllegalArgumentException e) {
				// ignore
catch (NoSuchMethodException e) {
				// ignore
catch (IllegalAccessException e) {
				// ignore
catch (InvocationTargetException e) {
				// ignore
			}
			if (connection instanceof JarURLConnection) {
				connection2 = (JarURLConnectionconnection;
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=156307
				connection.setUseCaches(false);
			}
			try {
				stream = new BufferedInputStream(connection.getInputStream());
catch (IllegalArgumentException e) {
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
				return null;
catch (NullPointerException e) {
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
				return null;
			}
			String encoding = connection.getContentEncoding();
			byte[] contents = org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsByteArray(streamconnection.getContentLength());
			if (encoding == null) {
				int index = getIndexOf(contents, 0, -1);
				if (index != -1) {
					int end = getIndexOf(contentsindex, -1);
					if (end != -1) {
						if ((end + 1) <= contents.lengthend++;
						int charsetIndex = getIndexOf(contentsindexend);
						if (charsetIndex == -1) {
							charsetIndex = getIndexOf(contentsindexend);
							if (charsetIndex != -1)
								charsetIndex = charsetIndex + .;
else {
							charsetIndex = charsetIndex + .;
						}
						if (charsetIndex != -1) {
							end = getIndexOf(contentscharsetIndexend);
							encoding = new String(contentscharsetIndexend - charsetIndex.......);
						}
					}
				}
			}
			try {
				if (encoding == null) {
					encoding = getJavaProject().getProject().getDefaultCharset();
				}
catch (CoreException e) {
				// ignore
			}
			if (contents != null) {
				if (encoding != null) {
					return new String(contentsencoding);
else {
					// platform encoding is used
					return new String(contents);
				}
			}
catch (SocketTimeoutException e) {
catch (MalformedURLException e) {
catch (FileNotFoundException e) {
			// Ignore, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559 &
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=403036
catch (SocketException e) {
			// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 &
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=400060
catch (UnknownHostException e) {
			// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 &
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=400060
catch (ProtocolException e) {
			// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 &
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=400060
catch (IOException e) {
finally {
			if (stream != null) {
				try {
					stream.close();
catch (IOException e) {
					// ignore
				}
			}
			if (connection2 != null) {
				try {
					connection2.getJarFile().close();
catch(IOException e) {
					// ignore
catch(IllegalStateException e) {
					/*
					 * ignore. Can happen in case the stream.close() did close the jar file
					 * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=140750
					 */
				}
 			}
		}
		return null;
	}
New to GrepCode? Check out our FAQ X