Java Code Examples for org.eclipse.jdt.core.ITypeRoot#getJavaProject()

The following examples show how to use org.eclipse.jdt.core.ITypeRoot#getJavaProject() . 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: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String getExpressionBaseName(Expression expr) {
	IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
	if (argBinding instanceof IVariableBinding) {
		IJavaProject project= null;
		ASTNode root= expr.getRoot();
		if (root instanceof CompilationUnit) {
			ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
			if (typeRoot != null) {
				project= typeRoot.getJavaProject();
			}
		}
		return StubUtility.getBaseName((IVariableBinding)argBinding, project);
	}
	if (expr instanceof SimpleName) {
		return ((SimpleName) expr).getIdentifier();
	}
	return null;
}
 
Example 2
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example 3
Source File: JavadocView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compute the textual representation of a 'static' 'final' field's constant initializer value.
 *
 * @param activePart the part that triggered the computation, or <code>null</code>
 * @param selection the selection that references the field, or <code>null</code>
 * @param resolvedField the filed whose constant value will be computed
 * @param monitor the progress monitor
 *
 * @return the textual representation of the constant, or <code>null</code> if the
 *   field is not a constant field, the initializer value could not be computed, or
 *   the progress monitor was cancelled
 * @since 3.4
 */
private String computeFieldConstant(IWorkbenchPart activePart, ISelection selection, IField resolvedField, IProgressMonitor monitor) {

	if (!JavadocHover.isStaticFinal(resolvedField))
		return null;

	Object constantValue;
	IJavaProject preferenceProject;

	if (selection instanceof ITextSelection && activePart instanceof JavaEditor) {
		IEditorPart editor= (IEditorPart) activePart;
		ITypeRoot activeType= JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
		preferenceProject= activeType.getJavaProject();
		constantValue= getConstantValueFromActiveEditor(activeType, resolvedField, (ITextSelection) selection, monitor);
		if (constantValue == null) // fall back - e.g. when selection is inside Javadoc of the element
			constantValue= computeFieldConstantFromTypeAST(resolvedField, monitor);
	} else {
		constantValue= computeFieldConstantFromTypeAST(resolvedField, monitor);
		preferenceProject= resolvedField.getJavaProject();
	}

	if (constantValue != null)
		return JavadocHover.getFormattedAssignmentOperator(preferenceProject) + formatCompilerConstantValue(constantValue);

	return null;
}
 
Example 4
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getExpressionBaseName(Expression expr) {
	IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
	if (argBinding instanceof IVariableBinding) {
		IJavaProject project= null;
		ASTNode root= expr.getRoot();
		if (root instanceof CompilationUnit) {
			ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
			if (typeRoot != null)
				project= typeRoot.getJavaProject();
		}
		return StubUtility.getBaseName((IVariableBinding)argBinding, project);
	}
	if (expr instanceof SimpleName)
		return ((SimpleName) expr).getIdentifier();
	return null;
}
 
Example 5
Source File: ProjectCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * public visibility only for test purpose
 */
public static IJavaProject getJavaProjectFromUri(String uri) throws CoreException, URISyntaxException {
	ITypeRoot typeRoot = JDTUtils.resolveTypeRoot(uri);
	if (typeRoot != null) {
		IJavaProject javaProject = typeRoot.getJavaProject();
		if (javaProject == null) {
			throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to an existing Java project."));
		}
		return javaProject;
	}

	// check for project root uri
	IContainer[] containers = ResourcesPlugin.getWorkspace().getRoot().findContainersForLocationURI(new URI(uri));
	if (containers == null || containers.length == 0) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to any Java project."));
	}

	// For multi-module scenario
	Arrays.sort(containers, (Comparator<IContainer>) (IContainer a, IContainer b) -> {
		return a.getFullPath().toPortableString().length() - b.getFullPath().toPortableString().length();
	});

	IJavaElement targetElement = null;
	for (IContainer container : containers) {
		targetElement = JavaCore.create(container);
		if (targetElement != null) {
			break;
		}
	}

	if (targetElement == null || targetElement.getJavaProject() == null) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to any Java project."));
	}

	return targetElement.getJavaProject();
}
 
Example 6
Source File: TokenScanner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a TokenScanner
 * @param typeRoot The type root to scan on
 * @throws CoreException thrown if the buffer cannot be accessed
 */
public TokenScanner(ITypeRoot typeRoot) throws CoreException {
	IJavaProject project= typeRoot.getJavaProject();
	IBuffer buffer= typeRoot.getBuffer();
	if (buffer == null) {
		throw new CoreException(createError(DOCUMENT_ERROR, "Element has no source", null)); //$NON-NLS-1$
	}
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScanner= ToolFactory.createScanner(true, false, true, sourceLevel, complianceLevel); // line info required

	fScanner.setSource(buffer.getCharacters());
	fDocument= null; // use scanner for line information
	fEndPosition= fScanner.getSource().length - 1;
}
 
Example 7
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus replaceReferences(ParameterObjectFactory pof, SearchResultGroup group, CompilationUnitRewrite cuRewrite) {
	TextEditGroup writeGroup= cuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_replace_write);
	TextEditGroup readGroup= cuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_replace_read);
	ITypeRoot typeRoot= cuRewrite.getCu();
	IJavaProject javaProject= typeRoot.getJavaProject();
	AST ast= cuRewrite.getAST();

	RefactoringStatus status= new RefactoringStatus();
	String parameterName= fDescriptor.getFieldName();

	SearchMatch[] searchResults= group.getSearchResults();
	for (int j= 0; j < searchResults.length; j++) {
		SearchMatch searchMatch= searchResults[j];
		ASTNode node= NodeFinder.perform(cuRewrite.getRoot(), searchMatch.getOffset(), searchMatch.getLength());
		ASTNode parent= node.getParent();
		boolean isDeclaration= parent instanceof VariableDeclaration && ((VariableDeclaration)parent).getInitializer() != node;
		if (!isDeclaration && node instanceof SimpleName) {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			if (parent.getNodeType() == ASTNode.SWITCH_CASE)
				status.addError(RefactoringCoreMessages.ExtractClassRefactoring_error_switch, JavaStatusContext.create(typeRoot, node));

			SimpleName name= (SimpleName) node;
			ParameterInfo pi= getFieldInfo(name.getIdentifier()).pi;
			boolean writeAccess= ASTResolving.isWriteAccess(name);
			if (writeAccess && fDescriptor.isCreateGetterSetter()) {
				boolean useSuper= parent.getNodeType() == ASTNode.SUPER_FIELD_ACCESS;
				Expression qualifier= getQualifier(parent);
				ASTNode replaceNode= getReplacementNode(parent, useSuper, qualifier);
				Expression assignedValue= getAssignedValue(pof, parameterName, javaProject, status, rewrite, pi, useSuper, name.resolveTypeBinding(), qualifier, replaceNode, typeRoot);
				if (assignedValue == null) {
					status.addError(RefactoringCoreMessages.ExtractClassRefactoring_error_unable_to_convert_node, JavaStatusContext.create(typeRoot, replaceNode));
				} else {
					NullLiteral marker= qualifier == null ? null : ast.newNullLiteral();
					Expression access= pof.createFieldWriteAccess(pi, parameterName, ast, javaProject, assignedValue, useSuper, marker);
					replaceMarker(rewrite, qualifier, access, marker);
					rewrite.replace(replaceNode, access, writeGroup);
				}
			} else {
				Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, false, null); //qualifier is already there
				rewrite.replace(name, fieldReadAccess, readGroup);
			}
		}
	}
	return status;
}
 
Example 8
Source File: ASTParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Sets the source code to be parsed.
 *
 * <p>This method automatically sets the project (and compiler
 * options) based on the given compilation unit of class file, in a manner
 * equivalent to {@link #setProject(IJavaProject) setProject(source.getJavaProject())}.</p>
 * <p>If the source is a class file without source attachment, the creation of the
 * ast will fail with an {@link IllegalStateException}.</p>
 *
 * <p>This source is not used when the AST is built using 
 * {@link #createASTs(ICompilationUnit[], String[], ASTRequestor, IProgressMonitor)}.</p>
 *
 * @param source the Java model compilation unit or class file whose corresponding source code
 * is to be parsed, or <code>null</code> if none
 * @since 3.3
 */
public void setSource(ITypeRoot source) {
	this.typeRoot = source;
	// clear the raw source
	this.rawSource = null;
	if (source != null) {
		this.project = source.getJavaProject();
		Map options = this.project.getOptions(true);
		options.remove(JavaCore.COMPILER_TASK_TAGS); // no need to parse task tags
		this.compilerOptions = options;
	}
}