org.eclipse.jdt.core.IJavaElement Java Examples

The following examples show how to use org.eclipse.jdt.core.IJavaElement. 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: AddGetterSetterOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a new setter method for the specified field
 * 
 * @param field the field
 * @param astRewrite the AST rewrite to use
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
	final IType type= field.getDeclaringType();
	final String name= GetterSetterUtil.getSetterName(field, null);
	final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
	if (existing == null || !querySkipExistingMethods(existing)) {
		IJavaElement sibling= null;
		if (existing != null) {
			sibling= StubUtility.findNextSibling(existing);
			removeExistingAccessor(existing, rewrite);
		} else
			sibling= fInsert;
		ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
		addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
		if (Flags.isFinal(field.getFlags())) {
			ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
			if (fieldDecl != null) {
				ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
			}
		}

	}
}
 
Example #2
Source File: JavaOutlineInformationControl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setInput(Object information) {
	if (information == null || information instanceof String) {
		inputChanged(null, null);
		return;
	}
	IJavaElement je= (IJavaElement)information;
	ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT);
	if (cu != null)
		fInput= cu;
	else
		fInput= je.getAncestor(IJavaElement.CLASS_FILE);

	inputChanged(fInput, information);

	fCategoryFilterActionGroup.setInput(getInputForCategories());
}
 
Example #3
Source File: JavaProjectClasspathChangeAnalyzer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * determines if the delta is a relevant change on a IPackageFragmentRoot
 * 
 * @param delta
 *            the IJavaElementDelta to analyze. the deltas element must be an instance of IPackageFragmentRoot
 */
public boolean isRelevantPackageFragmentRootChange(IJavaElementDelta delta) {
	IJavaElement element = delta.getElement();
	assert (element instanceof IPackageFragmentRoot);
	return delta.getKind() == IJavaElementDelta.REMOVED 
			|| delta.getKind() == IJavaElementDelta.ADDED
			|| (delta.getFlags() & IJavaElementDelta.F_REORDER) != 0
			|| (delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0
			|| (delta.getFlags() & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0
			|| (
					(
						((IPackageFragmentRoot) element).isExternal() 
						|| ((IPackageFragmentRoot) element).isArchive()
					) && 
					(
						delta.getFlags() & // external folders change
						(IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED)
					) == delta.getFlags()
			);
}
 
Example #4
Source File: CompletionProposalCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void acceptPotentialMethodDeclaration(CompletionProposal proposal) {
	try {
		IJavaElement enclosingElement= null;
		if (getContext().isExtended()) {
			enclosingElement= getContext().getEnclosingElement();
		} else if (fCompilationUnit != null) {
			// kept for backward compatibility: CU is not reconciled at this moment, information is missing (bug 70005)
			enclosingElement= fCompilationUnit.getElementAt(proposal.getCompletionLocation() + 1);
		}
		if (enclosingElement == null)
			return;
		IType type= (IType) enclosingElement.getAncestor(IJavaElement.TYPE);
		if (type != null) {
			String prefix= String.valueOf(proposal.getName());
			int completionStart= proposal.getReplaceStart();
			int completionEnd= proposal.getReplaceEnd();
			int relevance= computeRelevance(proposal);

			GetterSetterCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, relevance + 2, fSuggestedMethodNames, fJavaProposals);
			MethodDeclarationCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, relevance, fSuggestedMethodNames, fJavaProposals);
		}
	} catch (CoreException e) {
		JavaPlugin.log(e);
	}
}
 
Example #5
Source File: FatJarPackageWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return all java projects which contain the selected elements in the active workbench window
 */
protected IStructuredSelection getSelectedJavaProjects() {
	ISelection currentSelection= JavaPlugin.getActiveWorkbenchWindow().getSelectionService().getSelection();
	if (currentSelection instanceof IStructuredSelection) {
		IStructuredSelection structuredSelection= (IStructuredSelection) currentSelection;
		HashSet<IJavaProject> selectedElements= new HashSet<IJavaProject>();
		Iterator<?> iter= structuredSelection.iterator();
		while (iter.hasNext()) {
			Object selectedElement= iter.next();
			if (selectedElement instanceof IJavaElement) {
				IJavaProject javaProject= ((IJavaElement) selectedElement).getJavaProject();
				if (javaProject != null)
					selectedElements.add(javaProject);
			}
		}
		return new StructuredSelection(selectedElements);
	} else
		return StructuredSelection.EMPTY;
}
 
Example #6
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException {
	Assert.isNotNull(javaElement);
	if (!fCheckDestination) {
		return new RefactoringStatus();
	}
	if (!javaElement.exists()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
	}
	if (javaElement instanceof IJavaModel) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
	}
	if (!(javaElement instanceof IJavaProject)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
	}
	if (javaElement.isReadOnly()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable);
	}
	if (ReorgUtils.isPackageFragmentRoot(javaElement.getJavaProject())) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc);
	}
	return new RefactoringStatus();
}
 
Example #7
Source File: JavaUIHelp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void helpRequested(HelpEvent e) {
	try {
		Object[] selected= null;
		if (fViewer != null) {
			ISelection selection= fViewer.getSelection();
			if (selection instanceof IStructuredSelection) {
				selected= ((IStructuredSelection)selection).toArray();
			}
		} else if (fEditor != null) {
			IJavaElement input= SelectionConverter.getInput(fEditor);
			if (input != null && ActionUtil.isOnBuildPath(input)) {
				selected= SelectionConverter.codeResolve(fEditor);
			}
		}
		JavadocHelpContext.displayHelp(fContextId, selected);
	} catch (CoreException x) {
		JavaPlugin.log(x);
	}
}
 
Example #8
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public IJavaElement[] getActualJavaElementsToReorg() throws JavaModelException {
	List<IJavaElement> result= new ArrayList<>();
	for (int i= 0; i < fJavaElements.length; i++) {
		IJavaElement element= fJavaElements[i];
		if (element == null) {
			continue;
		}
		if (element instanceof IType) {
			IType type= (IType) element;
			ICompilationUnit cu= type.getCompilationUnit();
			if (cu != null && type.getDeclaringType() == null && cu.exists() && cu.getTypes().length == 1 && !result.contains(cu)) {
				result.add(cu);
			} else if (!result.contains(type)) {
				result.add(type);
			}
		} else if (!result.contains(element)) {
			result.add(element);
		}
	}
	return result.toArray(new IJavaElement[result.size()]);
}
 
Example #9
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean canUpdateQualifiedNames() {
	if (!canEnableQualifiedNameUpdating())
		return false;

	IPackageFragment pack= getDestinationAsPackageFragment();
	if (pack == null)
		return false;

	if (pack.isDefaultPackage())
		return false;

	IJavaElement destination= getJavaElementDestination();
	if (destination instanceof IPackageFragmentRoot && getCus().length > 0) {
		return false;
	}

	return true;
}
 
Example #10
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public MethodReferenceMatch newMethodReferenceMatch(
		IJavaElement enclosingElement,
		Binding enclosingBinding,
		int accuracy,
		int offset,
		int length,
		boolean isConstructor,
		boolean isSynthetic,
		ASTNode reference) {
	SearchParticipant participant = getParticipant();
	IResource resource = this.currentPossibleMatch.resource;
	boolean insideDocComment = (reference.bits & ASTNode.InsideJavadoc) != 0;
	if (enclosingBinding != null)
		enclosingElement = ((JavaElement) enclosingElement).resolved(enclosingBinding);
	boolean isOverridden = (accuracy & PatternLocator.SUPER_INVOCATION_FLAVOR) != 0;
	return new MethodReferenceMatch(enclosingElement, accuracy, offset, length, isConstructor, isSynthetic, isOverridden, insideDocComment, participant, resource);
}
 
Example #11
Source File: PackagesView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String formatLogicalPackageMessage(LogicalPackage logicalPackage) {
	IPackageFragment[] fragments= logicalPackage.getFragments();
	StringBuffer buf= new StringBuffer(logicalPackage.getElementName());
	buf.append(JavaElementLabels.CONCAT_STRING);
	String message= ""; //$NON-NLS-1$
	boolean firstTime= true;
	for (int i= 0; i < fragments.length; i++) {
		IPackageFragment fragment= fragments[i];
		IJavaElement element= fragment.getParent();
		if (element instanceof IPackageFragmentRoot) {
			IPackageFragmentRoot root= (IPackageFragmentRoot) element;
			String label= JavaElementLabels.getElementLabel(root, JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_QUALIFIED);
			if (firstTime) {
				buf.append(label);
				firstTime= false;
			}
			else
				message= Messages.format(JavaBrowsingMessages.StatusBar_concat, new String[] {message, label});
		}
	}
	buf.append(message);
	return buf.toString();
}
 
Example #12
Source File: GetterSetterCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Proposes a getter for this field.
 * 
 * @param context the proposal parameter
 * @param relevance relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
	IMethodBinding method= findGetter(context);
	if (method != null) {
		Expression mi= createMethodInvocation(context, method, null);
		context.astRewrite.replace(context.accessNode, mi, null);

		String label= Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithgetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
		return proposal;
	} else {
		IJavaElement element= context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field= (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
					return new SelfEncapsulateFieldProposal(relevance, field);
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #13
Source File: DeleteResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see MultiOperation This method delegate to <code>deleteResource</code> or
 * <code>deletePackageFragment</code> depending on the type of <code>element</code>.
 */
protected void processElement(IJavaElement element) throws JavaModelException {
	switch (element.getElementType()) {
		case IJavaElement.CLASS_FILE :
		case IJavaElement.COMPILATION_UNIT :
			deleteResource(element.getResource(), this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
			break;
		case IJavaElement.PACKAGE_FRAGMENT :
			deletePackageFragment((IPackageFragment) element);
			break;
		default :
			throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
	}
	// ensure the element is closed
	if (element instanceof IOpenable) {
		((IOpenable)element).close();
	}
}
 
Example #14
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public SearchMatch newDeclarationMatch(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, int length, MatchLocator locator) {
	PatternLocator closestPattern = null;
	int level = IMPOSSIBLE_MATCH;
	for (int i = 0, pl = this.patternLocators.length; i < pl; i++) {
		PatternLocator patternLocator = this.patternLocators[i];
		int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference);
		if (newLevel > level) {
			closestPattern = patternLocator;
			if (newLevel == ACCURATE_MATCH) break;
			level = newLevel;
		}
	}
	if (closestPattern != null) {
	    return closestPattern.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
	}
	// super implementation...
    return locator.newDeclarationMatch(element, elementBinding, accuracy, reference.sourceStart, length);
}
 
Example #15
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IJavaElement findPackageFragment(String packageName)
		throws JavaModelException {
	NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
	IPackageFragment[] pkgFragments = lookup.findPackageFragments(packageName, false);
	if (pkgFragments == null) {
		return null;

	} else {
		// try to return one that is a child of this project
		for (int i = 0, length = pkgFragments.length; i < length; i++) {

			IPackageFragment pkgFragment = pkgFragments[i];
			if (equals(pkgFragment.getParent().getParent())) {
				return pkgFragment;
			}
		}
		// default to the first one
		return pkgFragments[0];
	}
}
 
Example #16
Source File: JavaSynchronizationContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean containsAsResource(List<Object> list, IResource child) {
	for (Iterator<Object> iter= list.iterator(); iter.hasNext(); ) {
		Object element= iter.next();
		if (child.equals(element))
			return true;
		if (element instanceof IJavaElement) {
			IJavaElement javaChild = (IJavaElement)element;
			try {
				if (child.equals(javaChild.getCorrespondingResource()))
					return true;
			} catch (JavaModelException e) {
				continue;
			}
		}
		
	}
	return false;
}
 
Example #17
Source File: SourceMapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the type with the given <code>typeName</code>.  Returns inner classes
 * as well.
 */
protected IType getType(String typeName) {
	if (typeName.length() == 0) {
		IJavaElement classFile = this.binaryType.getParent();
		String classFileName = classFile.getElementName();
		StringBuffer newClassFileName = new StringBuffer();
		int lastDollar = classFileName.lastIndexOf('$');
		for (int i = 0; i <= lastDollar; i++)
			newClassFileName.append(classFileName.charAt(i));
		newClassFileName.append(Integer.toString(this.anonymousCounter));
		PackageFragment pkg = (PackageFragment) classFile.getParent();
		return new BinaryType(new ClassFile(pkg, newClassFileName.toString()), typeName);
	} else if (this.binaryType.getElementName().equals(typeName))
		return this.binaryType;
	else
		return this.binaryType.getType(typeName);
}
 
Example #18
Source File: NavigateToDefinitionHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Location fixLocation(IJavaElement element, Location location, IJavaProject javaProject) {
	if (location == null) {
		return null;
	}
	if (!javaProject.equals(element.getJavaProject()) && element.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		// see issue at: https://github.com/eclipse/eclipse.jdt.ls/issues/842 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=541573
		// for jdk classes, jdt will reuse the java model by altering project to share the model between projects
		// so that sometimes the project for `element` is default project and the project is different from the project for `unit`
		// this fix is to replace the project name with non-default ones since default project should be transparent to users.
		if (location.getUri().contains(ProjectsManager.DEFAULT_PROJECT_NAME)) {
			String patched = StringUtils.replaceOnce(location.getUri(), ProjectsManager.DEFAULT_PROJECT_NAME, javaProject.getProject().getName());
			try {
				IClassFile cf = (IClassFile) JavaCore.create(JDTUtils.toURI(patched).getQuery());
				if (cf != null && cf.exists()) {
					location.setUri(patched);
				}
			} catch (Exception ex) {

			}
		}
	}
	return location;
}
 
Example #19
Source File: CopyToClipboardAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Transfer[] createDataTypeArray(IResource[] resources, IJavaElement[] javaElements, String[] fileNames, TypedSource[] typedSources) {
	List<ByteArrayTransfer> result= new ArrayList<ByteArrayTransfer>(4);
	if (resources.length != 0)
		result.add(ResourceTransfer.getInstance());
	if (javaElements.length != 0)
		result.add(JavaElementTransfer.getInstance());
	if (fileNames.length != 0)
		result.add(FileTransfer.getInstance());
	if (typedSources.length != 0)
		result.add(TypedSourceTransfer.getInstance());
	result.add(TextTransfer.getInstance());
	return result.toArray(new Transfer[result.size()]);
}
 
Example #20
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IType getTypeAtOffset(JavaEditor editor) throws JavaModelException {
	IJavaElement element= SelectionConverter.getElementAtOffset(editor);
	IType type= (IType)element.getAncestor(IJavaElement.TYPE);
	if (type == null) {
		ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(editor);
		if (unit != null)
			type= unit.findPrimaryType();
	}
	return type;
}
 
Example #21
Source File: JdtUtils.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param javaElt
 * @return true, if corresponding java project has compiler setting to
 *         generate bytecode for jdk 1.5 and above
 */
private static boolean is50OrHigher(IJavaElement javaElt) {
    IJavaProject project = javaElt.getJavaProject();
    String option = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
    boolean result = JavaCore.VERSION_1_5.equals(option);
    if (result) {
        return result;
    }
    // probably > 1.5?
    result = JavaCore.VERSION_1_4.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_3.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_2.equals(option);
    if (result) {
        return false;
    }
    result = JavaCore.VERSION_1_1.equals(option);
    if (result) {
        return false;
    }
    // unknown = > 1.5
    return true;
}
 
Example #22
Source File: RefactoringExecutionStarter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static RenameSupport createRenameSupport(IJavaElement element, String newName, int flags) throws CoreException {
	switch (element.getElementType()) {
		case IJavaElement.JAVA_PROJECT:
			return RenameSupport.create((IJavaProject) element, newName, flags);
		case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			return RenameSupport.create((IPackageFragmentRoot) element, newName);
		case IJavaElement.PACKAGE_FRAGMENT:
			return RenameSupport.create((IPackageFragment) element, newName, flags);
		case IJavaElement.COMPILATION_UNIT:
			return RenameSupport.create((ICompilationUnit) element, newName, flags);
		case IJavaElement.TYPE:
			return RenameSupport.create((IType) element, newName, flags);
		case IJavaElement.METHOD:
			final IMethod method= (IMethod) element;
			if (method.isConstructor())
				return createRenameSupport(method.getDeclaringType(), newName, flags);
			else
				return RenameSupport.create((IMethod) element, newName, flags);
		case IJavaElement.FIELD:
			return RenameSupport.create((IField) element, newName, flags);
		case IJavaElement.TYPE_PARAMETER:
			return RenameSupport.create((ITypeParameter) element, newName, flags);
		case IJavaElement.LOCAL_VARIABLE:
			return RenameSupport.create((ILocalVariable) element, newName, flags);
	}
	return null;
}
 
Example #23
Source File: JavaElementResourceMapping.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public IJavaElement getJavaElement() {
	Object o= getModelObject();
	if (o instanceof IJavaElement) {
		return (IJavaElement)o;
	}
	return null;
}
 
Example #24
Source File: AbstractNewFileWizard.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static IResource getSelectedResource(IStructuredSelection selection) {
  Object selectedElement = null;

  if (selection != null) {
    selectedElement = selection.getFirstElement();
  }

  if (selectedElement instanceof IResource) {
    return (IResource) selectedElement;
  } else if (selectedElement instanceof IJavaElement) {
    return ((IJavaElement) selectedElement).getResource();
  } else if (selectedElement instanceof IAdaptable) {
    IAdaptable adaptable = (IAdaptable) selectedElement;
    return (IResource) adaptable.getAdapter(IResource.class);
  }

  // If we don't have a resource yet, try to get one from the active editor
  IEditorPart editor = GWTPlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
  if (editor != null) {
    IFile file = ResourceUtils.getEditorInput(editor);
    if (file != null) {
      return file;
    }
  }

  // Fall back to the workspace root if we don't have a selection yet
  return ResourcesPlugin.getWorkspace().getRoot();
}
 
Example #25
Source File: DeleteSourceManipulationChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IResource getModifiedResource() {
	IJavaElement elem= JavaCore.create(fHandle);
	if (elem != null) {
		return elem.getResource();
	}
	return null;
}
 
Example #26
Source File: JavaElementDelta.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the <code>JavaElementDelta</code> for the given element
 * in the delta tree, or null, if no delta for the given element is found.
 */
protected JavaElementDelta find(IJavaElement e) {
	if (equalsAndSameParent(this.changedElement, e)) { // handle case of two jars that can be equals but not in the same project
		return this;
	} else {
		for (int i = 0; i < this.affectedChildren.length; i++) {
			JavaElementDelta delta = ((JavaElementDelta)this.affectedChildren[i]).find(e);
			if (delta != null) {
				return delta;
			}
		}
	}
	return null;
}
 
Example #27
Source File: JavaTaskListAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IResource getAffectedResource(IAdaptable element) {
IJavaElement java = (IJavaElement) element;
IResource resource= java.getResource();
if (resource != null)
	return resource;

ICompilationUnit cu= (ICompilationUnit) java.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
	return cu.getPrimary().getResource();
}
return null;
}
 
Example #28
Source File: BonitaExplorerLabelProvider.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Image getImage(Object element) {
    RepositoryManager repositoryManager = RepositoryManager.getInstance();
    if (!repositoryManager.hasActiveRepository() || !repositoryManager.getCurrentRepository().isLoaded()) {
        return super.getImage(element);
    }
    if (!(element instanceof IJavaElement)) {
        if (element instanceof IResource) {
            Optional<? extends IRepositoryFileStore> fileStore = asFileStore(element, repositoryManager);
            if (fileStore.isPresent()) {
                return fileStore
                        .map(IRepositoryFileStore::getIcon)
                        .map(icon -> packageExplorerProblemsDecorator.decorateImage(icon, element))
                        .orElse(super.getImage(element));
            }
        }
    }
    if (!(element instanceof PackageFragment)) {
        Optional<IRepositoryStore<? extends IRepositoryFileStore>> repositoryStore = repositoryManager
                .getRepositoryStore(element);
        if (repositoryStore.isPresent()) {
            IRepositoryStore<? extends IRepositoryFileStore> store = repositoryStore.get();
            return packageExplorerProblemsDecorator.decorateImage(store.getIcon(), element);
        }
    }
    return super.getImage(element);
}
 
Example #29
Source File: JavaOutlinePage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if element has an enclosing parent among other selected elements.
 * 
 * @param element the element to be checked for overlap against all elements
 * @param allElements the list of all elements
 * @return <code>true</code> if the element has a parent in the list of all elements
 */
private boolean isElementOverlapping(IJavaElement element, List<?> allElements) {
	element= element.getParent();
	while (element != null) {
		if (element instanceof ISourceReference) {
			if (allElements.contains(element))
				return true;
		} else {
			return false;
		}
		element= element.getParent();
	}
	return false;
}
 
Example #30
Source File: JdtHyperlinkFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void createHyperlink(Region region, EObject to, IHyperlinkAcceptor acceptor) {
	JvmIdentifiableElement element = (JvmIdentifiableElement) to;
	IJavaElement javaElement = javaElementFinder.findElementFor(element);
	if (javaElement == null)
		return;
	String label = JavaElementLabels.getElementLabel(javaElement, JavaElementLabels.ALL_DEFAULT);
	JdtHyperlink result = jdtHyperlinkProvider.get();
	result.setHyperlinkRegion(region);
	result.setHyperlinkText(label);
	result.setJavaElement(javaElement);
	acceptor.accept(result);
}