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

The following examples show how to use org.eclipse.jdt.core.IJavaElement#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: ClasspathPipelineOptionsHierarchyFactory.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Override
public PipelineOptionsHierarchy forProject(
    IProject project, MajorVersion version, IProgressMonitor monitor)
    throws PipelineOptionsRetrievalException {
  IJavaElement javaElement = project.getAdapter(IJavaElement.class);
  checkNotNull(
      javaElement,
      "%s cannot be created for a non-java project: %s",
      JavaProjectPipelineOptionsHierarchy.class.getSimpleName(),
      project);
  try {
    IJavaProject javaProject = javaElement.getJavaProject();
    IType rootType = javaProject.findType(PipelineOptionsNamespaces.rootType(version));
    if (rootType == null || !rootType.exists()) {
      return global(monitor);
    }
    return new JavaProjectPipelineOptionsHierarchy(javaProject, version, monitor);
  } catch (JavaModelException e) {
    DataflowCorePlugin.logError(e,
        "Error while constructing Pipeline Options Hierarchy for project %s", project.getName());
    throw new PipelineOptionsRetrievalException(e);
  }
}
 
Example 2
Source File: ActionUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isOnBuildPath(IJavaElement element) {
       //fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051
       if (element.getElementType() == IJavaElement.JAVA_PROJECT)
           return true;
	IJavaProject project= element.getJavaProject();
	try {
		if (!project.isOnClasspath(element))
			return false;
		IProject resourceProject= project.getProject();
		if (resourceProject == null)
			return false;
		IProjectNature nature= resourceProject.getNature(JavaCore.NATURE_ID);
		// We have a Java project
		if (nature != null)
			return true;
	} catch (CoreException e) {
	}
	return false;
}
 
Example 3
Source File: PackagesView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IJavaElement findInputForJavaElement(IJavaElement je, boolean canChangeInputType) {
	if (je == null || !je.exists())
		return null;

	if (isValidInput(je)) {

		//don't update if input must be project (i.e. project is used as source folder)
		if (canChangeInputType)
			fLastInputWasProject= je.getElementType() == IJavaElement.JAVA_PROJECT;
		return je;
	} else if (fLastInputWasProject) {
		IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot)je.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
		if (!packageFragmentRoot.isExternal())
			return je.getJavaProject();
	}

	return findInputForJavaElement(je.getParent(), canChangeInputType);
}
 
Example 4
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IFormattingContext createFormattingContext() {
	IFormattingContext context= new JavaFormattingContext();

	Map<String, String> preferences;
	IJavaElement inputJavaElement= getInputJavaElement();
	IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
	if (javaProject == null)
		preferences= new HashMap<String, String>(JavaCore.getOptions());
	else
		preferences= new HashMap<String, String>(javaProject.getOptions(true));

	context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);

	return context;
}
 
Example 5
Source File: RefactoringScopeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new search scope with all compilation units possibly referencing
 * <code>javaElement</code>.
 *
 * @param javaElement
 *            the java element
 * @param considerVisibility
 *            consider visibility of javaElement iff <code>true</code>
 * @param sourceReferencesOnly
 *            consider references in source only (no references in binary)
 * @return the search scope
 * @throws JavaModelException
 *             if an error occurs
 */
public static IJavaSearchScope create(IJavaElement javaElement, boolean considerVisibility, boolean sourceReferencesOnly) throws JavaModelException {
	if (considerVisibility & javaElement instanceof IMember) {
		IMember member = (IMember) javaElement;
		if (JdtFlags.isPrivate(member)) {
			if (member.getCompilationUnit() != null) {
				return SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getCompilationUnit() });
			} else {
				return SearchEngine.createJavaSearchScope(new IJavaElement[] { member });
			}
		}
		// Removed code that does some optimizations regarding package visible members. The problem is that
		// there can be a package fragment with the same name in a different source folder or project. So we
		// have to treat package visible members like public or protected members.
	}

	IJavaProject javaProject = javaElement.getJavaProject();
	return SearchEngine.createJavaSearchScope(getAllScopeElements(javaProject, sourceReferencesOnly), false);
}
 
Example 6
Source File: JavaProjectsStateHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public List<String> initVisibleHandles(String handle) {
	IJavaElement javaElement = JavaCore.create(handle);
	if (javaElement != null) {
		IJavaProject project = javaElement.getJavaProject();
		if (isAccessibleXtextProject(project.getProject())) {
			List<String> rootHandles = getPackageFragmentRootHandles(project);
			return rootHandles;
		} 
		return Collections.emptyList();
	}
	return Collections.emptyList();
}
 
Example 7
Source File: JavaProcessors.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String[] computeAffectedNatures(IJavaElement element) throws CoreException {
	if (element instanceof IMember) {
		IMember member= (IMember)element;
		if (JdtFlags.isPrivate(member)) {
			return element.getJavaProject().getProject().getDescription().getNatureIds();
		}
	}
	IJavaProject project= element.getJavaProject();
	return ResourceProcessors.computeAffectedNatures(project.getProject());
}
 
Example 8
Source File: InferTypeArgumentsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private HashMap<IJavaProject, ArrayList<IJavaElement>> getJavaElementsPerProject(IJavaElement[] elements) {
	HashMap<IJavaProject, ArrayList<IJavaElement>> result= new HashMap<IJavaProject, ArrayList<IJavaElement>>();
	for (int i= 0; i < elements.length; i++) {
		IJavaElement element= elements[i];
		IJavaProject javaProject= element.getJavaProject();
		ArrayList<IJavaElement> javaElements= result.get(javaProject);
		if (javaElements == null) {
			javaElements= new ArrayList<IJavaElement>();
			result.put(javaProject, javaElements);
		}
		javaElements.add(element);
	}
	return result;
}
 
Example 9
Source File: JdtUtils.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param javaElt
 * @return true, if corresponding java project has compiler setting to
 *         generate bytecode for jdk 1.5 and above
 */
private static boolean is50OrHigher(IJavaElement javaElt) {
    IJavaProject project = javaElt.getJavaProject();
    String option = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
    boolean result = JavaCore.VERSION_1_5.equals(option);
    if (result) {
        return result;
    }
    // probably > 1.5?
    result = JavaCore.VERSION_1_4.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_3.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_2.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_1.equals(option);
    if (result) {
        return false;
    }
    // unknown = > 1.5
    return true;
}
 
Example 10
Source File: JavaSearchScopeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IJavaSearchScope createJavaProjectSearchScope(IEditorInput editorInput, int includeMask) {
	IJavaElement elem= JavaUI.getEditorInputJavaElement(editorInput);
	if (elem != null) {
		IJavaProject project= elem.getJavaProject();
		if (project != null) {
			return createJavaProjectSearchScope(project, includeMask);
		}
	}
	return EMPTY_SCOPE;
}
 
Example 11
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);

	IJavaProject javaProject= element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options= javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);

	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 12
Source File: NewContainerWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initializes the source folder field with a valid package fragment root.
 * The package fragment root is computed from the given Java element.
 *
 * @param elem the Java element used to compute the initial package
 *    fragment root used as the source folder
 */
protected void initContainerPage(IJavaElement elem) {
	IPackageFragmentRoot initRoot= null;
	if (elem != null) {
		initRoot= JavaModelUtil.getPackageFragmentRoot(elem);
		try {
			if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
				IJavaProject jproject= elem.getJavaProject();
				if (jproject != null) {
						initRoot= null;
						if (jproject.exists()) {
							IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
							for (int i= 0; i < roots.length; i++) {
								if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
									initRoot= roots[i];
									break;
								}
							}
						}
					if (initRoot == null) {
						initRoot= jproject.getPackageFragmentRoot(jproject.getResource());
					}
				}
			}
		} catch (JavaModelException e) {
			JavaPlugin.log(e);
		}
	}
	setPackageFragmentRoot(initRoot, true);
}
 
Example 13
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 14
Source File: ContextSensitiveImportRewriteContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Name[] getImportedNames() {
	if (fImportedNames == null) {
		IJavaProject project= null;
		IJavaElement javaElement= fCompilationUnit.getJavaElement();
		if (javaElement != null)
			project= javaElement.getJavaProject();

		List<SimpleName> imports= new ArrayList<SimpleName>();
		ImportReferencesCollector.collect(fCompilationUnit, project, null, imports, null);
		fImportedNames= imports.toArray(new Name[imports.size()]);
	}
	return fImportedNames;
}
 
Example 15
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	Assert.isNotNull(element);
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	
	IJavaProject javaProject= element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options= javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);
	
	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 16
Source File: ClassFinder.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private List findCLasses( IJavaElement element, IProgressMonitor pm )
		throws JavaModelException
{
	List found = new ArrayList( );
	IJavaProject javaProject = element.getJavaProject( );

	IType testCaseType = classType( javaProject );
	if ( testCaseType == null )
		return found;

	IType[] subtypes = javaProject.newTypeHierarchy( testCaseType,
			getRegion( element ),
			pm ).getAllSubtypes( testCaseType );

	if ( subtypes == null )
		throw new JavaModelException( new CoreException( new Status( IStatus.ERROR,
				ID,
				IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE,
				ERROR_MESSAGE,
				null ) ) );

	for ( int i = 0; i < subtypes.length; i++ )
	{
		try
		{
			if ( hasValidModifiers( subtypes[i] ) )
				found.add( subtypes[i] );
		}
		catch ( JavaModelException e )
		{
			logger.log(Level.SEVERE, e.getMessage(),e);
		}
	}
	return found;
}
 
Example 17
Source File: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean getConvertVarTypeToResolvedTypeProposal(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> proposals) {
	CompilationUnit astRoot = context.getASTRoot();
	IJavaElement root = astRoot.getJavaElement();
	if (root == null) {
		return false;
	}
	IJavaProject javaProject = root.getJavaProject();
	if (javaProject == null) {
		return false;
	}
	if (!JavaModelUtil.is10OrHigher(javaProject)) {
		return false;
	}

	if (!(node instanceof SimpleName)) {
		return false;
	}
	SimpleName name = (SimpleName) node;
	IBinding binding = name.resolveBinding();
	if (!(binding instanceof IVariableBinding)) {
		return false;
	}
	IVariableBinding varBinding = (IVariableBinding) binding;
	if (varBinding.isField() || varBinding.isParameter()) {
		return false;
	}

	ASTNode varDeclaration = astRoot.findDeclaringNode(varBinding);
	if (varDeclaration == null) {
		return false;
	}

	ITypeBinding typeBinding = varBinding.getType();
	if (typeBinding == null || typeBinding.isAnonymous() || typeBinding.isIntersectionType() || typeBinding.isWildcardType()) {
		return false;
	}

	Type type = null;
	if (varDeclaration instanceof SingleVariableDeclaration) {
		type = ((SingleVariableDeclaration) varDeclaration).getType();
	} else if (varDeclaration instanceof VariableDeclarationFragment) {
		ASTNode parent = varDeclaration.getParent();
		if (parent instanceof VariableDeclarationStatement) {
			type = ((VariableDeclarationStatement) parent).getType();
		} else if (parent instanceof VariableDeclarationExpression) {
			type = ((VariableDeclarationExpression) parent).getType();
		}
	}
	if (type == null || !type.isVar()) {
		return false;
	}

	TypeChangeCorrectionProposal proposal = new TypeChangeCorrectionProposal(context.getCompilationUnit(), varBinding, astRoot, typeBinding, false, IProposalRelevance.CHANGE_VARIABLE);
	proposal.setKind(CodeActionKind.Refactor);
	proposals.add(proposal);
	return true;
}
 
Example 18
Source File: JavaBuilderState.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public static JavaBuilderState getLastBuiltState(IJavaElement javaElement) {
	IJavaProject javaProject = javaElement.getJavaProject();
	return javaProject == null ? null : JavaBuilderState.getLastBuiltState(javaProject.getProject());
}
 
Example 19
Source File: JavadocHelpContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public JavadocHelpContext(IContext context, Object[] elements) throws JavaModelException {
	Assert.isNotNull(elements);
	if (context instanceof IContext2)
		fTitle= ((IContext2)context).getTitle();

	List<IHelpResource> helpResources= new ArrayList<IHelpResource>();

	String javadocSummary= null;
	for (int i= 0; i < elements.length; i++) {
		if (elements[i] instanceof IJavaElement) {
			IJavaElement element= (IJavaElement) elements[i];
			// if element isn't on the build path skip it
			if (!ActionUtil.isOnBuildPath(element))
				continue;

			// Create Javadoc summary
			if (BUG_85721_FIXED) {
				if (javadocSummary == null) {
					javadocSummary= retrieveText(element);
					if (javadocSummary != null) {
						String elementLabel= JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_DEFAULT);

						// FIXME: needs to be NLSed once the code becomes active
						javadocSummary= "<b>Javadoc for " + elementLabel + ":</b><br>" + javadocSummary;   //$NON-NLS-1$//$NON-NLS-2$
					}
				} else {
					javadocSummary= ""; // no Javadoc summary for multiple selection //$NON-NLS-1$
				}
			}

			URL url= JavaUI.getJavadocLocation(element, true);
			if (url == null || doesNotExist(url)) {
				IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
				if (root != null) {
					url= JavaUI.getJavadocBaseLocation(element);
					if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
						element= element.getJavaProject();
					} else {
						element= root;
					}
					url= JavaUI.getJavadocLocation(element, false);
				}
			}
			if (url != null) {
				IHelpResource javaResource= new JavaUIHelpResource(element, getURLString(url));
				helpResources.add(javaResource);
			}
		}
	}

	// Add static help topics
	if (context != null) {
		IHelpResource[] resources= context.getRelatedTopics();
		if (resources != null) {
			for (int j= 0; j < resources.length; j++) {
				helpResources.add(resources[j]);
			}
		}
	}

	fHelpResources= helpResources.toArray(new IHelpResource[helpResources.size()]);

	if (context != null)
		fText= context.getText();

	if (BUG_85721_FIXED) {
		if (javadocSummary != null && javadocSummary.length() > 0) {
			if (fText != null)
				fText= context.getText() + "<br><br>" + javadocSummary; //$NON-NLS-1$
			else
				fText= javadocSummary;
		}
	}

	if (fText == null)
		fText= "";  //$NON-NLS-1$

}
 
Example 20
Source File: WorkingSetAwareContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IProject getProject(IJavaElement element) {
	IJavaProject project= element.getJavaProject();
	if (project == null)
		return null;
	return project.getProject();
}