org.eclipse.jdt.internal.corext.util.JavaModelUtil Java Examples

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil. 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: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Expression getAssignedValue(ProposalParameter context) {
	ASTNode parent= context.accessNode.getParent();
	ASTRewrite astRewrite= context.astRewrite;
	IJavaProject javaProject= context.compilationUnit.getJavaProject();
	IMethodBinding getter= findGetter(context);
	Expression getterExpression= null;
	if (getter != null) {
		getterExpression= astRewrite.getAST().newSimpleName("placeholder"); //$NON-NLS-1$
	}
	ITypeBinding type= context.variableBinding.getType();
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject);
	Expression result= GetterSetterUtil.getAssignedValue(parent, astRewrite, getterExpression, type, is50OrHigher);
	if (result != null && getterExpression != null && getterExpression.getParent() != null) {
		getterExpression.getParent().setStructuralProperty(getterExpression.getLocationInParent(), createMethodInvocation(context, getter, null));
	}
	return result;
}
 
Example #2
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean convertForLoops, boolean convertIterableForLoops, boolean makeFinal) {
	if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject()))
		return null;

	if (!convertForLoops && !convertIterableForLoops)
		return null;

	List<ConvertLoopOperation> operations= new ArrayList<ConvertLoopOperation>();
	ControlStatementFinder finder= new ControlStatementFinder(convertForLoops, convertIterableForLoops, makeFinal, operations);
	compilationUnit.accept(finder);

	if (operations.isEmpty())
		return null;

	CompilationUnitRewriteOperation[] ops= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new ConvertLoopFix(FixMessages.ControlStatementsFix_change_name, compilationUnit, ops, null);
}
 
Example #3
Source File: SARLProposalProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public boolean accept(int modifiers, char[] packageName, char[] simpleTypeName,
		char[][] enclosingTypeNames, String path) {
	// Avoid auto reference of type.
	final String fullName = JavaModelUtil.concatenateName(packageName, simpleTypeName);
	if (Objects.equals(this.modelFullName, fullName)) {
		return false;
	}
	//The following tests are done by the visibility filter.
	//if (TypeMatchFilters.isInternalClass(simpleTypeName, enclosingTypeNames)) {
	//	return false;
	//}
	//if (!TypeMatchFilters.isAcceptableByPreference().accept(modifiers, packageName,
	//		simpleTypeName, enclosingTypeNames, path)) {
	//	return false;
	//}
	// Final modifier test
	if (Flags.isFinal(modifiers)) {
		return false;
	}
	return this.visibilityFilter.accept(modifiers, packageName, simpleTypeName, enclosingTypeNames, path);
}
 
Example #4
Source File: RenameLocalVariableProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	initAST();
	if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local);
	}

	if (!Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, LambdaExpression.class)) {
		if (JavaModelUtil.is18OrHigher(fCu.getJavaProject())) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_initializers_and_lambda);
		}

		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers);
	}

	initNames();
	return new RefactoringStatus();
}
 
Example #5
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor, ICompilationUnit cu) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject());

	int typeKinds= SimilarElementsRequestor.ALL_TYPES;
	if (nameNode != null) {
		typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
	}

	ArrayList<TypeNameMatch> typeInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
	new SearchEngine().searchAllTypeNames(null, 0, simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor);

	ArrayList<TypeNameMatch> typeRefsFound= new ArrayList<TypeNameMatch>(typeInfos.size());
	for (int i= 0, len= typeInfos.size(); i < len; i++) {
		TypeNameMatch curr= typeInfos.get(i);
		if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
			if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example #6
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static boolean isIntroduceIndirectionAvailable(IMethod method) throws JavaModelException {
	if (method == null) {
		return false;
	}
	if (!method.exists()) {
		return false;
	}
	if (!method.isStructureKnown()) {
		return false;
	}
	if (method.isConstructor()) {
		return false;
	}
	if (method.getDeclaringType().isAnnotation()) {
		return false;
	}
	if (JavaModelUtil.isPolymorphicSignature(method)) {
		return false;
	}

	return true;
}
 
Example #7
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isIntroduceIndirectionAvailable(IMethod method) throws JavaModelException {
	if (method == null)
		return false;
	if (!method.exists())
		return false;
	if (!method.isStructureKnown())
		return false;
	if (method.isConstructor())
		return false;
	if (method.getDeclaringType().isAnnotation())
		return false;
	if (JavaModelUtil.isPolymorphicSignature(method))
		return false;

	return true;
}
 
Example #8
Source File: ReorgMoveAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void selectionChanged(IStructuredSelection selection) {
	if (!selection.isEmpty()) {
		if (ReorgUtils.containsOnlyProjects(selection.toList())) {
			setEnabled(createWorkbenchAction(selection).isEnabled());
			return;
		}
		try {
			List<?> elements= selection.toList();
			IResource[] resources= ReorgUtils.getResources(elements);
			IJavaElement[] javaElements= ReorgUtils.getJavaElements(elements);
			if (elements.size() != resources.length + javaElements.length)
				setEnabled(false);
			else
				setEnabled(RefactoringAvailabilityTester.isMoveAvailable(resources, javaElements));
		} catch (JavaModelException e) {
			// no ui here - this happens on selection changes
			// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
			if (JavaModelUtil.isExceptionToBeLogged(e))
				JavaPlugin.log(e);
			setEnabled(false);
		}
	} else
		setEnabled(false);
}
 
Example #9
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addImportToSourcePackageTypes(ICompilationUnit movedUnit, IProgressMonitor pm) throws CoreException{
	List<ICompilationUnit> cuList= Arrays.asList(fCus);
	IType[] allCuTypes= movedUnit.getAllTypes();
	IType[] referencedTypes= ReferenceFinderUtil.getTypesReferencedIn(allCuTypes, pm);
	ImportRewrite importEdit= getImportRewrite(movedUnit);
	importEdit.setFilterImplicitImports(false);
	IPackageFragment srcPack= (IPackageFragment)movedUnit.getParent();
	for (int i= 0; i < referencedTypes.length; i++) {
			IType iType= referencedTypes[i];
			if (! iType.exists())
				continue;
			if (!JavaModelUtil.isSamePackage(iType.getPackageFragment(), srcPack))
				continue;
			if (cuList.contains(iType.getCompilationUnit()))
				continue;
			importEdit.addImport(iType.getFullyQualifiedName('.'));
	}
}
 
Example #10
Source File: SourceJarLocations.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static File getSourceJarPath(IJavaElement element) throws JavaModelException {
	IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);

	if (root == null) {
		return null;
	}

	IClasspathEntry entry = root.getResolvedClasspathEntry();
	IPath sourceAttachment = entry.getSourceAttachmentPath();

	if (sourceAttachment == null) {
		return null; //No source jar could be found
	}

	return sourceAttachment.toFile();
}
 
Example #11
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IStatus containerChanged() {
	IStatus status= super.containerChanged();
    IPackageFragmentRoot root= getPackageFragmentRoot();
	if ((fTypeKind == ANNOTATION_TYPE || fTypeKind == ENUM_TYPE) && !status.matches(IStatus.ERROR)) {
    	if (root != null && !JavaModelUtil.is50OrHigher(root.getJavaProject())) {
    		// error as createType will fail otherwise (bug 96928)
			return new StatusInfo(IStatus.ERROR, Messages.format(NewWizardMessages.NewTypeWizardPage_warning_NotJDKCompliant, BasicElementLabels.getJavaElementName(root.getJavaProject().getElementName())));
    	}
    	if (fTypeKind == ENUM_TYPE) {
	    	try {
	    	    // if findType(...) == null then Enum is unavailable
	    	    if (findType(root.getJavaProject(), "java.lang.Enum") == null) //$NON-NLS-1$
	    	        return new StatusInfo(IStatus.WARNING, NewWizardMessages.NewTypeWizardPage_warning_EnumClassNotFound);
	    	} catch (JavaModelException e) {
	    	    JavaPlugin.log(e);
	    	}
    	}
    }

	fCurrPackageCompletionProcessor.setPackageFragmentRoot(root);
	if (root != null) {
		fEnclosingTypeCompletionProcessor.setPackageFragment(root.getPackageFragment("")); //$NON-NLS-1$
	}
	return status;
}
 
Example #12
Source File: JavadocConfigurationPropertyPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IClasspathEntry handleContainerEntry(IPath containerPath, IJavaProject jproject, IPath jarPath) throws JavaModelException {
	ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
	IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject);
	if (initializer == null || container == null) {
		setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_invalid_container, BasicElementLabels.getPathLabel(containerPath, false)));
		return null;
	}
	String containerName= container.getDescription();
	IStatus status= initializer.getAttributeStatus(containerPath, jproject, IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME);
	if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
		setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_not_supported, containerName));
		return null;
	}
	IClasspathEntry entry= JavaModelUtil.findEntryInContainer(container, jarPath);
	if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
		setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_read_only, containerName));
		fIsReadOnly= true;
		return entry;
	}
	Assert.isNotNull(entry);
	setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description);
	return entry;
}
 
Example #13
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject());

	int typeKinds= SimilarElementsRequestor.ALL_TYPES;
	if (nameNode != null) {
		typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
	}

	ArrayList<TypeNameMatch> typeInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, simpleTypeName.toCharArray(), matchMode, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);

	ArrayList<TypeNameMatch> typeRefsFound= new ArrayList<TypeNameMatch>(typeInfos.size());
	for (int i= 0, len= typeInfos.size(); i < len; i++) {
		TypeNameMatch curr= typeInfos.get(i);
		if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
			if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example #14
Source File: CreateCopyOfCompilationUnitChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IFile getOldFile(IProgressMonitor monitor) throws OperationCanceledException {
	try {
		monitor.beginTask("", 12); //$NON-NLS-1$
		String oldSource= super.getSource();
		IPath oldPath= super.getPath();
		String newTypeName= fNameQuery.getNewName();
		try {
			String newSource= getCopiedFileSource(new SubProgressMonitor(monitor, 9), fOldCu, newTypeName);
			setSource(newSource);
			setPath(fOldCu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(fOldCu, newTypeName)));
			return super.getOldFile(new SubProgressMonitor(monitor, 1));
		} catch (CoreException e) {
			setSource(oldSource);
			setPath(oldPath);
			return super.getOldFile(new SubProgressMonitor(monitor, 2));
		}
	} finally {
		monitor.done();
	}
}
 
Example #15
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 #16
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Change copyCuToPackage(ICompilationUnit cu, IPackageFragment dest, NewNameProposer nameProposer, INewNameQueries copyQueries) {
	// XXX workaround for bug 31998 we will have to disable renaming of
	// linked packages (and cus)
	IResource res= ReorgUtils.getResource(cu);
	if (res != null && res.isLinked()) {
		if (ResourceUtil.getResource(dest) instanceof IContainer)
			return copyFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest), nameProposer, copyQueries);
	}

	String newName= nameProposer.createNewName(cu, dest);
	Change simpleCopy= new CopyCompilationUnitChange(cu, dest, copyQueries.createStaticQuery(newName));
	if (newName == null || newName.equals(cu.getElementName()))
		return simpleCopy;

	try {
		IPath newPath= cu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(cu, newName));
		INewNameQuery nameQuery= copyQueries.createNewCompilationUnitNameQuery(cu, newName);
		return new CreateCopyOfCompilationUnitChange(newPath, cu.getSource(), cu, nameQuery);
	} catch (CoreException e) {
		// Using inferred change
		return simpleCopy;
	}
}
 
Example #17
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IStatus satisfiesPreconditions() {
	ForStatement statement= getForStatement();
	CompilationUnit ast= (CompilationUnit)statement.getRoot();

	IJavaElement javaElement= ast.getJavaElement();
	if (javaElement == null)
		return ERROR_STATUS;

	if (!JavaModelUtil.is50OrHigher(javaElement.getJavaProject()))
		return ERROR_STATUS;

	if (!validateInitializers(statement))
		return ERROR_STATUS;

	if (!validateExpression(statement))
		return ERROR_STATUS;

	if (!validateUpdaters(statement))
		return ERROR_STATUS;

	if (!validateBody(statement))
		return ERROR_STATUS;

	return Status.OK_STATUS;
}
 
Example #18
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createNewMethodDeclarationNode(MemberActionInfo info, TypeVariableMaplet[] mapping, CompilationUnitRewrite rewriter, MethodDeclaration oldMethod) throws JavaModelException {
	Assert.isTrue(!info.isFieldInfo());
	IMethod method= (IMethod) info.getMember();
	ASTRewrite rewrite= rewriter.getASTRewrite();
	AST ast= rewrite.getAST();
	MethodDeclaration newMethod= ast.newMethodDeclaration();
	copyBodyOfPushedDownMethod(rewrite, method, oldMethod, newMethod, mapping);
	newMethod.setConstructor(oldMethod.isConstructor());
	copyExtraDimensions(oldMethod, newMethod);
	if (info.copyJavadocToCopiesInSubclasses())
		copyJavadocNode(rewrite, oldMethod, newMethod);
	final IJavaProject project= rewriter.getCu().getJavaProject();
	if (info.isNewMethodToBeDeclaredAbstract() && JavaModelUtil.is50OrHigher(project) && JavaPreferencesSettings.getCodeGenerationSettings(project).overrideAnnotation) {
		final MarkerAnnotation annotation= ast.newMarkerAnnotation();
		annotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
		newMethod.modifiers().add(annotation);
	}
	copyAnnotations(oldMethod, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldMethod.getModifiers())));
	newMethod.setName(ast.newSimpleName(oldMethod.getName().getIdentifier()));
	copyReturnType(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	return newMethod;
}
 
Example #19
Source File: MainMethodSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	Object enclosingElement= match.getElement();
	if (enclosingElement instanceof IMethod) { // defensive code
		try {
			IMethod curr= (IMethod) enclosingElement;
			if (curr.isMainMethod()) {
				if (!considerExternalJars()) {
					IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(curr);
					if (root == null || root.isArchive()) {
						return;
					}
				}
				if (!considerBinaries() && curr.isBinary()) {
					return;
				}
				fResult.add(curr.getDeclaringType());
			}
		} catch (JavaModelException e) {
			JavaPlugin.log(e.getStatus());
		}
	}
}
 
Example #20
Source File: BuildPathSupport.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the compliance options from the given EE. If the result is not <code>null</code>,
 * it contains at least these core options:
 * <ul>
 * <li>{@link JavaCore#COMPILER_COMPLIANCE}</li>
 * <li>{@link JavaCore#COMPILER_SOURCE}</li>
 * <li>{@link JavaCore#COMPILER_CODEGEN_TARGET_PLATFORM}</li>
 * <li>{@link JavaCore#COMPILER_PB_ASSERT_IDENTIFIER}</li>
 * <li>{@link JavaCore#COMPILER_PB_ENUM_IDENTIFIER}</li>
 * <li>{@link JavaCore#COMPILER_CODEGEN_INLINE_JSR_BYTECODE} for compliance levels 1.5 and greater</li>
 * </ul>
 * 
 * @param ee the EE, can be <code>null</code>
 * @return the options, or <code>null</code> if none
 * @since 3.5
 */
public static Map<String, String> getEEOptions(IExecutionEnvironment ee) {
	if (ee == null)
		return null;
	Map<String, String> eeOptions= ee.getComplianceOptions();
	if (eeOptions == null)
		return null;
	
	Object complianceOption= eeOptions.get(JavaCore.COMPILER_COMPLIANCE);
	if (!(complianceOption instanceof String))
		return null;

	// eeOptions can miss some options, make sure they are complete:
	HashMap<String, String> options= new HashMap<String, String>();
	JavaModelUtil.setComplianceOptions(options, (String)complianceOption);
	options.putAll(eeOptions);
	return options;
}
 
Example #21
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addImportsToTargetUnit(final ICompilationUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaModelException {
	monitor.beginTask("", 2); //$NON-NLS-1$
	try {
		ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true);
		if (fTypeImports != null) {
			ITypeBinding type= null;
			for (final Iterator<ITypeBinding> iterator= fTypeImports.iterator(); iterator.hasNext();) {
				type= iterator.next();
				rewrite.addImport(type);
			}
		}
		if (fStaticImports != null) {
			IBinding binding= null;
			for (final Iterator<IBinding> iterator= fStaticImports.iterator(); iterator.hasNext();) {
				binding= iterator.next();
				rewrite.addStaticImport(binding);
			}
		}
		fTypeImports= null;
		fStaticImports= null;
		TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
		JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1));
	} finally {
		monitor.done();
	}
}
 
Example #22
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	initAST();
	if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local);

	if (!Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, LambdaExpression.class)) {
		if (JavaModelUtil.is18OrHigher(fCu.getJavaProject()))
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_initializers_and_lambda);

		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers);
	}

	initNames();
	return new RefactoringStatus();
}
 
Example #23
Source File: JarPackagerUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Tells whether the specified manifest main class is valid.
 * 
 * @param data the Jar package data
 * @param context the runnable context
 * @return <code>true</code> if a main class is specified and valid
 */
public static boolean isMainClassValid(JarPackageData data, IRunnableContext context) {
	if (data == null)
		return false;

	IType mainClass= data.getManifestMainClass();
	if (mainClass == null)
		// no main class specified
		return true;

	try {
		// Check if main method is in scope
		IFile file= (IFile)mainClass.getResource();
		if (file == null || !contains(asResources(data.getElements()), file))
			return false;

		// Test if it has a main method
		return JavaModelUtil.hasMainMethod(mainClass);
	} catch (JavaModelException e) {
		JavaPlugin.log(e.getStatus());
	}
	return false;
}
 
Example #24
Source File: ReplaceInvocationsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void selectionChanged(IStructuredSelection selection) {
	try {
		setEnabled(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
	} catch (JavaModelException e) {
		if (JavaModelUtil.isExceptionToBeLogged(e))
			JavaPlugin.log(e);
	}
}
 
Example #25
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Hook method that gets called when the superclass name has changed. The method
 * validates the superclass name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus superClassChanged() {
	StatusInfo status= new StatusInfo();
	IPackageFragmentRoot root= getPackageFragmentRoot();
	fSuperClassDialogField.enableButton(root != null);

	fSuperClassStubTypeContext= null;

	String sclassName= getSuperClass();
	if (sclassName.length() == 0) {
		// accept the empty field (stands for java.lang.Object)
		return status;
	}

	if (root != null) {
		Type type= TypeContextChecker.parseSuperClass(sclassName);
		if (type == null) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperClassName);
			return status;
		}
		if (type instanceof ParameterizedType && ! JavaModelUtil.is50OrHigher(root.getJavaProject())) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_SuperClassNotParameterized);
			return status;
		}
	} else {
		status.setError(""); //$NON-NLS-1$
	}
	return status;
}
 
Example #26
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a fake compilation unit.
 *
 * @param editorInput the URI editor input
 * @return the fake compilation unit
 * @since 3.3
 */
private ICompilationUnit createFakeCompiltationUnit(IURIEditorInput editorInput) {
	try {
		final URI uri= editorInput.getURI();
		final IFileStore fileStore= EFS.getStore(uri);
		final IPath path= URIUtil.toPath(uri);
		String fileStoreName= fileStore.getName();
		if (fileStoreName == null || path == null)
			return null;

		WorkingCopyOwner woc= new WorkingCopyOwner() {
			/*
			 * @see org.eclipse.jdt.core.WorkingCopyOwner#createBuffer(org.eclipse.jdt.core.ICompilationUnit)
			 * @since 3.2
			 */
			@Override
			public IBuffer createBuffer(ICompilationUnit workingCopy) {
				return new DocumentAdapter(workingCopy, fileStore, path);
			}
		};

		IClasspathEntry[] cpEntries= null;
		IJavaProject jp= findJavaProject(path);
		if (jp != null)
			cpEntries= jp.getResolvedClasspath(true);

		if (cpEntries == null || cpEntries.length == 0)
			cpEntries= new IClasspathEntry[] { JavaRuntime.getDefaultJREContainerEntry() };

		final ICompilationUnit cu= woc.newWorkingCopy(fileStoreName, cpEntries, getProgressMonitor());

		if (!isModifiable(editorInput))
			JavaModelUtil.reconcile(cu);

		return cu;
	} catch (CoreException ex) {
		return null;
	}
}
 
Example #27
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addOverrideAnnotation(IJavaProject project, ASTRewrite rewrite, MethodDeclaration decl, IMethodBinding binding) {
	if (binding.getDeclaringClass().isInterface()) {
		String version= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6))
			return; // not allowed in 1.5
		if (JavaCore.DISABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true)))
			return; // user doesn't want to use 1.6 style
	}
	
	Annotation marker= rewrite.getAST().newMarkerAnnotation();
	marker.setTypeName(rewrite.getAST().newSimpleName("Override")); //$NON-NLS-1$
	rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null);
}
 
Example #28
Source File: InlineMethodAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void selectionChanged(IStructuredSelection selection) {
	try {
		setEnabled(RefactoringAvailabilityTester.isInlineMethodAvailable(selection));
	} catch (JavaModelException e) {
		if (JavaModelUtil.isExceptionToBeLogged(e))
			JavaPlugin.log(e);
	}
}
 
Example #29
Source File: ContributedProcessorDescriptor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean matches(ICompilationUnit cunit) {
	if (fRequiredSourceLevel != null) {
		String current= cunit.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true);
		if (JavaModelUtil.isVersionLessThan(current, fRequiredSourceLevel)) {
			return false;
		}
	}

	if (fStatus != null) {
		return fStatus.booleanValue();
	}

	IConfigurationElement[] children= fConfigurationElement.getChildren(ExpressionTagNames.ENABLEMENT);
	if (children.length == 1) {
		try {
			ExpressionConverter parser= ExpressionConverter.getDefault();
			Expression expression= parser.perform(children[0]);
			EvaluationContext evalContext= new EvaluationContext(null, cunit);
			evalContext.addVariable("compilationUnit", cunit); //$NON-NLS-1$
			IJavaProject javaProject= cunit.getJavaProject();
			String[] natures= javaProject.getProject().getDescription().getNatureIds();
			evalContext.addVariable("projectNatures", Arrays.asList(natures)); //$NON-NLS-1$
			evalContext.addVariable("sourceLevel", javaProject.getOption(JavaCore.COMPILER_SOURCE, true)); //$NON-NLS-1$
			return expression.evaluate(evalContext) == EvaluationResult.TRUE;
		} catch (CoreException e) {
			JavaPlugin.log(e);
		}
		return false;
	}
	fStatus= Boolean.FALSE;
	return false;
}
 
Example #30
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName) throws CoreException{
	RefactoringStatus result= new RefactoringStatus();
	IMethod accessor= JavaModelUtil.findMethod(newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType());
	if (accessor == null || !accessor.exists()) {
		return null;
	}

	String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
			new String[]{JavaElementUtil.createMethodSignature(accessor), BasicElementLabels.getJavaElementName(fField.getDeclaringType().getFullyQualifiedName('.'))});
	result.addError(message, JavaStatusContext.create(accessor));
	return result;
}