Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#getElementAt()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getElementAt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MethodFinder.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
public IMethod convertMethodDecl2IMethod(MethodDeclaration methodDecl){
	SimpleName methodName = methodDecl.getName();
	//cu.accept(visitor);
	
	try {
		ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom((IFile) resource);
		
		int startPos = methodDecl.getStartPosition();
		IJavaElement element = iCompilationUnit.getElementAt(startPos);
		if(element instanceof IMethod) {
			return (IMethod) element;
		}
		return null;
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 2
Source File: JavadocCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private String createJavaDocTags(IDocument document, int offset, String indentation, String lineDelimiter, ICompilationUnit unit) throws CoreException, BadLocationException {
	IJavaElement element = unit.getElementAt(offset);
	if (element == null) {
		return null;
	}
	switch (element.getElementType()) {
		case IJavaElement.TYPE:
			return createTypeTags(document, offset, indentation, lineDelimiter, (IType) element);

		case IJavaElement.METHOD:
			return createMethodTags(document, offset, indentation, lineDelimiter, (IMethod) element);

		default:
			return null;
	}
}
 
Example 3
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the method which references the specified ast node.
 *
 * @param node
 *            the ast node
 * @return the referencing method
 * @throws JavaModelException
 *             if an error occurs
 */
protected final IMethod getReferencingMethod(final ASTNode node) throws JavaModelException {
	if (node instanceof Type) {
		final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
		if (parent instanceof MethodDeclaration) {
			final IMethodBinding binding= ((MethodDeclaration) parent).resolveBinding();
			if (binding != null) {
				final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(node);
				final IJavaElement element= unit.getElementAt(node.getStartPosition());
				if (element instanceof IMethod)
					return (IMethod) element;
			}
		}
	}
	return null;
}
 
Example 4
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the most narrow element including the given offset.  If <code>reconcile</code>
 * is <code>true</code> the editor's input element is reconciled in advance. If it is
 * <code>false</code> this method only returns a result if the editor's input element
 * does not need to be reconciled.
 *
 * @param offset the offset included by the retrieved element
 * @param reconcile <code>true</code> if working copy should be reconciled
 * @return the most narrow element which includes the given offset
 */
@Override
protected IJavaElement getElementAt(int offset, boolean reconcile) {
	ICompilationUnit unit= (ICompilationUnit)getInputJavaElement();

	if (unit != null) {
		try {
			if (reconcile) {
				JavaModelUtil.reconcile(unit);
				return unit.getElementAt(offset);
			} else if (unit.isConsistent())
				return unit.getElementAt(offset);

		} catch (JavaModelException x) {
			if (!x.isDoesNotExist())
			JavaPlugin.log(x.getStatus());
			// nothing found, be tolerant and go on
		}
	}

	return null;
}
 
Example 5
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the Javadoc tags for newly inserted comments.
 *
 * @param document the document
 * @param command the command
 * @param indentation the base indentation to use
 * @param lineDelimiter the line delimiter to use
 * @param unit the compilation unit shown in the editor
 * @return the tags to add to the document
 * @throws CoreException if accessing the Java model fails
 * @throws BadLocationException if accessing the document fails
 */
private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit)
	throws CoreException, BadLocationException
{
	IJavaElement element= unit.getElementAt(command.offset);
	if (element == null)
		return null;

	switch (element.getElementType()) {
	case IJavaElement.TYPE:
		return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);

	case IJavaElement.METHOD:
		return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element);

	default:
		return null;
	}
}
 
Example 6
Source File: JavaBreakPointProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private String getHandleId(final IJavaStratumLineBreakpoint breakpoint) throws CoreException {
	IClassFile classFile = getClassFile(breakpoint);
	if (classFile != null)
		return classFile.getType().getHandleIdentifier();
	ILocationInEclipseResource javaLocation = getJavaLocation(breakpoint);
	if (javaLocation == null)
		return null;
	IStorage javaResource = javaLocation.getPlatformResource();
	if (!(javaResource instanceof IFile))
		return null;
	ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create((IFile) javaResource);
	IJavaElement element = compilationUnit.getElementAt(javaLocation.getTextRegion().getOffset());
	return element == null ? null : element.getHandleIdentifier();
}
 
Example 7
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the field which corresponds to the specified variable declaration
 * fragment
 *
 * @param fragment
 *            the variable declaration fragment
 * @return the corresponding field
 * @throws JavaModelException
 *             if an error occurs
 */
protected final IField getCorrespondingField(final VariableDeclarationFragment fragment) throws JavaModelException {
	final IBinding binding= fragment.getName().resolveBinding();
	if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		if (variable.isField()) {
			final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(fragment);
			final IJavaElement element= unit.getElementAt(fragment.getStartPosition());
			if (element instanceof IField)
				return (IField) element;
		}
	}
	return null;
}
 
Example 8
Source File: RefactoringExecutionStarter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void startIntroduceParameterObject(ICompilationUnit unit, int offset, Shell shell) throws CoreException {
	IJavaElement javaElement= unit.getElementAt(offset);
	if (javaElement instanceof IMethod) {
		IMethod method= (IMethod) javaElement;
		startIntroduceParameterObject(method, shell);
	}
}
 
Example 9
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IJavaElement resolveEnclosingElement(IJavaElement input, ITextSelection selection) throws JavaModelException {
	IJavaElement atOffset= null;
	if (input instanceof ICompilationUnit) {
		ICompilationUnit cunit= (ICompilationUnit)input;
		JavaModelUtil.reconcile(cunit);
		atOffset= cunit.getElementAt(selection.getOffset());
	} else if (input instanceof IClassFile) {
		IClassFile cfile= (IClassFile)input;
		atOffset= cfile.getElementAt(selection.getOffset());
	} else {
		return null;
	}
	if (atOffset == null) {
		return input;
	} else {
		int selectionEnd= selection.getOffset() + selection.getLength();
		IJavaElement result= atOffset;
		if (atOffset instanceof ISourceReference) {
			ISourceRange range= ((ISourceReference)atOffset).getSourceRange();
			while (range.getOffset() + range.getLength() < selectionEnd) {
				result= result.getParent();
				if (! (result instanceof ISourceReference)) {
					result= input;
					break;
				}
				range= ((ISourceReference)result).getSourceRange();
			}
		}
		return result;
	}
}
 
Example 10
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test getter/setter generation in anonymous type
 *
 * @throws Exception
 */
@Test
public void test7() throws Exception {
	/* @formatter:off */
	ICompilationUnit b= fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"\r\n" +
			"	{\r\n" +
			"		B someAnon = new B() {\r\n" +
			"			\r\n" +
			"			A innerfield;\r\n" +
			"			\r\n" +
			"		};\r\n" +
			"	}\r\n" +
			"}", true, null);
	/* @formatter:on */

	IType anon = (IType) b.getElementAt(60); // This is the position of the constructor of the anonymous type
	runAndApplyOperation(anon);

	/* @formatter:off */
	String expected= "public class B {\r\n" +
					"\r\n" +
					"	{\r\n" +
					"		B someAnon = new B() {\r\n" +
					"			\r\n" +
					"			A innerfield;\r\n" +
					"\r\n" +
					"			/**\r\n" +
					"			 * @return Returns the innerfield.\r\n" +
					"			 */\r\n" +
					"			public A getInnerfield() {\r\n" +
					"				return innerfield;\r\n" +
					"			}\r\n" +
					"\r\n" +
					"			/**\r\n" +
					"			 * @param innerfield The innerfield to set.\r\n" +
					"			 */\r\n" +
					"			public void setInnerfield(A innerfield) {\r\n" +
					"				this.innerfield = innerfield;\r\n" +
					"			}\r\n" +
					"			\r\n" +
					"		};\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */
	compareSource(expected, b.getType("B").getSource());
}
 
Example 11
Source File: JavaQueryParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
private Match createMatch(IIndexedJavaRef ref, QuerySpecification query) {
  // Get the file that the indexed Java reference is contained in
  IPath filePath = ref.getSource();
  IFile file = Util.getWorkspaceRoot().getFile(filePath);
  if (!file.exists()) {
    // This may happen if a file in the index is removed from the project
    return null;
  }

  // Get the location of the Java reference within its containing file
  int offset, length;
  if (isTypeSearch(query)) {
    offset = ref.getClassOffset();
    length = ref.className().length();

    if (query instanceof ElementQuerySpecification) {
      IType type = (IType) ((ElementQuerySpecification) query).getElement();

      // Using this instead of ref.className().length() allows us to highlight
      // outer types correctly on refs which reference their inner types.
      length = type.getFullyQualifiedName().length();
    }
  } else {
    offset = ref.getMemberOffset();
    length = ref.memberName().length();
  }

  // By default, we'll pass the file itself as the match element
  Object container = file;

  try {
    // See if the resource containing the reference is a .java file
    ICompilationUnit cu = (ICompilationUnit) JavaCore.create(file);
    if (cu != null) {
      // If the reference is in a .java file, find the JSNI method it's in
      IJavaElement jsniMethod = cu.getElementAt(offset);
      assert (jsniMethod instanceof IMethod);

      // Make sure the method is within the search scope
      if (!query.getScope().encloses(jsniMethod)) {
        return null;
      }

      // Pass the method as the more specific match element
      container = jsniMethod;
    } else {
      // In this case, the Java reference is not inside a .java file (e.g.,
      // it could be inside a module XML file)

      // Make sure this file is within the search scope
      if (!query.getScope().encloses(filePath.toString())) {
        return null;
      }
    }

    return new Match(container, offset, length);

  } catch (JavaModelException e) {
    GWTPluginLog.logError(e);
    return null;
  }
}