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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#findPrimaryType() . 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
private static LaunchableResource toLaunchableResource(IResource resource) {
  if (resource == null) {
    return null;
  }
  IJavaElement javaElement = resource.getAdapter(IJavaElement.class);
  if (javaElement != null && javaElement.exists() && javaElement instanceof ICompilationUnit) {
    ICompilationUnit compilationUnit = (ICompilationUnit) javaElement;
    IType javaType = compilationUnit.findPrimaryType();
    if (javaType == null) {
      return null;
    }
    IMethod mainMethod = javaType.getMethod(
        "main", new String[] {Signature.createTypeSignature("String[]", false)});
    return new LaunchableResource(resource, mainMethod, javaType);
  }
  return new LaunchableResource(resource);
}
 
Example 2
/**
 * @since 2.3
 * @deprecated This method is not used anymore.
 */
@Deprecated
protected IType getPrimaryTypeFrom(ICompilationUnit cu) {
	try {
		if (cu.exists()) {
			IType primaryType = cu.findPrimaryType();
			if (primaryType != null)
				return primaryType;

			// if no exact match is found, return the first public type in CU (if any)
			for (IType type : cu.getTypes()) {
				if (Flags.isPublic(type.getFlags()))
					return type;
			}
		}
	} catch (JavaModelException e) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug(e, e);
	}
	return null;
}
 
Example 3
public static IType getSelectionType(IInvocationContext context) {
	ICompilationUnit unit = context.getCompilationUnit();
	ASTNode node = context.getCoveredNode();
	if (node == null) {
		node = context.getCoveringNode();
	}

	ITypeBinding typeBinding = null;
	while (node != null && !(node instanceof CompilationUnit)) {
		if (node instanceof AbstractTypeDeclaration) {
			typeBinding = ((AbstractTypeDeclaration) node).resolveBinding();
			break;
		} else if (node instanceof AnonymousClassDeclaration) { // Anonymous
			typeBinding = ((AnonymousClassDeclaration) node).resolveBinding();
			break;
		}

		node = node.getParent();
	}

	if (typeBinding != null && typeBinding.getJavaElement() instanceof IType) {
		return (IType) typeBinding.getJavaElement();
	}

	return unit.findPrimaryType();
}
 
Example 4
/**
 * Finds and returns the type for the given CU.
 *
 * @param cu	the compilation unit
 * @return	the type with same name as the given CU or the first type in the CU
 */
protected IType getTypeForCU(ICompilationUnit cu) {

	if (cu == null || !cu.exists())
		return null;

	// Use primary type if possible
	IType primaryType= cu.findPrimaryType();
	if (primaryType != null)
		return primaryType;

	// Use first top-level type
	try {
		IType[] types= cu.getTypes();
		if (types.length > 0)
			return types[0];
		else
			return null;
	} catch (JavaModelException ex) {
		return null;
	}
}
 
Example 5
protected IType getTypeForCU(ICompilationUnit cu) {
	// Use primary type if possible
	IType primaryType= cu.findPrimaryType();
	if (primaryType != null)
		return primaryType;

	// Use first top-level type
	try {
		IType[] types= cu.getTypes();
		if (types.length > 0)
			return types[0];
		else
			return null;
	} catch (JavaModelException ex) {
		return null;
	}
}
 
Example 6
@Override
protected boolean isDirty(URI uri) {
	if (uri == null)
		return false;
	if (URIHelperConstants.PROTOCOL.equals(uri.scheme())) {
		String path = uri.path();
		if (URIHelperConstants.PRIMITIVES.equals(path))
			return false;
		String topLevelTypeName = path.substring(URIHelperConstants.OBJECTS.length());
		ICompilationUnit[] workingCopies = JavaCore.getWorkingCopies(null);
		for(ICompilationUnit cu: workingCopies) {
			try {
				if (cu.hasUnsavedChanges()) {
					IType primaryType = cu.findPrimaryType();
					if (primaryType != null) {
						if (topLevelTypeName.equals(primaryType.getFullyQualifiedName())) {
							return true;
						}
					}
				}
			} catch (JavaModelException e) {
				// ignore
			}
		}
	}
	return super.isDirty(uri);
}
 
Example 7
private static SearchResultGroup getReferences(final ICompilationUnit copy, IProgressMonitor monitor) throws JavaModelException {
	final ICompilationUnit[] copies= new ICompilationUnit[] { copy};
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(copies);
	final IType type= copy.findPrimaryType();
	if (type == null) {
		return null;
	}
	SearchPattern pattern= createSearchPattern(type);
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(pattern);
	engine.setScope(scope);
	engine.setWorkingCopies(copies);
	engine.setRequestor(new IRefactoringSearchRequestor() {
		TypeOccurrenceCollector fTypeOccurrenceCollector= new TypeOccurrenceCollector(type);
		@Override
		public SearchMatch acceptSearchMatch(SearchMatch match) {
			try {
				return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
			} catch (CoreException e) {
				JavaLanguageServerPlugin.log(e);
				return null;
			}
		}
	});

	engine.searchPattern(monitor);
	final Object[] results= engine.getResults();
	// Assert.isTrue(results.length <= 1);
	// just 1 file or none, but inaccurate matches can play bad here (see
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=106127)
	for (int index= 0; index < results.length; index++) {
		SearchResultGroup group= (SearchResultGroup) results[index];
		if (group.getCompilationUnit().equals(copy)) {
			return group;
		}
	}
	return null;
}
 
Example 8
private static SearchResultGroup getReferences(final ICompilationUnit copy, IProgressMonitor monitor) throws JavaModelException {
	final ICompilationUnit[] copies= new ICompilationUnit[] { copy};
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(copies);
	final IType type= copy.findPrimaryType();
	if (type == null)
		return null;
	SearchPattern pattern= createSearchPattern(type);
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(pattern);
	engine.setScope(scope);
	engine.setWorkingCopies(copies);
	engine.setRequestor(new IRefactoringSearchRequestor() {
		TypeOccurrenceCollector fTypeOccurrenceCollector= new TypeOccurrenceCollector(type);
		public SearchMatch acceptSearchMatch(SearchMatch match) {
			try {
				return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
			} catch (CoreException e) {
				JavaPlugin.log(e);
				return null;
			}
		}
	});
	
	engine.searchPattern(monitor);
	final Object[] results= engine.getResults();
	// Assert.isTrue(results.length <= 1);
	// just 1 file or none, but inaccurate matches can play bad here (see
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=106127)
	for (int index= 0; index < results.length; index++) {
		SearchResultGroup group= (SearchResultGroup) results[index];
		if (group.getCompilationUnit().equals(copy))
			return group;
	}
	return null;
}
 
Example 9
public static IType getTypeAtOffset(JavaEditor editor) throws JavaModelException {
	IJavaElement element= SelectionConverter.getElementAtOffset(editor);
	IType type= (IType)element.getAncestor(IJavaElement.TYPE);
	if (type == null) {
		ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(editor);
		if (unit != null)
			type= unit.findPrimaryType();
	}
	return type;
}
 
Example 10
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException {
	StringBuffer dummyCU= new StringBuffer();
	String packName= cu.getParent().getElementName();
	IType type= cu.findPrimaryType();
	if (type == null) {
		return new String[0];
	}

	if (packName.length() > 0) {
		dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$
	}
	dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer  //$NON-NLS-1$//$NON-NLS-2$
	int offset= dummyCU.length();
	dummyCU.append("\n}\n }"); //$NON-NLS-1$

	ICompilationUnit newCU= null;
	try {
		newCU= cu.getWorkingCopy(null);
		newCU.getBuffer().setContents(dummyCU.toString());

		final HashSet<String> result= new HashSet<>();

		CompletionRequestor requestor= new CompletionRequestor(true) {
			@Override
			public void accept(CompletionProposal proposal) {
				if (elementName.equals(new String(proposal.getName()))) {
					CompletionProposal[] requiredProposals= proposal.getRequiredProposals();
					for (int i= 0; i < requiredProposals.length; i++) {
						CompletionProposal curr= requiredProposals[i];
						if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) {
							result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName()));
						}
					}
				}
			}
		};

		if (isMethod) {
			requestor.setIgnored(CompletionProposal.METHOD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
		} else {
			requestor.setIgnored(CompletionProposal.FIELD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
		}
		requestor.setFavoriteReferences(favorites);

		newCU.codeComplete(offset, requestor);

		return result.toArray(new String[result.size()]);
	} finally {
		if (newCU != null) {
			newCU.discardWorkingCopy();
		}
	}
}
 
Example 11
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException {
	StringBuffer dummyCU= new StringBuffer();
	String packName= cu.getParent().getElementName();
	IType type= cu.findPrimaryType();
	if (type == null)
		return new String[0];
	
	if (packName.length() > 0) {
		dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$
	}		
	dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer  //$NON-NLS-1$//$NON-NLS-2$
	int offset= dummyCU.length();
	dummyCU.append("\n}\n }"); //$NON-NLS-1$
	
	ICompilationUnit newCU= null;
	try {
		newCU= cu.getWorkingCopy(null);
		newCU.getBuffer().setContents(dummyCU.toString());
		
		final HashSet<String> result= new HashSet<String>();
		
		CompletionRequestor requestor= new CompletionRequestor(true) {
			@Override
			public void accept(CompletionProposal proposal) {
				if (elementName.equals(new String(proposal.getName()))) {
					CompletionProposal[] requiredProposals= proposal.getRequiredProposals();
					for (int i= 0; i < requiredProposals.length; i++) {
						CompletionProposal curr= requiredProposals[i];
						if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) {
							result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName()));
						}
					}
				}
			}
		};
		
		if (isMethod) {
			requestor.setIgnored(CompletionProposal.METHOD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
		} else {
			requestor.setIgnored(CompletionProposal.FIELD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
		}
		requestor.setFavoriteReferences(favorites);
		
		newCU.codeComplete(offset, requestor);
		
		return result.toArray(new String[result.size()]);
	} finally {
		if (newCU != null) {
			newCU.discardWorkingCopy();
		}	
	}	
}