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

The following examples show how to use org.eclipse.jdt.core.IType#getCompilationUnit() . 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: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Add additional source types
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
	// case of SearchableEnvironment of an IJavaProject is used
	ISourceType sourceType = sourceTypes[0];
	while (sourceType.getEnclosingType() != null)
		sourceType = sourceType.getEnclosingType();
	if (sourceType instanceof SourceTypeElementInfo) {
		// get source
		SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
		IType type = elementInfo.getHandle();
		ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
		accept(sourceUnit, accessRestriction);
	} else {
		CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
		CompilationUnitDeclaration unit =
			SourceTypeConverter.buildCompilationUnit(
				sourceTypes,
				SourceTypeConverter.FIELD_AND_METHOD // need field and methods
				| SourceTypeConverter.MEMBER_TYPE, // need member types
				// no need for field initialization
				this.lookupEnvironment.problemReporter,
				result);
		this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
		this.lookupEnvironment.completeTypeBindings(unit, true);
	}
}
 
Example 2
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 3
Source File: TargetProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static TargetProvider create(MethodDeclaration declaration) {
	IMethodBinding method= declaration.resolveBinding();
	if (method == null)
		return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_method_declaration_not_unique));
	ITypeBinding type= method.getDeclaringClass();
	if (type.isLocal()) {
		if (((IType) type.getJavaElement()).isBinary()) {
			return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_cannot_local_method_in_binary));
		} else {
			IType declaringClassOfLocal= (IType) type.getDeclaringClass().getJavaElement();
			return new LocalTypeTargetProvider(declaringClassOfLocal.getCompilationUnit(), declaration);
		}
	} else {
		return new MemberTypeTargetProvider(declaration.resolveBinding());
	}
}
 
Example 4
Source File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateToString(IType type, LspVariableBinding[] fields) {
	if (type == null || type.getCompilationUnit() == null) {
		return null;
	}

	Preferences preferences = JavaLanguageServerPlugin.getPreferencesManager().getPreferences();
	ToStringGenerationSettingsCore settings = new ToStringGenerationSettingsCore();
	settings.overrideAnnotation = true;
	settings.createComments = preferences.isCodeGenerationTemplateGenerateComments();
	settings.useBlocks = preferences.isCodeGenerationTemplateUseBlocks();
	settings.stringFormatTemplate = StringUtils.isBlank(preferences.getGenerateToStringTemplate()) ? DEFAULT_TEMPLATE : preferences.getGenerateToStringTemplate();
	settings.toStringStyle = getToStringStyle(preferences.getGenerateToStringCodeStyle());
	settings.skipNulls = preferences.isGenerateToStringSkipNullValues();
	settings.customArrayToString = preferences.isGenerateToStringListArrayContents();
	settings.limitElements = preferences.getGenerateToStringLimitElements() > 0;
	settings.limitValue = Math.max(preferences.getGenerateToStringLimitElements(), 0);
	settings.customBuilderSettings = new CustomBuilderSettings();
	if (type.getCompilationUnit().getJavaProject() != null) {
		String version = type.getCompilationUnit().getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true);
		settings.is50orHigher = !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_5);
		settings.is60orHigher = !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6);
	}

	return generateToString(type, fields, settings);
}
 
Example 5
Source File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static WorkspaceEdit generateToString(GenerateToStringParams params) {
	IType type = SourceAssistProcessor.getSelectionType(params.context);
	if (type == null || type.getCompilationUnit() == null) {
		return null;
	}

	TextEdit edit = generateToString(type, params.fields);
	return (edit == null) ? null : SourceAssistProcessor.convertToWorkspaceEdit(type.getCompilationUnit(), edit);
}
 
Example 6
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 7
Source File: SortMembersAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ICompilationUnit getSelectedCompilationUnit(IStructuredSelection selection) {
	if (selection.size() == 1) {
		Object element= selection.getFirstElement();
		if (element instanceof ICompilationUnit) {
			return (ICompilationUnit) element;
		} else if (element instanceof IType) {
			IType type= (IType) element;
			if (type.getParent() instanceof ICompilationUnit) { // only top level types
				return type.getCompilationUnit();
			}
		}
	}
	return null;
}
 
Example 8
Source File: HierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {

		this.hierarchy = hierarchy;
		JavaProject project = (JavaProject) hierarchy.javaProject();

		IType focusType = hierarchy.getType();
		org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType == null ? null : focusType.getCompilationUnit();
		org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.hierarchy.workingCopies;
		org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside;
		if (unitToLookInside != null) {
			int wcLength = workingCopies == null ? 0 : workingCopies.length;
			if (wcLength == 0) {
				unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
			} else {
				unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength+1];
				unitsToLookInside[0] = unitToLookInside;
				System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
			}
		} else {
			unitsToLookInside = workingCopies;
		}
		if (project != null) {
			SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
			this.nameLookup = searchableEnvironment.nameLookup;
			this.hierarchyResolver =
				new HierarchyResolver(
					searchableEnvironment,
					project.getOptions(true),
					this,
					new DefaultProblemFactory());
		}
		this.infoToHandle = new HashMap(5);
		this.focusQualifiedName = focusType == null ? null : focusType.getFullyQualifiedName();
	}
 
Example 9
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the visibility threshold from a type to a method.
 *
 * @param referencing the referencing type
 * @param referenced the referenced method
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToMethod(final IType referencing, final IMethod referenced, final IProgressMonitor monitor) throws JavaModelException {
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	if (referenced.getDeclaringType().equals(referencing))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced.getDeclaringType())) {
				keyword= ModifierKeyword.PROTECTED_KEYWORD;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
		if (referenced.getDeclaringType().getDeclaringType() != null)
			keyword= null;
		else
			keyword= ModifierKeyword.PRIVATE_KEYWORD;
	} else if (referencedUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example 10
Source File: JavaUiCodeAppenderImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void revealInEditor(IType objectClass, IJavaElement elementToReveal)
        throws JavaModelException, PartInitException {
    ICompilationUnit compilationUnit = objectClass.getCompilationUnit();
    IEditorPart javaEditor = JavaUI.openInEditor(compilationUnit);
    JavaUI.revealInEditor(javaEditor, elementToReveal);
}
 
Example 11
Source File: SignatureHelpHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSignatureHelp_varargs2() throws JavaModelException {
	IJavaProject javaProject = JavaCore.create(project);
	IType type = javaProject.findType("test1.Varargs");
	ICompilationUnit cu = type.getCompilationUnit();
	SignatureHelp help = getSignatureHelp(cu, 4, 16);
	assertNotNull(help);
	assertEquals(2, help.getSignatures().size());
	assertTrue(help.getSignatures().get(help.getActiveSignature()).getLabel().equals("run(Class<?> clazz, String... args) : void"));
}
 
Example 12
Source File: GenerateDelegateMethodsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean supportsGenerateDelegateMethods(IType type) throws JavaModelException {
	if (type == null || type.getCompilationUnit() == null || type.isAnnotation() || type.isInterface()) {
		return false;
	}

	IField[] fields = type.getFields();
	int count = 0;
	for (IField field : fields) {
		if (!JdtFlags.isEnum(field) && !hasPrimitiveType(field) && !isArray(field)) {
			count++;
		}
	}

	return count > 0;
}
 
Example 13
Source File: OverrideMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
	if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
		final IType type= (IType) selection.getFirstElement();
		return type.getCompilationUnit() != null && !type.isInterface();
	}
	if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
		return true;
	return false;
}
 
Example 14
Source File: SerialVersionHashOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IFile getClassfile(ITypeBinding typeBinding) throws CoreException {
	// bug 191943
	IType type= (IType) typeBinding.getJavaElement();
	if (type == null || type.getCompilationUnit() == null) {
		return null;
	}

	IRegion region= JavaCore.newRegion();
	region.add(type.getCompilationUnit());

	String name= typeBinding.getBinaryName();
	if (name != null) {
		int packStart= name.lastIndexOf('.');
		if (packStart != -1) {
			name= name.substring(packStart + 1);
		}
	} else {
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, CorrectionMessages.SerialVersionHashOperation_error_classnotfound));
	}

	name += ".class"; //$NON-NLS-1$

	IResource[] classFiles= JavaCore.getGeneratedResources(region, false);
	for (int i= 0; i < classFiles.length; i++) {
		IResource resource= classFiles[i];
		if (resource.getType() == IResource.FILE && resource.getName().equals(name)) {
			return (IFile) resource;
		}
	}
	throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, CorrectionMessages.SerialVersionHashOperation_error_classnotfound));
}
 
Example 15
Source File: AddDelegateMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean canRunOn(IType type) throws JavaModelException {
	if (type == null || type.getCompilationUnit() == null) {
		MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_not_in_source_file);
		return false;
	} else if (type.isAnnotation()) {
		MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_annotation_not_applicable);
		return false;
	} else if (type.isInterface()) {
		MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_interface_not_applicable);
		return false;
	}
	return canRunOn(type.getFields());
}
 
Example 16
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getGenerateConstructorsAction(CodeActionParams params, IInvocationContext context, IType type, String kind) {
	try {
		if (type == null || type.isAnnotation() || type.isInterface() || type.isAnonymous() || type.getCompilationUnit() == null) {
			return Optional.empty();
		}
	} catch (JavaModelException e) {
		return Optional.empty();
	}

	if (preferenceManager.getClientPreferences().isGenerateConstructorsPromptSupported()) {
		CheckConstructorsResponse status = GenerateConstructorsHandler.checkConstructorStatus(type);
		if (status.constructors.length == 0) {
			return Optional.empty();
		}
		if (status.constructors.length == 1 && status.fields.length == 0) {
			TextEdit edit = GenerateConstructorsHandler.generateConstructors(type, status.constructors, status.fields);
			return convertToWorkspaceEditAction(params.getContext(), type.getCompilationUnit(), ActionMessages.GenerateConstructorsAction_label, kind, edit);
		}

		Command command = new Command(ActionMessages.GenerateConstructorsAction_ellipsisLabel, COMMAND_ID_ACTION_GENERATECONSTRUCTORSPROMPT, Collections.singletonList(params));
		if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS)) {
			CodeAction codeAction = new CodeAction(ActionMessages.GenerateConstructorsAction_ellipsisLabel);
			codeAction.setKind(kind);
			codeAction.setCommand(command);
			codeAction.setDiagnostics(Collections.emptyList());
			return Optional.of(Either.forRight(codeAction));
		} else {
			return Optional.of(Either.forLeft(command));
		}
	}

	return Optional.empty();
}
 
Example 17
Source File: JavaModuleInProject.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tries to get completions for a given element.
 */
private void getCompletionsForType(String contents, String filterCompletionName, IType type,
        final List<Tuple<IJavaElement, CompletionProposal>> ret) throws JavaModelException {
    ICompilationUnit unit = type.getCompilationUnit();
    if (unit == null) {
        return;
    }
    CompletionProposalCollector collector = createCollector(filterCompletionName, ret, unit);
    type.codeComplete(StringUtils.format(contents, name).toCharArray(), -1, 0, new char[0][0], new char[0][0],
            new int[0], false, collector);
}
 
Example 18
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean supportsHashCodeEquals(IInvocationContext context, IType type) {
	try {
		if (type == null || type.isAnnotation() || type.isInterface() || type.isEnum() || type.getCompilationUnit() == null) {
			return false;
		}
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		return (typeBinding == null) ? false : Arrays.stream(typeBinding.getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers())).findAny().isPresent();
	} catch (JavaModelException e) {
		return false;
	}
}
 
Example 19
Source File: TypeDeclarationFromSuperclassExtractor.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private Optional<CompilationUnit> getCompilationUnit(IType superClassType) {
    Optional<CompilationUnit> result = empty();
    if (superClassType.getCompilationUnit() != null) {
        result = ofNullable(compilationUnitParser.parse(superClassType.getCompilationUnit()));
    } else if (superClassType.getClassFile() != null) {
        result = ofNullable(compilationUnitParser.parse(superClassType.getClassFile()));
    }
    return result;
}
 
Example 20
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the enclosing type name has changed. The method
 * validates the enclosing type and returns the status of the validation. It also updates the
 * enclosing type model.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus enclosingTypeChanged() {
	StatusInfo status= new StatusInfo();
	fCurrEnclosingType= null;

	IPackageFragmentRoot root= getPackageFragmentRoot();

	fEnclosingTypeDialogField.enableButton(root != null);
	if (root == null) {
		status.setError(""); //$NON-NLS-1$
		return status;
	}

	String enclName= getEnclosingTypeText();
	if (enclName.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeEnterName);
		return status;
	}
	try {
		IType type= findType(root.getJavaProject(), enclName);
		if (type == null) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists);
			return status;
		}

		if (type.getCompilationUnit() == null) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotInCU);
			return status;
		}
		if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotEditable);
			return status;
		}

		fCurrEnclosingType= type;
		IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
		if (!enclosingRoot.equals(root)) {
			status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_EnclosingNotInSourceFolder);
		}
		return status;
	} catch (JavaModelException e) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists);
		JavaPlugin.log(e);
		return status;
	}
}