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

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil. 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
/**
 * 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 2
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
@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 4
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 5
Source Project: sarl   Source File: SARLProposalProvider.java    License: 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 6
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
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
@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
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 Project: eclipse.jdt.ls   Source File: SourceJarLocations.java    License: 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
@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
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
@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 14
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 15
@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 16
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 17
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 18
@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 19
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 20
/**
 * 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
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
@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
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 24
private ICompilationUnit getNewCompilationUnit() {
	ICompilationUnit cu= fType.getCompilationUnit();
	if (isPrimaryType()) {
		IPackageFragment parent= fType.getPackageFragment();
		String renamedCUName= JavaModelUtil.getRenamedCUName(cu, getNewElementName());
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 25
private ImportReferencesCollector(IJavaProject project, CompilationUnit astRoot, Region rangeLimit, boolean skipMethodBodies, Collection<SimpleName> resultingTypeImports, Collection<SimpleName> resultingStaticImports) {
	super(processJavadocComments(astRoot));
	fTypeImports= resultingTypeImports;
	fStaticImports= resultingStaticImports;
	fSubRange= rangeLimit;
	if (project == null || !JavaModelUtil.is50OrHigher(project)) {
		fStaticImports= null; // do not collect
	}
	fASTRoot= astRoot; // can be null
	fSkipMethodBodies= skipMethodBodies;
}
 
Example 26
private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
		if (input instanceof ICodeAssist) {
			if (input instanceof ICompilationUnit) {
				ICompilationUnit cunit= (ICompilationUnit)input;
				if (cunit.isWorkingCopy())
					JavaModelUtil.reconcile(cunit);
			}
			IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
			if (elements != null && elements.length > 0)
				return elements;
		}
		return EMPTY_RESULT;
}
 
Example 27
/**
 * {@inheritDoc}
 */
@Override
public void selectionChanged(IStructuredSelection selection) {
	try {
		setEnabled(RefactoringAvailabilityTester.isPushDownAvailable(selection));
	} catch (JavaModelException e) {
		// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
		if (JavaModelUtil.isExceptionToBeLogged(e))
			JavaPlugin.log(e);
		setEnabled(false);// no UI
	}
}
 
Example 28
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;
}
 
Example 29
public static IEditorPart openDeclaration(IJavaElement element) throws PartInitException, JavaModelException {
	if (!(element instanceof IPackageFragment)) {
		return JavaUI.openInEditor(element);
	}
	
	IPackageFragment packageFragment= (IPackageFragment) element;
	ITypeRoot typeRoot;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		typeRoot= packageFragment.getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	} else {
		typeRoot= packageFragment.getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	}

	// open the package-info file in editor if one exists
	if (typeRoot.exists())
		return JavaUI.openInEditor(typeRoot);

	// open the package.html file in editor if one exists
	Object[] nonJavaResources= packageFragment.getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return EditorUtility.openInEditor(file, true);
			}
		}
	}

	// select the package in the Package Explorer if there is no associated package Javadoc file
	PackageExplorerPart view= (PackageExplorerPart) JavaPlugin.getActivePage().showView(JavaUI.ID_PACKAGES);
	view.tryToReveal(packageFragment);
	return null;
}
 
Example 30
private IField getFieldInWorkingCopy(ICompilationUnit newWorkingCopyOfDeclaringCu, String elementName) {
	IType type= fField.getDeclaringType();
	IType typeWc= (IType) JavaModelUtil.findInCompilationUnit(newWorkingCopyOfDeclaringCu, type);
	if (typeWc == null)
		return null;

	return typeWc.getField(elementName);
}