org.eclipse.jdt.internal.core.JavaProject Java Examples

The following examples show how to use org.eclipse.jdt.internal.core.JavaProject. 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: ModelBasedCompletionEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void codeComplete(ICompilationUnit cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	if (!(cu instanceof CompilationUnit)) {
		return;
	}

	if (requestor == null) {
		throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
	}

	IBuffer buffer = cu.getBuffer();
	if (buffer == null) {
		return;
	}

	if (position < -1 || position > buffer.getLength()) {
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
	}

	JavaProject project = (JavaProject) cu.getJavaProject();
	ModelBasedSearchableEnvironment environment = new ModelBasedSearchableEnvironment(project, owner, requestor.isTestCodeExcluded());
	environment.setUnitToSkip((CompilationUnit) cu);

	// code complete
	CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
	engine.complete((CompilationUnit) cu, position, 0, cu);
}
 
Example #2
Source File: DocumentUimaImpl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the project class loader.
 *
 * @param project the project
 * @return the project class loader
 * @throws CoreException the core exception
 */
public static ClassLoader getProjectClassLoader(IProject project) throws CoreException {
  IProjectNature javaNature = project.getNature(JAVA_NATURE);
  if (javaNature != null) {
    JavaProject javaProject = (JavaProject) JavaCore.create(project);
    
    String[] runtimeClassPath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
    List<URL> urls = new ArrayList<>();
    for (String cp : runtimeClassPath) {
      try {
        urls.add(Paths.get(cp).toUri().toURL());
      } catch (MalformedURLException e) {
        CasEditorPlugin.log(e);
      }
    }
    return new URLClassLoader(urls.toArray(new URL[0]));
  } 
  return null;
}
 
Example #3
Source File: RegionBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds all of the openables defined within this java project to the
 * list.
 */
private void injectAllOpenablesForJavaProject(
	IJavaProject project,
	ArrayList openables) {
	try {
		IPackageFragmentRoot[] devPathRoots =
			((JavaProject) project).getPackageFragmentRoots();
		if (devPathRoots == null) {
			return;
		}
		for (int j = 0; j < devPathRoots.length; j++) {
			IPackageFragmentRoot root = devPathRoots[j];
			injectAllOpenablesForPackageFragmentRoot(root, openables);
		}
	} catch (JavaModelException e) {
		// ignore
	}
}
 
Example #4
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Locate the matches amongst the possible matches.
 */
protected void locateMatches(JavaProject javaProject, PossibleMatchSet matchSet, int expected) throws CoreException {
	PossibleMatch[] possibleMatches = matchSet.getPossibleMatches(javaProject.getPackageFragmentRoots());
	int length = possibleMatches.length;
	// increase progress from duplicate matches not stored in matchSet while adding...
	if (this.progressMonitor != null && expected>length) {
		this.progressWorked += expected-length;
		this.progressMonitor.worked( expected-length);
	}
	// locate matches (processed matches are limited to avoid problem while using VM default memory heap size)
	for (int index = 0; index < length;) {
		int max = Math.min(MAX_AT_ONCE, length - index);
		locateMatches(javaProject, possibleMatches, index, max);
		index += max;
	}
	this.patternLocator.clear();
}
 
Example #5
Source File: JavaSearchNameEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public JavaSearchNameEnvironment(IJavaProject javaProject, org.eclipse.jdt.core.ICompilationUnit[] copies) {
	computeClasspathLocations(javaProject.getProject().getWorkspace().getRoot(), (JavaProject) javaProject);
	try {
		int length = copies == null ? 0 : copies.length;
		this.workingCopies = new HashMap(length);
		if (copies != null) {
			for (int i = 0; i < length; i++) {
				org.eclipse.jdt.core.ICompilationUnit workingCopy = copies[i];
				IPackageDeclaration[] pkgs = workingCopy.getPackageDeclarations();
				String pkg = pkgs.length > 0 ? pkgs[0].getElementName() : ""; //$NON-NLS-1$
				String cuName = workingCopy.getElementName();
				String mainTypeName = Util.getNameWithoutJavaLikeExtension(cuName);
				String qualifiedMainTypeName = pkg.length() == 0 ? mainTypeName : pkg.replace('.', '/') + '/' + mainTypeName;
				this.workingCopies.put(qualifiedMainTypeName, workingCopy);
			}
		}
	} catch (JavaModelException e) {
		// working copy doesn't exist: cannot happen
	}
}
 
Example #6
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private IPackageFragmentRoot[] getSourceFolders() throws JavaModelException {
	// Build scope using prereq projects but only source folders
	if (javaProject instanceof JavaProject) {
		return getSourceFolders((JavaProject) javaProject);
	} else {
		IPackageFragmentRoot[] allRoots = javaProject.getAllPackageFragmentRoots();
		int length = allRoots.length, size = 0;
		IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
		for (int i=0; i<length; i++) {
			if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
				allSourceFolders[size++] = allRoots[i];
			}
		}
		if (size < length) {
			System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
		}
		return allSourceFolders;
	}
}
 
Example #7
Source File: Storage2UriMapperJavaImpl.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void doInitializeCache() throws CoreException {
	if(!isInitialized) {
		IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
			@Override
			public void run(IProgressMonitor monitor) throws CoreException {
				if(!isInitialized) {
					for(IProject project: workspace.getRoot().getProjects()) {
						if(project.isAccessible() && JavaProject.hasJavaNature(project)) {
							IJavaProject javaProject = JavaCore.create(project);
							updateCache(javaProject);
						}
					}
					isInitialized = true;
				}
			}
		};
		// while the tree is locked, workspace.run may not be used but we are sure that we do already
		// hold the workspace lock - save to just run the action code
		if (workspace.isTreeLocked()) {
			runnable.run(null);
		} else {
			workspace.run(runnable, null, IWorkspace.AVOID_UPDATE, null);
		}
	}
}
 
Example #8
Source File: Storage2UriMapperJdtImplTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug463258_03b() throws Exception {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.notindexed", "//empty")), true, monitor());
	
	Storage2UriMapperJavaImpl impl = getStorage2UriMapper();
	IPackageFragmentRoot root = JarPackageFragmentRootTestUtil.getJarPackageFragmentRoot(file, (JavaProject) project);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.notindexed");
	fileInJar.setParent(foo);
	
	File jarFile = file.getLocation().toFile();
	assertTrue("exists", jarFile.exists());
	assertTrue("delete", jarFile.delete());
	
	URI uri = impl.getUri(fileInJar);
	assertNull(uri);
}
 
Example #9
Source File: Storage2UriMapperJdtImplTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug463258_03c() throws Exception {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.notindexed", "//empty")), true, monitor());
	addJarToClasspath(project, file);
	
	Storage2UriMapperJavaImpl impl = getStorage2UriMapper();
	
	IPackageFragmentRoot root = JarPackageFragmentRootTestUtil.getJarPackageFragmentRoot(file, (JavaProject) project);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.notindexed");
	fileInJar.setParent(foo);
	
	File jarFile = file.getLocation().toFile();
	assertTrue("exists", jarFile.exists());
	assertTrue("delete", jarFile.delete());
	// simulate an automated refresh
	file.refreshLocal(IResource.DEPTH_ONE, null);
	URI uri = impl.getUri(fileInJar);
	assertNull(uri);
}
 
Example #10
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
public static IJavaSearchScope getSearchScope(IJavaProject project) {
    	if (fSearchScope == null) {
            fSearchScope = SearchEngine.createWorkspaceScope();
        	//fSearchScope = SearchEngine.createJavaSearchScope(new IResource[] {method.getResource()});
        }
//    	return fSearchScope;

    	if(project == null) {	        
	        return fSearchScope;
    	} else {
    		JavaSearchScope js = new JavaSearchScope();
    		try {
    			int includeMask = 
    				JavaSearchScope.SOURCES | 
					JavaSearchScope.APPLICATION_LIBRARIES | 
					JavaSearchScope.SYSTEM_LIBRARIES ;
				js.add((JavaProject) project, includeMask, new HashSet());
			} catch (JavaModelException e) {
				log(e.getMessage(), e);
				return fSearchScope;
			}
    		return js;
    	} 
    }
 
Example #11
Source File: JavaClassPathResourceForIEditorInputFactoryTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expected=CoreException.class) public void testBug463258_03c() throws Throwable {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.testlanguage", "//empty")), true, monitor());
	addJarToClasspath(project, file);
	
	IPackageFragmentRoot root = JarPackageFragmentRootTestUtil.getJarPackageFragmentRoot(file, (JavaProject) project);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.testlanguage");
	fileInJar.setParent(foo);
	
	File jarFile = file.getLocation().toFile();
	assertTrue("exists", jarFile.exists());
	assertTrue("delete", jarFile.delete());
	// simulate an automated refresh
	file.refreshLocal(IResource.DEPTH_ONE, null);
	XtextReadonlyEditorInput editorInput = new XtextReadonlyEditorInput(fileInJar);
	try {
		factory.createResource(editorInput);
	} catch(WrappedException e) {
		throw e.getCause();
	}
}
 
Example #12
Source File: JavaClassPathResourceForIEditorInputFactoryTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expected=CoreException.class) public void testBug463258_03b() throws Throwable {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.testlanguage", "//empty")), true, monitor());
	
	IPackageFragmentRoot root = JarPackageFragmentRootTestUtil.getJarPackageFragmentRoot(file, (JavaProject) project);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.testlanguage");
	fileInJar.setParent(foo);
	
	File jarFile = file.getLocation().toFile();
	assertTrue("exists", jarFile.exists());
	assertTrue("delete", jarFile.delete());
	
	XtextReadonlyEditorInput editorInput = new XtextReadonlyEditorInput(fileInJar);
	try {
		factory.createResource(editorInput);
	} catch(WrappedException e) {
		throw e.getCause();
	}
}
 
Example #13
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a collection of return statements withing @param methodDeclaration.
 * */
public static Collection<ReturnStatement> findReturns(IProgressMonitor progressMonitor, MethodDeclaration methodDeclaration, JavaProject project) {
	progressMonitor.setTaskName("Looking for returns in " + methodDeclaration.getName());
	final Collection<ReturnStatement> returns = new ArrayList<ReturnStatement>();
	ASTVisitor finder = new ASTVisitor() {			
		public boolean visit(ReturnStatement node) {
			return returns.add(node);
		}
	};
	
	methodDeclaration.accept(finder);
	return returns;
}
 
Example #14
Source File: GroovyCompilationOnScriptExpressionConstraint.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private IStatus evaluateExpression(final IValidationContext context, final EObject eObj) {
    final Expression expression = (Expression) eObj;
    final String scriptText = expression.getContent();
    if (scriptText == null || scriptText.isEmpty()) {
        return context.createSuccessStatus();
    }
    final IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    final GroovySnippetCompiler compiler = new GroovySnippetCompiler((JavaProject) javaProject);
    final CompilationResult result = compiler.compileForErrors(scriptText, null);
    final CategorizedProblem[] problems = result.getErrors();
    if (problems != null && problems.length > 0) {
        final StringBuilder sb = new StringBuilder();
        for (final CategorizedProblem problem : problems) {
            sb.append(problem.getMessage());
            sb.append(", ");
        }
        if (sb.length() > 1) {
            sb.delete(sb.length() - 2, sb.length());
            return context.createFailureStatus(new Object[] { Messages.bind(Messages.groovyCompilationProblem, expression.getName(), sb.toString()) });
        }
    }
    final ModuleNode moduleNode = compiler.compile(scriptText, null);
    final BlockStatement statementBlock = moduleNode.getStatementBlock();
    final ValidationCodeVisitorSupport validationCodeVisitorSupport = new ValidationCodeVisitorSupport(context, expression, moduleNode);
    statementBlock.visit(validationCodeVisitorSupport);
    return validationCodeVisitorSupport.getStatus();
}
 
Example #15
Source File: RegionBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Configure this type hierarchy that is based on a region.
 */
private void createTypeHierarchyBasedOnRegion(HashMap allOpenablesInRegion, IProgressMonitor monitor) {

	try {
		int size = allOpenablesInRegion.size();
		if (monitor != null) monitor.beginTask("", size * 2/* 1 for build binding, 1 for connect hierarchy*/); //$NON-NLS-1$
		this.infoToHandle = new HashMap(size);
		Iterator javaProjects = allOpenablesInRegion.entrySet().iterator();
		while (javaProjects.hasNext()) {
			Map.Entry entry = (Map.Entry) javaProjects.next();
			JavaProject project = (JavaProject) entry.getKey();
			ArrayList allOpenables = (ArrayList) entry.getValue();
			Openable[] openables = new Openable[allOpenables.size()];
			allOpenables.toArray(openables);

			try {
				// resolve
				SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.hierarchy.workingCopies);
				this.nameLookup = searchableEnvironment.nameLookup;
				this.hierarchyResolver.resolve(openables, null, monitor);
			} catch (JavaModelException e) {
				// project doesn't exit: ignore
			}
		}
	} finally {
		if (monitor != null) monitor.done();
	}
}
 
Example #16
Source File: SourceIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void resolveDocument() {
	try {
		IPath path = new Path(this.document.getPath());
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
		JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
		JavaProject javaProject = (JavaProject) model.getJavaProject(project);

		this.options = new CompilerOptions(javaProject.getOptions(true));
		ProblemReporter problemReporter =
				new ProblemReporter(
						DefaultErrorHandlingPolicies.proceedWithAllProblems(),
						this.options,
						new DefaultProblemFactory());

		// Re-parse using normal parser, IndexingParser swallows several nodes, see comment above class.
		this.basicParser = new Parser(problemReporter, false);
		this.basicParser.reportOnlyOneSyntaxError = true;
		this.basicParser.scanner.taskTags = null;
		this.cud = this.basicParser.parse(this.compilationUnit, new CompilationResult(this.compilationUnit, 0, 0, this.options.maxProblemsPerUnit));

		// Use a non model name environment to avoid locks, monitors and such.
		INameEnvironment nameEnvironment = new JavaSearchNameEnvironment(javaProject, JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true/*add primary WCs*/));
		this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, nameEnvironment);
		reduceParseTree(this.cud);
		this.lookupEnvironment.buildTypeBindings(this.cud, null);
		this.lookupEnvironment.completeTypeBindings();
		this.cud.scope.faultInTypes();
		this.cud.resolve();
	} catch (Exception e) {
		if (JobManager.VERBOSE) {
			e.printStackTrace();
		}
	}
}
 
Example #17
Source File: ClasspathUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return the raw classpath entry on the project's classpath that contributes
 * the given type to the project.
 *
 * @param javaProject The java project
 * @param fullyQualifiedName The fully-qualified type name
 * @return The raw classpath entry that contributes the type to the project,
 *         or <code>null</code> if no such classpath entry can be found.
 * @throws JavaModelException
 */
public static IClasspathEntry findRawClasspathEntryFor(
    IJavaProject javaProject, String fullyQualifiedName)
    throws JavaModelException {
  IType type = javaProject.findType(fullyQualifiedName);
  if (type != null) {
    IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

    JavaProject jProject = (JavaProject) javaProject;

    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    for (IClasspathEntry rawClasspathEntry : rawClasspath) {
      IClasspathEntry[] resolvedClasspath = jProject.resolveClasspath(new IClasspathEntry[] {rawClasspathEntry});

      // was this - which is no longer, internal api refactor
      //IPackageFragmentRoot[] computePackageFragmentRoots = jProject.computePackageFragmentRoots(resolvedClasspath, true, null);

      // now this - from IPackage
      List<IPackageFragmentRoot> fragmentRoots = new ArrayList<IPackageFragmentRoot>();
      for (IClasspathEntry classPathEntry : resolvedClasspath) {
        IPackageFragmentRoot[] foundRoots = javaProject.findPackageFragmentRoots(classPathEntry);
        fragmentRoots.addAll(Arrays.asList(foundRoots));
      }

      IPackageFragmentRoot[] computePackageFragmentRoots = new IPackageFragmentRoot[fragmentRoots.size()];
      fragmentRoots.toArray(computePackageFragmentRoots);

      if (Arrays.asList(computePackageFragmentRoots).contains(
          packageFragmentRoot)) {
        return rawClasspathEntry;
      }
    }

    return packageFragmentRoot.getRawClasspathEntry();
  }

  return null;
}
 
Example #18
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IPackageFragmentRoot[] getSourceFolders(JavaProject javaProject) throws JavaModelException {
	/*
	 * IJavaProject#getAllPackageFragmentRoots will open all references archives to read the JDK version from
	 * the first class file it finds. This isn't necessary for our case thus we try to avoid this by copying a lot of 
	 * code. 
	 */
	ObjectVector result = new ObjectVector();
	collectSourcePackageFragmentRoots(javaProject, Sets.<String>newHashSet(), null, result);
	IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[result.size()];
	result.copyInto(rootArray);
	return rootArray;
}
 
Example #19
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
protected IType findPrimaryType(String packageName, String typeName) throws JavaModelException {
	JavaProject casted = (JavaProject) javaProject;
	NameLookup nameLookup = getNameLookup(casted);
	NameLookup.Answer answer = nameLookup.findType(
			typeName,
			packageName,
			false,
			NameLookup.ACCEPT_ALL,
			false, // do not consider secondary types
			true, // wait for indexes (in case we need to consider secondary types)
			false/*don't check restrictions*/,
			null);
	return answer == null ? null : answer.type;
}
 
Example #20
Source File: JdtToBeBuiltComputer.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.19
 */
@Override
public void addInterestingProjects(IProject thisProject, Set<IProject> result) {
	IJavaProject javaProject = JavaCore.create(thisProject);
	if (javaProject instanceof JavaProject) {
		Set<IProject> requiredProjects = getRequiredProjects((JavaProject) javaProject, thisProject.getWorkspace().getRoot());
		projectDependencyGraph.putDependency(thisProject, requiredProjects);
		result.addAll(requiredProjects);
	}
}
 
Example #21
Source File: SourceView.java    From lapse-plus with GNU General Public License v3.0 4 votes vote down vote up
int addMethodsByName(String methodName, String type, String category, JavaProject project, IProgressMonitor monitor, boolean nonWeb) {
	int matches = 0;
	ViewContentProvider cp = ((ViewContentProvider)viewer.getContentProvider());
	try {
		MethodDeclarationsSearchRequestor requestor = new MethodDeclarationsSearchRequestor();
           SearchEngine searchEngine = new SearchEngine();

           IJavaSearchScope searchScope = CallerFinder.getSearchScope(project);
           SearchPattern pattern = SearchPattern.createPattern(
           		methodName, 
				IJavaSearchConstants.METHOD,
				IJavaSearchConstants.DECLARATIONS, 
				SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE
				);
    
		searchEngine.search(
				pattern, 
				new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
		        searchScope, 
		        requestor, 
				monitor
				);
		Collection pairs =  requestor.getMethodUnitPairs();
		for(Iterator iter = pairs.iterator(); iter.hasNext();) {
			Utils.MethodDeclarationUnitPair pair = (MethodDeclarationUnitPair) iter.next();
			ViewMatch match = new ViewMatch(
					pair.getMember().getDeclaringType().getElementName() + "." + pair.getMember().getElementName(),  
					pair.getMethod() != null ? pair.getMethod().getName() : null, 
					pair.getCompilationUnit(), 
					pair.getResource(), 
					type,
					category,
					pair.getMember(),
					false,
					nonWeb);
			cp.addMatch(match);
			monitor.subTask("Found " + matches + " matches");
			matches++;
		}
	} catch (CoreException e) {
		// TODO Auto-generated catch block
		log(e.getMessage(), e);
	}
	
	return matches;
}
 
Example #22
Source File: ModelBasedSearchableEnvironment.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public ModelBasedSearchableEnvironment(JavaProject javaProject, WorkingCopyOwner owner, boolean excludeTestCode) throws JavaModelException {
	super(javaProject, owner, excludeTestCode);
}
 
Example #23
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @see JavaProject computePackageFragmentRoots(IClasspathEntry, ObjectVector, HashSet, IClasspathEntry, boolean, boolean, java.util.Map)
 */
private void collectSourcePackageFragmentRoots(JavaProject javaProject, HashSet<String> rootIDs, IClasspathEntry referringEntry, ObjectVector result) throws JavaModelException {
	if (referringEntry == null){
		rootIDs.add(javaProject.rootID());
	} else if (rootIDs.contains(javaProject.rootID())) {
		return;
	}
	IWorkspaceRoot workspaceRoot = javaProject.getProject().getWorkspace().getRoot();
	for(IClasspathEntry entry: javaProject.getResolvedClasspath()) {
		switch(entry.getEntryKind()) {
			case IClasspathEntry.CPE_PROJECT:
				if (referringEntry != null && !entry.isExported())
					return;
				
				IPath pathToProject = entry.getPath();
				IResource referencedProject = workspaceRoot.findMember(pathToProject);
				if (referencedProject != null && referencedProject.getType() == IResource.PROJECT) {
					IProject casted = (IProject) referencedProject;
					if (JavaProject.hasJavaNature(casted)) {
						rootIDs.add(javaProject.rootID());
						JavaProject referencedJavaProject = (JavaProject) JavaCore.create(casted);
						collectSourcePackageFragmentRoots(referencedJavaProject, rootIDs, entry, result);
					}
				}
				break;
			case IClasspathEntry.CPE_SOURCE:
				// inlined from org.eclipse.jdt.internal.core.JavaProject
				// .computePackageFragmentRoots(IClasspathEntry, ObjectVector, HashSet, IClasspathEntry, boolean, boolean, Map)
				IPath projectPath = javaProject.getProject().getFullPath();
				IPath entryPath = entry.getPath();
				if (projectPath.isPrefixOf(entryPath)){
					Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
					if (target != null) {
						if (target instanceof IFolder || target instanceof IProject){
							IPackageFragmentRoot root = javaProject.getPackageFragmentRoot((IResource)target);
							result.add(root);
						}
					}
				}
				break;
		}
	}
}
 
Example #24
Source File: JavaSearchNameEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void computeClasspathLocations(IWorkspaceRoot workspaceRoot, JavaProject javaProject) {

	IPackageFragmentRoot[] roots = null;
	try {
		roots = javaProject.getAllPackageFragmentRoots();
	} catch (JavaModelException e) {
		// project doesn't exist
		this.locations = new ClasspathLocation[0];
		return;
	}
	int length = roots.length;
	ClasspathLocation[] cpLocations = new ClasspathLocation[length];
	int index = 0;
	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	for (int i = 0; i < length; i++) {
		PackageFragmentRoot root = (PackageFragmentRoot) roots[i];
		IPath path = root.getPath();
		try {
			if (root.isArchive()) {
				ZipFile zipFile = manager.getZipFile(path);
				cpLocations[index++] = new ClasspathJar(zipFile, ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
			} else {
				Object target = JavaModel.getTarget(path, true);
				if (target == null) {
					// target doesn't exist any longer
					// just resize cpLocations
					System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
				} else if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
					cpLocations[index++] = new ClasspathSourceDirectory((IContainer)target, root.fullExclusionPatternChars(), root.fullInclusionPatternChars());
				} else {
					cpLocations[index++] = ClasspathLocation.forBinaryFolder((IContainer) target, false, ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
				}
			}
		} catch (CoreException e1) {
			// problem opening zip file or getting root kind
			// consider root corrupt and ignore
			// just resize cpLocations
			System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
		}
	}
	this.locations = cpLocations;
}
 
Example #25
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a new parser for the given project, as well as a lookup environment.
 */
public void initialize(JavaProject project, int possibleMatchSize) throws JavaModelException {
	// clean up name environment only if there are several possible match as it is reused
	// when only one possible match (bug 58581)
	if (this.nameEnvironment != null && possibleMatchSize != 1) {
		this.nameEnvironment.cleanup();
		this.unitScope = null; // don't leak a reference to the cleaned-up name environment
	}

	SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.workingCopies);

	// if only one possible match, a file name environment costs too much,
	// so use the existing searchable  environment which will populate the java model
	// only for this possible match and its required types.
	this.nameEnvironment = possibleMatchSize == 1
		? (INameEnvironment) searchableEnvironment
		: (INameEnvironment) new JavaSearchNameEnvironment(project, this.workingCopies);

	// create lookup environment
	Map map = project.getOptions(true);
	map.put(CompilerOptions.OPTION_TaskTags, org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING);
	this.options = new CompilerOptions(map);
	ProblemReporter problemReporter =
		new ProblemReporter(
			DefaultErrorHandlingPolicies.proceedWithAllProblems(),
			this.options,
			new DefaultProblemFactory());
	this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
	this.lookupEnvironment.mayTolerateMissingType = true;
	this.parser = MatchLocatorParser.createParser(problemReporter, this);

	// basic parser needs also to be reset as project options may have changed
	// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=163072
	this.basicParser = null;

	// remember project's name lookup
	this.nameLookup = searchableEnvironment.nameLookup;

	// initialize queue of units
	this.numberOfMatches = 0;
	this.matchesToProcess = new PossibleMatch[possibleMatchSize];

	this.lookupEnvironment.addResolutionListener(this.patternLocator);
}
 
Example #26
Source File: CompPlugin.java    From junion with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void doFinish(IJavaProject project) {
	if(project != null ) {
		
		try {
			
			ProjectData data = cache.get(project);
			if(data == null) {
				log("Unexpected error: project data is null");
				Thread.dumpStack();
				return;
			}
			String genFolder = data.properties.getProperty(GEN_FOLDER).trim();
			String projectName = project.getProject().getName();
			char SEP = IPath.SEPARATOR;
			String genFolderPathRelative = SEP+projectName+SEP+genFolder;
			data.paths.clear();

			PerProjectInfo info = ((JavaProject)project).getPerProjectInfo();
			IClasspathEntry raw[] = info.rawClasspath;

			if(raw != null) {
				for(IClasspathEntry entry : raw) {
					if(entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
						String srcPath = entry.getPath().toString();
						if(srcPath.equals(genFolderPathRelative)) {
							setPaths(entry, ALL_PATHS);
						}
						else {
							
							setPaths(entry, NONE_PATHS);
							
						}
							
					}
					
				}
			}
			
			
			IFolder file = project.getProject().getFolder(genFolder);
			file.refreshLocal(IResource.DEPTH_INFINITE, null);
			    
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
}
 
Example #27
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private NameLookup getNameLookup(JavaProject casted) throws JavaModelException {
	return casted.newNameLookup(getWorkingCopies());
}
 
Example #28
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS3 JLS3} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS3}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS3 has been deprecated. This method has been replaced by {@link #getAST4()} which returns an AST
 * with JLS4 level.
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST3() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example #29
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS4 JLS4} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS4}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS4 has been deprecated. This method has been replaced by {@link #getAST8()} which returns an AST
 * with JLS8 level.
 * @since 3.7.1
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST4() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS4 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS4);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example #30
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS8 JLS8} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS8}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @since 3.10
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST8() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS8 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}