Java Code Examples for org.eclipse.jdt.core.WorkingCopyOwner

The following examples show how to use org.eclipse.jdt.core.WorkingCopyOwner. These examples are extracted from open source projects. 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 Project: xtext-eclipse   Source File: JdtBasedTypeFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
ParameterNameInitializer createParameterNameInitializer(
		IMethodBinding method,
		WorkingCopyOwner workingCopyOwner,
		JvmExecutable result,
		String handleIdentifier,
		String[] path,
		String name,
		SegmentSequence signaturex) {
	if (method.isConstructor() && method.getDeclaringClass().isEnum()) {
		String syntheticParams = "Ljava/lang/String;I";
		String withoutSyntheticArgs = signaturex.toString();
		// sometimes (don't really know when... JDT bug?) an enum constructor comes without synthetic arguments
		// this solution might wrongly strip off a (String,int) signature, but I don't see how this can be done differently here.
		if (withoutSyntheticArgs.startsWith(syntheticParams)) {
			withoutSyntheticArgs = withoutSyntheticArgs.substring(syntheticParams.length());
		}
		return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, withoutSyntheticArgs);
	}
	return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
}
 
Example 2
public IJavaElement findPackageFragment(String packageName)
		throws JavaModelException {
	NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
	IPackageFragment[] pkgFragments = lookup.findPackageFragments(packageName, false);
	if (pkgFragments == null) {
		return null;

	} else {
		// try to return one that is a child of this project
		for (int i = 0, length = pkgFragments.length; i < length; i++) {

			IPackageFragment pkgFragment = pkgFragments[i];
			if (equals(pkgFragment.getParent().getParent())) {
				return pkgFragment;
			}
		}
		// default to the first one
		return pkgFragments[0];
	}
}
 
Example 3
public InternalExtendedCompletionContext(
		InternalCompletionContext completionContext,
		ITypeRoot typeRoot,
		CompilationUnitDeclaration compilationUnitDeclaration,
		LookupEnvironment lookupEnvironment,
		Scope assistScope,
		ASTNode assistNode,
		ASTNode assistNodeParent,
		WorkingCopyOwner owner,
		CompletionParser parser) {
	this.completionContext = completionContext;
	this.typeRoot = typeRoot;
	this.compilationUnitDeclaration = compilationUnitDeclaration;
	this.lookupEnvironment = lookupEnvironment;
	this.assistScope = assistScope;
	this.assistNode = assistNode;
	this.assistNodeParent = assistNodeParent;
	this.owner = owner;
	this.parser = parser;
}
 
Example 4
Source Project: Pydev   Source File: JavaZipModule.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets tuples with the java element and the corresponding completion proposal for that element.
 *
 * @param contents the contents that should be set for doing the code-completion
 * @param completionOffset the offset where the code completion should be requested
 * @param filterCompletionName if specified, only return matches from elements that have the name passed (otherwise it should be null)
 * @return a list of tuples corresponding to the element and the proposal for the gotten elements
 * @throws JavaModelException
 */
@Override
protected List<Tuple<IJavaElement, CompletionProposal>> getJavaCompletionProposals(String contents,
        int completionOffset, final String filterCompletionName) throws JavaModelException {

    final List<Tuple<IJavaElement, CompletionProposal>> ret = new ArrayList<Tuple<IJavaElement, CompletionProposal>>();

    IClasspathEntry entries[] = getClasspathEntries();
    //Using old version for compatibility with eclipse 3.2
    ICompilationUnit unit = new WorkingCopyOwner() {
    }.newWorkingCopy(name, entries, null, new NullProgressMonitor());
    unit.getBuffer().setContents(contents);
    CompletionProposalCollector collector = createCollector(filterCompletionName, ret, unit);

    unit.codeComplete(completionOffset, collector); //fill the completions while searching it
    return ret;
}
 
Example 5
public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
	switch (token.charAt(0)) {
		case JEM_PACKAGEFRAGMENTROOT:
			String rootPath = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
			token = null;
			while (memento.hasMoreTokens()) {
				token = memento.nextToken();
				// https://bugs.eclipse.org/bugs/show_bug.cgi?id=331821
				if (token == MementoTokenizer.PACKAGEFRAGMENT || token == MementoTokenizer.COUNT) {
					break;
				}
				rootPath += token;
			}
			JavaElement root = (JavaElement)getPackageFragmentRoot(new Path(rootPath));
			if (token != null && token.charAt(0) == JEM_PACKAGEFRAGMENT) {
				return root.getHandleFromMemento(token, memento, owner);
			} else {
				return root.getHandleFromMemento(memento, owner);
			}
	}
	return null;
}
 
Example 6
private ITypeHierarchy getCachedHierarchy(IType type, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	IType rep= fUnionFind.find(type);
	if (rep != null) {
		Collection<IType> collection= fRootReps.get(rep);
		for (Iterator<IType> iter= collection.iterator(); iter.hasNext();) {
			IType root= iter.next();
			ITypeHierarchy hierarchy= fRootHierarchies.get(root);
			if (hierarchy == null) {
				hierarchy= root.newTypeHierarchy(owner, new SubProgressMonitor(monitor, 1));
				fRootHierarchies.put(root, hierarchy);
			}
			if (hierarchy.contains(type)) {
				return hierarchy;
			}
		}
	}
	return null;
}
 
Example 7
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 8
private ITypeHierarchy getCachedHierarchy(IType type, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	IType rep= fUnionFind.find(type);
	if (rep != null) {
		Collection<IType> collection= fRootReps.get(rep);
		for (Iterator<IType> iter= collection.iterator(); iter.hasNext();) {
			IType root= iter.next();
			ITypeHierarchy hierarchy= fRootHierarchies.get(root);
			if (hierarchy == null) {
				hierarchy= root.newTypeHierarchy(owner, new SubProgressMonitor(monitor, 1));
				fRootHierarchies.put(root, hierarchy);
			}
			if (hierarchy.contains(type))
				return hierarchy;
		}
	}
	return null;
}
 
Example 9
Source Project: jdt-codemining   Source File: DeclaringType.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void codeComplete(char[] snippet, int insertion, int position, char[][] localVariableTypeNames,
		char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic, ICompletionRequestor requestor,
		WorkingCopyOwner owner) throws JavaModelException {
	// TODO Auto-generated method stub

}
 
Example 10
Source Project: jdt-codemining   Source File: DeclaringType.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void codeComplete(char[] snippet, int insertion, int position, char[][] localVariableTypeNames,
		char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic, CompletionRequestor requestor,
		WorkingCopyOwner owner) throws JavaModelException {
	// TODO Auto-generated method stub

}
 
Example 11
Source Project: jdt-codemining   Source File: DeclaringType.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void codeComplete(char[] snippet, int insertion, int position, char[][] localVariableTypeNames,
		char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic, CompletionRequestor requestor,
		WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	// TODO Auto-generated method stub

}
 
Example 12
/**
 * @see IJavaProject#findType(String, String, WorkingCopyOwner, IProgressMonitor)
 */
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaModelException {
	NameLookup lookup = newNameLookup(owner);
	return findType(
		packageName,
		typeQualifiedName,
		lookup,
		true, // consider secondary types
		progressMonitor);
}
 
Example 13
@Override
public WorkingCopyOwner getWorkingCopyOwner(final IJavaProject javaProject, final ResourceSet resourceSet) {
	return new WorkingCopyOwner() {
		@Override
		public String findSource(String typeName, String packageName) {
			if (packageName.startsWith("java"))
				return super.findSource(typeName, packageName);
			QualifiedName qn = toQualifiedName(packageName, typeName);
			final IResourceDescriptions descriptions = descriptionsProvider.getResourceDescriptions(resourceSet);
			Iterator<IEObjectDescription> exportedObjects = descriptions.getExportedObjects(TypesPackage.Literals.JVM_DECLARED_TYPE, qn, false).iterator();
			while (exportedObjects.hasNext()) {
				IEObjectDescription candidate = exportedObjects.next();
				URI uri = candidate.getEObjectURI();
				if (uri.isPlatformResource() && URI.decode(uri.segment(1)).equals(javaProject.getElementName())) {
					IResourceDescription resourceDescription = descriptions.getResourceDescription(uri.trimFragment());
					return getSource(typeName, packageName, candidate, resourceSet, resourceDescription);
				}
			}
			return super.findSource(typeName, packageName);
		}
		
		
		/**
		 * not implemented because we don't have a proper index for Java package names and the very rare cases in which this would
		 * cause trouble are not worth the general degrade in performance.
		 */
		@Override public boolean isPackage(String[] pkg) {
			return super.isPackage(pkg);
		}
	};
}
 
Example 14
Source Project: xtext-eclipse   Source File: JdtBasedTypeFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
ParameterNameInitializer createParameterNameInitializer(
		IMethodBinding method,
		WorkingCopyOwner workingCopyOwner,
		JvmExecutable result,
		String handleIdentifier,
		String[] path,
		String name,
		SegmentSequence signaturex) {
	if (method.isConstructor()) {
		ITypeBinding declarator = method.getDeclaringClass();
		if (declarator.isEnum()) {
			return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
		}
		if (declarator.isMember()) {
			return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex) {
				@Override
				protected void setParameterNames(IMethod javaMethod, java.util.List<JvmFormalParameter> parameters) throws JavaModelException {
					String[] parameterNames = javaMethod.getParameterNames();
					int size = parameters.size();
					if (size == parameterNames.length) {
						super.setParameterNames(javaMethod, parameters);
					} else if (size == parameterNames.length - 1) {
						for (int i = 1; i < parameterNames.length; i++) {
							String string = parameterNames[i];
							parameters.get(i - 1).setName(string);
						}
					} else {
						throw new IllegalStateException("unmatching arity for java method "+javaMethod.toString()+" and "+getExecutable().getIdentifier());
					}
				}
			};
		}
	}
	return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
}
 
Example 15
Source Project: xtext-eclipse   Source File: JdtBasedTypeFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
ParameterNameInitializer createParameterNameInitializer(IMethodBinding method, WorkingCopyOwner workingCopyOwner,
		JvmExecutable result, String handleIdentifier, String[] path, String name, SegmentSequence signaturex) {
	if (method.isConstructor() && method.getDeclaringClass().isEnum()) {
		return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
	} else {
		return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
	}
}
 
Example 16
Source Project: xtext-eclipse   Source File: JdtBasedTypeFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @noreference This constructor is not intended to be referenced by clients.
 */
protected ParameterNameInitializer(WorkingCopyOwner workingCopyOwner, JvmExecutable executable, String handleIdentifier, String[] path, String name, CharSequence signature) {
	super();
	this.workingCopyOwner = workingCopyOwner;
	this.executable = executable;
	this.handleIdentifier = handleIdentifier;
	this.path = path;
	this.name = name;
	this.signature = signature;
}
 
Example 17
/**
 * @see IJavaProject#findType(String, String, WorkingCopyOwner)
 */
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner) throws JavaModelException {
	NameLookup lookup = newNameLookup(owner);
	return findType(
		packageName,
		typeQualifiedName,
		lookup,
		false, // do not consider secondary types
		null);
}
 
Example 18
private static SearchMatch[] getFieldReferencesIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException {
	List<SearchMatch> referencedFields= new ArrayList<>();
	pm.beginTask("", elements.length); //$NON-NLS-1$
	for (int i = 0; i < elements.length; i++) {
		referencedFields.addAll(getFieldReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
	}
	pm.done();
	return referencedFields.toArray(new SearchMatch[referencedFields.size()]);
}
 
Example 19
private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
	ICompilationUnit[] newWorkingCopies= null;
	WorkingCopyOwner newWCOwner= new WorkingCopyOwner() { /* must subclass */ };
	try {
		pm.beginTask("", 2); //$NON-NLS-1$
		RefactoringStatus result= new RefactoringStatus();
		SearchResultGroup[] oldReferences= fReferences;

		List<ICompilationUnit> compilationUnitsToModify= new ArrayList<>();
		if (fIsComposite) {
			// limited change set, no accessors.
			for (int i= 0; i < oldReferences.length; i++) {
				compilationUnitsToModify.add(oldReferences[i].getCompilationUnit());
			}
			compilationUnitsToModify.add(fField.getCompilationUnit());
		} else {
			// include all cus, including accessors
			compilationUnitsToModify.addAll(Arrays.asList(fChangeManager.getAllCompilationUnits()));
		}

		newWorkingCopies= RenameAnalyzeUtil.createNewWorkingCopies(compilationUnitsToModify.toArray(new ICompilationUnit[compilationUnitsToModify.size()]),
				fChangeManager, newWCOwner, new SubProgressMonitor(pm, 1));

		SearchResultGroup[] newReferences= getNewReferences(new SubProgressMonitor(pm, 1), result, newWCOwner, newWorkingCopies);
		result.merge(RenameAnalyzeUtil.analyzeRenameChanges2(fChangeManager, oldReferences, newReferences, getNewElementName()));
		return result;
	} finally{
		pm.done();
		if (newWorkingCopies != null){
			for (int i= 0; i < newWorkingCopies.length; i++) {
				newWorkingCopies[i].discardWorkingCopy();
			}
		}
	}
}
 
Example 20
Source Project: eclipse.jdt.ls   Source File: RippleMethodFinder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static IMethod[] getRelatedMethods(IMethod method, IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
	try {
		if (!isVirtual(method)) {
			return new IMethod[]{ method };
		}

		return new RippleMethodFinder(method).getAllRippleMethods(pm, owner);
	} finally {
		pm.done();
	}
}
 
Example 21
private void createHierarchyOfDeclarations(IProgressMonitor pm, WorkingCopyOwner owner) throws JavaModelException {
	IRegion region= JavaCore.newRegion();
	for (Iterator<IMethod> iter= fDeclarations.iterator(); iter.hasNext();) {
		IType declaringType= iter.next().getDeclaringType();
		region.add(declaringType);
	}
	fHierarchy= JavaCore.newTypeHierarchy(region, owner, pm);
}
 
Example 22
DefaultBindingResolver(LookupEnvironment lookupEnvironment, WorkingCopyOwner workingCopyOwner, BindingTables bindingTables, boolean isRecoveringBindings, boolean fromJavaProject) {
	this.newAstToOldAst = new HashMap();
	this.astNodesToBlockScope = new HashMap();
	this.bindingsToAstNodes = new HashMap();
	this.bindingTables = bindingTables;
	this.scope = new CompilationUnitScope(new CompilationUnitDeclaration(null, null, -1), lookupEnvironment);
	this.workingCopyOwner = workingCopyOwner;
	this.isRecoveringBindings = isRecoveringBindings;
	this.fromJavaProject = fromJavaProject;
}
 
Example 23
Source Project: eclipse.jdt.ls   Source File: RenameAnalyzeUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
static ICompilationUnit[] createNewWorkingCopies(ICompilationUnit[] compilationUnitsToModify, TextChangeManager manager, WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
	pm.beginTask("", compilationUnitsToModify.length); //$NON-NLS-1$
	ICompilationUnit[] newWorkingCopies= new ICompilationUnit[compilationUnitsToModify.length];
	for (int i= 0; i < compilationUnitsToModify.length; i++) {
		ICompilationUnit cu= compilationUnitsToModify[i];
		newWorkingCopies[i]= createNewWorkingCopy(cu, manager, owner, new SubProgressMonitor(pm, 1));
	}
	pm.done();
	return newWorkingCopies;
}
 
Example 24
public static IMethod[] getRelatedMethods(IMethod method, boolean excludeBinaries, IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
	try{
		if (! MethodChecks.isVirtual(method)) {
			return new IMethod[]{ method };
		}

		return new RippleMethodFinder2(method, excludeBinaries).getAllRippleMethods(pm, owner);
	} finally{
		pm.done();
	}
}
 
Example 25
public static IMethod[] getRelatedMethods(IMethod method, ReferencesInBinaryContext binaryRefs, IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
	try {
		if (! MethodChecks.isVirtual(method)) {
			return new IMethod[]{ method };
		}

		return new RippleMethodFinder2(method, binaryRefs).getAllRippleMethods(pm, owner);
	} finally{
		pm.done();
	}
}
 
Example 26
@Override
public CompilationUnit newCompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) {
    if (ContentTypeUtils.isGroovyLikeFileName(name)) {
        return new BonitaScriptGroovyCompilationUnit(parent, name, owner) ;
    } else {
        return new CompilationUnit(parent, name, owner);
    }
}
 
Example 27
/**
    * Sets the working copy owner used when resolving bindings, where
    * <code>null</code> means the primary owner. Defaults to the primary owner.
    *
 * @param owner the owner of working copies that take precedence over underlying
 *   compilation units, or <code>null</code> if the primary owner should be used
    */
public void setWorkingCopyOwner(WorkingCopyOwner owner) {
    if (owner == null) {
		this.workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
	} else {
		this.workingCopyOwner = owner;
 	}
}
 
Example 28
private void createHierarchyOfDeclarations(IProgressMonitor pm, WorkingCopyOwner owner) throws JavaModelException {
	IRegion region= JavaCore.newRegion();
	for (Iterator<IMethod> iter= fDeclarations.iterator(); iter.hasNext();) {
		IType declaringType= iter.next().getDeclaringType();
		region.add(declaringType);
	}
	fHierarchy= JavaCore.newTypeHierarchy(region, owner, pm);
}
 
Example 29
public static CompilationUnit convert(
		CompilationUnitDeclaration compilationUnitDeclaration,
		char[] source,
		int apiLevel,
		Map options,
		boolean needToResolveBindings,
		WorkingCopyOwner owner,
		DefaultBindingResolver.BindingTables bindingTables,
		int flags,
		IProgressMonitor monitor,
		boolean fromJavaProject) {
	BindingResolver resolver = null;
	AST ast = AST.newAST(apiLevel);
	ast.setDefaultNodeFlag(ASTNode.ORIGINAL);
	CompilationUnit compilationUnit = null;
	ASTConverter converter = new ASTConverter(options, needToResolveBindings, monitor);
	if (needToResolveBindings) {
		resolver = new DefaultBindingResolver(compilationUnitDeclaration.scope, owner, bindingTables, (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, fromJavaProject);
		ast.setFlag(flags | AST.RESOLVED_BINDINGS);
	} else {
		resolver = new BindingResolver();
		ast.setFlag(flags);
	}
	ast.setBindingResolver(resolver);
	converter.setAST(ast);
	compilationUnit = converter.convert(compilationUnitDeclaration, source);
	compilationUnit.setLineEndTable(compilationUnitDeclaration.compilationResult.getLineSeparatorPositions());
	ast.setDefaultNodeFlag(0);
	ast.setOriginalModificationCount(ast.modificationCount());
	return compilationUnit;
}
 
Example 30
Source Project: eclipse.jdt.ls   Source File: MavenClasspathTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMain() throws Exception {
	IProject project = importMavenProject("classpathtest");
	IJavaProject javaProject = JavaCore.create(project);
	IType type = javaProject.findType("main.App");
	ICompilationUnit cu = type.getCompilationUnit();
	openDocument(cu, cu.getSource(), 1);
	final DiagnosticsHandler handler = new DiagnosticsHandler(javaClient, cu);
	WorkingCopyOwner wcOwner = getWorkingCopy(handler);
	cu.reconcile(ICompilationUnit.NO_AST, true, wcOwner, null);
	assertTrue("There aren't any problems", handler.getProblems().size() == 1);
}