Java Code Examples for org.eclipse.jdt.core.IType#isBinary()

The following examples show how to use org.eclipse.jdt.core.IType#isBinary() . 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: JavaElementUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static boolean isMainType(IType type) throws JavaModelException{
	if (! type.exists()) {
		return false;
	}

	if (type.isBinary()) {
		return false;
	}

	if (type.getCompilationUnit() == null) {
		return false;
	}

	if (type.getDeclaringType() != null) {
		return false;
	}

	return isPrimaryType(type) || isCuOnlyType(type);
}
 
Example 2
Source File: JavaElementLinks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IType resolveType(IType baseType, String refTypeName) throws JavaModelException {
	if (refTypeName.length() == 0) {
		return baseType;
	}

	String[][] resolvedNames = baseType.resolveType(refTypeName);
	if (resolvedNames != null && resolvedNames.length > 0) {
		return baseType.getJavaProject().findType(resolvedNames[0][0], resolvedNames[0][1].replace('$', '.'), (IProgressMonitor) null);

	} else if (baseType.isBinary()) {
		// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=206597
		IType type = baseType.getJavaProject().findType(refTypeName, (IProgressMonitor) null);
		if (type == null) {
			// could be unqualified reference:
			type = baseType.getJavaProject().findType(baseType.getPackageFragment().getElementName() + '.' + refTypeName, (IProgressMonitor) null);
		}
		return type;

	} else {
		return null;
	}
}
 
Example 3
Source File: CompletionResultRequestor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void acceptType(IType type) {
	try {
		if (this.unitToSkip != null && this.unitToSkip.equals(type.getCompilationUnit())){
			return;
		}

		char[] packageName = type.getPackageFragment().getElementName().toCharArray();
		if (type.isBinary()) {
			// Tradeoff: type.getFlags() needs load the binary class into memory, which is
			// a little expensive for the code completion feature. So make a compromise
			// here and simply return the type modifier as public class. This will lose a
			// bit of precision, like type might be interface, enum, etc.
			this.requestor.acceptType(packageName, type.getElementName().toCharArray(), null, ClassFileConstants.AccPublic, null);
		} else {
			this.requestor.acceptType(packageName, type.getElementName().toCharArray(), null, type.getFlags(), null);
		}
	} catch (JavaModelException jme) {
		// ignore
	}
}
 
Example 4
Source File: JavaBrowsingContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Object[] getChildren(IType type) throws JavaModelException{
	IParent parent;
	if (type.isBinary())
		parent= type.getClassFile();
	else {
		parent= type.getCompilationUnit();
	}
	if (type.getDeclaringType() != null)
		return type.getChildren();

	// Add import declarations
	IJavaElement[] members= parent.getChildren();
	ArrayList<IJavaElement> tempResult= new ArrayList<IJavaElement>(members.length);
	for (int i= 0; i < members.length; i++)
		if ((members[i] instanceof IImportContainer))
			tempResult.add(members[i]);
	tempResult.addAll(Arrays.asList(type.getChildren()));
	return tempResult.toArray();
}
 
Example 5
Source File: JavaElementLinks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IType resolveType(IType baseType, String refTypeName) throws JavaModelException {
	if (refTypeName.length() == 0)
		return baseType;

	String[][] resolvedNames= baseType.resolveType(refTypeName);
	if (resolvedNames != null && resolvedNames.length > 0) {
		return baseType.getJavaProject().findType(resolvedNames[0][0], resolvedNames[0][1].replace('$', '.'), (IProgressMonitor) null);

	} else if (baseType.isBinary()) {
		// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=206597
		IType type= baseType.getJavaProject().findType(refTypeName, (IProgressMonitor) null);
		if (type == null) {
			// could be unqualified reference:
			type= baseType.getJavaProject().findType(baseType.getPackageFragment().getElementName() + '.' + refTypeName, (IProgressMonitor) null);
		}
		return type;

	} else {
		return null;
	}
}
 
Example 6
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected final void adjustTypeVisibility(final ITypeBinding binding) throws JavaModelException {
	Assert.isNotNull(binding);
	final IJavaElement element= binding.getJavaElement();
	if (element instanceof IType) {
		final IType type= (IType) element;
		if (!type.isBinary() && !type.isReadOnly() && !Flags.isPublic(type.getFlags())) {
			boolean same= false;
			final CompilationUnitRewrite rewrite= getCompilationUnitRewrite(fRewrites, type.getCompilationUnit());
			final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, rewrite.getRoot());
			if (declaration != null) {
				final ITypeBinding declaring= declaration.resolveBinding();
				if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
					same= true;
				final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
				final String modifier= same ? RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default : RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
				if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue()) && MemberVisibilityAdjustor.needsVisibilityAdjustments(type, keyword, fAdjustments))
					fAdjustments.put(type, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(type, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(type.getCompilationUnit(), declaration))));
			}
		}
	}
}
 
Example 7
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IType[] getCandidateTypes(final RefactoringStatus status, final IProgressMonitor monitor) throws JavaModelException {
	final IType declaring= getDeclaringType();
	final IType[] superTypes= declaring.newSupertypeHierarchy(fOwner, monitor).getAllSupertypes(declaring);
	final List<IType> list= new ArrayList<IType>(superTypes.length);
	int binary= 0;
	for (int index= 0; index < superTypes.length; index++) {
		final IType type= superTypes[index];
		if (type != null && type.exists() && !type.isReadOnly() && !type.isBinary() && !"java.lang.Object".equals(type.getFullyQualifiedName())) { //$NON-NLS-1$
			list.add(type);
		} else {
			if (type != null && type.isBinary()) {
				binary++;
			}
		}
	}
	if (superTypes.length == 1 && superTypes[0].getFullyQualifiedName().equals("java.lang.Object")) //$NON-NLS-1$
		status.addFatalError(RefactoringCoreMessages.PullUPRefactoring_not_java_lang_object);
	else if (superTypes.length == binary)
		status.addFatalError(RefactoringCoreMessages.PullUPRefactoring_no_all_binary);

	Collections.reverse(list);
	return list.toArray(new IType[list.size()]);
}
 
Example 8
Source File: MembersView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Answers if the given <code>element</code> is a valid
 * input for this part.
 *
 * @param 	element	the object to test
 * @return	<true> if the given element is a valid input
 */
@Override
protected boolean isValidInput(Object element) {
	if (element instanceof IType) {
		IType type= (IType)element;
		return type.isBinary() || type.getDeclaringType() == null;
	}
	return false;
}
 
Example 9
Source File: CompilationUnitCompletion.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if <code>signature</code> is a concrete type signature,
 * <code>false</code> if it is a type variable.
 *
 * @param signature the signature to check
 * @param context the context inside which to resolve the type
 * @return <code>true</code> if the given signature is a concrete type signature
 * @throws JavaModelException if finding the type fails
 */
private boolean isConcreteType(String signature, IType context) throws JavaModelException {
	// Inexpensive check for the variable type first
	if (Signature.TYPE_VARIABLE_SIGNATURE == Signature.getTypeSignatureKind(signature))
		return false;

	// try and resolve otherwise
	if (context.isBinary()) {
		return fUnit.getJavaProject().findType(SignatureUtil.stripSignatureToFQN(signature)) != null;
	} else {
		return context.resolveType(SignatureUtil.stripSignatureToFQN(signature)) != null;
	}
}
 
Example 10
Source File: MoveMembersWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IStatus validateDestinationType(IType type, String typeName){
	if (type == null || ! type.exists())
		return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format(RefactoringMessages.MoveMembersInputPage_not_found, BasicElementLabels.getJavaElementName(typeName)), null);
	if (type.isBinary())
		return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_no_binary, null);
	return Status.OK_STATUS;
}
 
Example 11
Source File: JavaElementUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isMainType(IType type) throws JavaModelException{
	if (! type.exists())
		return false;

	if (type.isBinary())
		return false;

	if (type.getCompilationUnit() == null)
		return false;

	if (type.getDeclaringType() != null)
		return false;

	return isPrimaryType(type) || isCuOnlyType(type);
}
 
Example 12
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an IField from the given field declaration and type.
 */
protected IJavaElement createHandle(FieldDeclaration fieldDeclaration, TypeDeclaration typeDeclaration, IJavaElement parent) {
	if (!(parent instanceof IType)) return parent;
	IType type = (IType) parent;

	switch (fieldDeclaration.getKind()) {
		case AbstractVariableDeclaration.FIELD :
		case AbstractVariableDeclaration.ENUM_CONSTANT :
			return ((IType) parent).getField(new String(fieldDeclaration.name));
	}
	if (type.isBinary()) {
		// do not return initializer for binary types
		// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=98378
		return type;
	}
	// find occurrence count of the given initializer in its type declaration
	int occurrenceCount = 0;
	FieldDeclaration[] fields = typeDeclaration.fields;
	int length = fields == null ? 0 : fields.length;
	for (int i = 0; i < length; i++) {
		if (fields[i].getKind() == AbstractVariableDeclaration.INITIALIZER) {
			occurrenceCount++;
			if (fields[i].equals(fieldDeclaration)) break;
		}
	}
	return ((IType) parent).getInitializer(occurrenceCount);
}
 
Example 13
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param fullyQualifiedTypeName the fully qualified name of the intermediary method
 * @return status for type name. Use {@link #setIntermediaryMethodName(String)} to check for overridden methods.
 */
public RefactoringStatus setIntermediaryTypeName(String fullyQualifiedTypeName) {
	IType target= null;

	try {
		if (fullyQualifiedTypeName.length() == 0)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_type_not_selected_error);

		// find type (now including secondaries)
		target= getProject().findType(fullyQualifiedTypeName, new NullProgressMonitor());
		if (target == null || !target.exists())
			return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_type_does_not_exist_error, BasicElementLabels.getJavaElementName(fullyQualifiedTypeName)));
		if (target.isAnnotation())
			return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_annotation);
		if (target.isInterface() && !(JavaModelUtil.is18OrHigher(target.getJavaProject()) && JavaModelUtil.is18OrHigher(getProject())))
			return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_on_interface);
	} catch (JavaModelException e) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_unable_determine_declaring_type);
	}

	if (target.isReadOnly())
		return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_readonly);

	if (target.isBinary())
		return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_binary);

	fIntermediaryType= target;

	return new RefactoringStatus();
}
 
Example 14
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkDeclaringType(){
	IType declaringType= getDeclaringType();

	if (declaringType.getFullyQualifiedName('.').equals("java.lang.Object")) //$NON-NLS-1$
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_Object);

	if (declaringType.isBinary())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_binary);

	if (declaringType.isReadOnly())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_read_only);

	return null;
}
 
Example 15
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public IType[] getCandidateTypes(final RefactoringStatus status, final IProgressMonitor monitor) {
	Assert.isNotNull(monitor);
	if (fPossibleCandidates == null || fPossibleCandidates.length == 0) {
		final IType declaring= getDeclaringType();
		if (declaring != null) {
			try {
				monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_computing_possible_types, 10);
				final IType superType= getDeclaringSuperTypeHierarchy(new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).getSuperclass(declaring);
				if (superType != null) {
					fPossibleCandidates= superType.newTypeHierarchy(fOwner, new SubProgressMonitor(monitor, 9, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).getSubtypes(superType);
					final LinkedList<IType> list= new LinkedList<IType>(Arrays.asList(fPossibleCandidates));
					final Set<String> names= new HashSet<String>();
					for (final Iterator<IType> iterator= list.iterator(); iterator.hasNext();) {
						final IType type= iterator.next();
						if (type.isReadOnly() || type.isBinary() || type.isAnonymous() || !type.isClass() || names.contains(type.getFullyQualifiedName()))
							iterator.remove();
						else
							names.add(type.getFullyQualifiedName());
					}
					fPossibleCandidates= list.toArray(new IType[list.size()]);
				}
			} catch (JavaModelException exception) {
				JavaPlugin.log(exception);
			} finally {
				monitor.done();
			}
		}
	}
	return fPossibleCandidates;
}
 
Example 16
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IType[] getAbstractDestinations(IProgressMonitor monitor) throws JavaModelException {
	IType[] allDirectSubclasses= getHierarchyOfDeclaringClass(monitor).getSubclasses(getDeclaringType());
	List<IType> result= new ArrayList<IType>(allDirectSubclasses.length);
	for (int index= 0; index < allDirectSubclasses.length; index++) {
		IType subclass= allDirectSubclasses[index];
		if (subclass.exists() && !subclass.isBinary() && !subclass.isReadOnly() && subclass.getCompilationUnit() != null && subclass.isStructureKnown())
			result.add(subclass);
	}
	return result.toArray(new IType[result.size()]);
}
 
Example 17
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public MatchLocator(
	SearchPattern pattern,
	SearchRequestor requestor,
	IJavaSearchScope scope,
	IProgressMonitor progressMonitor) {

	this.pattern = pattern;
	this.patternLocator = PatternLocator.patternLocator(this.pattern);
	this.matchContainer = this.patternLocator == null ? 0 : this.patternLocator.matchContainer();
	this.requestor = requestor;
	this.scope = scope;
	this.progressMonitor = progressMonitor;
	if (pattern instanceof PackageDeclarationPattern) {
		this.searchPackageDeclaration = true;
	} else if (pattern instanceof OrPattern) {
		this.searchPackageDeclaration = ((OrPattern)pattern).hasPackageDeclaration();
	} else {
		this.searchPackageDeclaration = false;
	}
	if (pattern instanceof MethodPattern) {
	    IType type = ((MethodPattern) pattern).declaringType;
	    if (type != null && !type.isBinary()) {
	    	SourceType sourceType = (SourceType) type;
	    	IMember local = sourceType.getOuterMostLocalContext();
	    	if (local instanceof IMethod) { // remember this method's range so we don't purge its statements.
	    		try {
	    			ISourceRange range = local.getSourceRange();
	    			this.sourceStartOfMethodToRetain  = range.getOffset();
	    			this.sourceEndOfMethodToRetain = this.sourceStartOfMethodToRetain + range.getLength() - 1; // offset is 0 based.
	    		} catch (JavaModelException e) {
	    			// drop silently. 
	    		}
	    	}
	    }
	}
}
 
Example 18
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean createHierarchyResolver(IType focusType, PossibleMatch[] possibleMatches) {
	// cache focus type if not a possible match
	char[][] compoundName = CharOperation.splitOn('.', focusType.getFullyQualifiedName().toCharArray());
	boolean isPossibleMatch = false;
	for (int i = 0, length = possibleMatches.length; i < length; i++) {
		if (CharOperation.equals(possibleMatches[i].compoundName, compoundName)) {
			isPossibleMatch = true;
			break;
		}
	}
	if (!isPossibleMatch) {
		if (focusType.isBinary()) {
			try {
				cacheBinaryType(focusType, null);
			} catch (JavaModelException e) {
				return false;
			}
		} else {
			// cache all types in the focus' compilation unit (even secondary types)
			accept((ICompilationUnit) focusType.getCompilationUnit(), null /*TODO no access restriction*/);
		}
	}

	// resolve focus type
	this.hierarchyResolver = new HierarchyResolver(this.lookupEnvironment, null/*hierarchy is not going to be computed*/);
	ReferenceBinding binding = this.hierarchyResolver.setFocusType(compoundName);
	return binding != null && binding.isValidBinding() && (binding.tagBits & TagBits.HierarchyHasProblems) == 0;
}
 
Example 19
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static boolean isExtractInterfaceAvailable(final IType type) throws JavaModelException {
	return Checks.isAvailable(type) && !type.isBinary() && !type.isReadOnly() && !type.isAnnotation() && !type.isAnonymous() && !type.isLambda();
}
 
Example 20
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(context);
	Assert.isNotNull(fTarget);
	final RefactoringStatus status= new RefactoringStatus();
	fChangeManager= new TextChangeManager();
	try {
		monitor.beginTask("", 4); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		status.merge(Checks.checkIfCuBroken(fMethod));
		if (!status.hasError()) {
			checkGenericTarget(new SubProgressMonitor(monitor, 1), status);
			if (status.isOK()) {
				final IType type= getTargetType();
				if (type != null) {
					if (type.isBinary() || type.isReadOnly() || !fMethod.exists() || fMethod.isBinary() || fMethod.isReadOnly())
						status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
					else {
						status.merge(Checks.checkIfCuBroken(type));
						if (!status.hasError()) {
							if (!type.exists() || type.isBinary() || type.isReadOnly())
								status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
							checkConflictingTarget(new SubProgressMonitor(monitor, 1), status);
							checkConflictingMethod(new SubProgressMonitor(monitor, 1), status);

							Checks.addModifiedFilesToChecker(computeModifiedFiles(fMethod.getCompilationUnit(), type.getCompilationUnit()), context);

							monitor.worked(1);
							if (!status.hasFatalError())
								fChangeManager= createChangeManager(status, new SubProgressMonitor(monitor, 1));
						}
					}
				} else
					status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_resolved_target, JavaStatusContext.create(fMethod)));
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}