Java Code Examples for org.eclipse.jdt.core.IJavaElement#getElementName()

The following examples show how to use org.eclipse.jdt.core.IJavaElement#getElementName() . 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: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static int findInnerClassSourceLine(IJavaElement type, String name) throws JavaModelException {
    String elemName = type.getElementName();
    if (name.equals(elemName)) {
        if (type instanceof IType) {
            return getLineStart((IType) type);
        }
    }
    if (type instanceof IParent) {
        IJavaElement[] children = ((IParent) type).getChildren();
        for (int i = 0; i < children.length; i++) {
            // recursive call
            int line = findInnerClassSourceLine(children[i], name);
            if (line > 0) {
                return line;
            }
        }
    }
    return DONT_KNOW_LINE;
}
 
Example 2
Source File: PackagesViewHierarchicalContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPackageFragment[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) {
	List<IPackageFragment> list= new ArrayList<IPackageFragment>();
	try {

		IJavaElement[] children= parent.getChildren();
		String fragmentname= fragment.getElementName();
		for (int i= 0; i < children.length; i++) {
			IJavaElement element= children[i];
			if (element instanceof IPackageFragment) {
				IPackageFragment frag= (IPackageFragment) element;

				String name= element.getElementName();
				if (name.length() > fragmentname.length() && name.charAt(fragmentname.length()) == '.' && frag.exists() && !IPackageFragment.DEFAULT_PACKAGE_NAME.equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) {
					String tail= name.substring(fragmentname.length() + 1);
					if (!IPackageFragment.DEFAULT_PACKAGE_NAME.equals(tail) && tail.indexOf('.') == -1) {
						list.add(frag);
					}
				}
			}
		}

	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	return list.toArray(new IPackageFragment[list.size()]);
}
 
Example 3
Source File: JavaElementLinks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String getPackageFragmentElementName(IJavaElement javaElement) {
	IPackageFragmentRoot root= (IPackageFragmentRoot) javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	String javaElementName= javaElement.getElementName();
	String[] individualSegmentNames= javaElementName.split("\\."); //$NON-NLS-1$
	String packageName= null;
	StringBuffer strBuffer= new StringBuffer();

	for (int i= 0; i < individualSegmentNames.length; i++) {
		String lastSegmentName= individualSegmentNames[i];
		if (packageName != null) {
			strBuffer.append('.');
			packageName= packageName + '.' + lastSegmentName;
		} else {
			packageName= lastSegmentName;
		}
		IPackageFragment subFragment= root.getPackageFragment(packageName);
		strBuffer.append(getElementName(subFragment, lastSegmentName));
	}

	return strBuffer.toString();
}
 
Example 4
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
public static IResource findClassByName(final String className, final IProject currentProject) throws ClassNotFoundException {
	try {
		for (final IPackageFragment l : JavaCore.create(currentProject).getPackageFragments()) {
			for (final ICompilationUnit cu : l.getCompilationUnits()) {
				final IJavaElement cuResource = JavaCore.create(cu.getCorrespondingResource());
				for (IJavaElement a : (ArrayList<IJavaElement>)((CompilationUnit) cuResource).getChildrenOfType(7)) {
					String name = cuResource.getParent().getElementName() + "." + a.getElementName();

					if (name.startsWith(".")) {
						name = name.substring(1);
					}
					if (name.startsWith(className)) {
						return cu.getCorrespondingResource();
					}
				}
			}
		}
	}
	catch (final JavaModelException e) {
		throw new ClassNotFoundException("Class " + className + " not found.", e);
	}
	throw new ClassNotFoundException("Class " + className + " not found.");
}
 
Example 5
Source File: RefactoringHandleTransplanter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private String resolveElementName(IJavaElement element) {
	final String newName= fRefactoredSimilarElements.get(element);
	if (newName != null) {
		return newName;
	} else {
		return element.getElementName();
	}
}
 
Example 6
Source File: PatternStrings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String getSignature(IJavaElement element) {
	if (element == null)
		return null;
	else
		switch (element.getElementType()) {
			case IJavaElement.METHOD:
				return getMethodSignature((IMethod)element);
			case IJavaElement.TYPE:
				return getTypeSignature((IType) element);
			case IJavaElement.FIELD:
				return getFieldSignature((IField) element);
			default:
				return element.getElementName();
		}
}
 
Example 7
Source File: RefactoringHandleTransplanter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String resolveElementName(IJavaElement element) {
	final String newName= fRefactoredSimilarElements.get(element);
	if (newName != null)
		return newName;
	else
		return element.getElementName();
}
 
Example 8
Source File: SourceMapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int getFlags(IJavaElement element) {
	switch(element.getElementType()) {
		case IJavaElement.LOCAL_VARIABLE :
			LocalVariableElementKey key = new LocalVariableElementKey(element.getParent(), element.getElementName());
			if (this.finalParameters != null && this.finalParameters.contains(key)) {
				return Flags.AccFinal;
			}
	}
	return 0;
}
 
Example 9
Source File: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String getSourceFileHint(IType type, String qualifiedClassName) {
    String sourceFileStr = "";
    IJavaElement primaryElement = type.getPrimaryElement();
    if (primaryElement != null) {
        return primaryElement.getElementName() + ".java";
    }
    return sourceFileStr;
}
 
Example 10
Source File: CopyElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if this element is the main type of its compilation unit.
 */
protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) throws JavaModelException {
	if ((isRename() || getNewNameFor(element) != null)
		&& dest.getElementType() == IJavaElement.COMPILATION_UNIT) {
		String typeName = dest.getElementName();
		typeName = org.eclipse.jdt.internal.core.util.Util.getNameWithoutJavaLikeExtension(typeName);
		return element.getElementName().equals(typeName) && element.getParent().equals(dest);
	}
	return false;
}
 
Example 11
Source File: SaveUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static ArrayList<IEditorPart> getAffectedDirtyEditors(String projectName, String modelName,
		Iterable<String> descriptions) {
	HashSet<String> packageElements = getPackageElements(projectName, modelName, descriptions);
	IEditorPart[] dirtyEditors = getDitryEditors();
	ArrayList<IEditorPart> affectedEditors = new ArrayList<IEditorPart>(dirtyEditors.length);

	for (IEditorPart part : dirtyEditors) {
		IEditorInput input = part.getEditorInput();

		if (input instanceof IFileEditorInput) {
			IJavaElement javaPackage = JavaCore.create(((IFileEditorInput) input).getFile().getParent());
			if (javaPackage == null) {
				continue;
			}

			String packageName = javaPackage.getElementName();
			String fileName = input.getName();
			String fullName = packageName + "." + fileName;

			if (packageElements.contains(fullName)) {
				affectedEditors.add(part);
			}
		}
	}

	return affectedEditors;
}
 
Example 12
Source File: JavaElementLinks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getElementName(IJavaElement element) {
	if (element instanceof IPackageFragment || element instanceof IPackageDeclaration) {
		return getPackageFragmentElementName(element);
	}

	String elementName= element.getElementName();
	return getElementName(element, elementName);
}
 
Example 13
Source File: UiBinderSubtypeToOwnerIndex.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return an object representing the persisted memento, or null if the
 *         memento is no longer valid
 * @throws PersistenceException
 */
public static UiBinderSubtypeAndOwner load(IMemento memento)
    throws PersistenceException {
  String ownerTypeName = memento.getString(KEY_OWNER_TYPE_NAME);
  if (ownerTypeName == null) {
    throw new PersistenceException("Missing key " + KEY_OWNER_TYPE_NAME);
  }

  String uiBinderSubtypeKey = memento.getString(KEY_UIBINDER_SUBTYPE);
  if (uiBinderSubtypeKey == null) {
    throw new PersistenceException("Missing key " + KEY_UIBINDER_SUBTYPE);
  }

  IJavaElement javaElement = JavaCore.create(uiBinderSubtypeKey);
  if (javaElement == null) {
    throw new PersistenceException("Could not create type "
        + uiBinderSubtypeKey);
  }

  if (!(javaElement instanceof IType)) {
    throw new PersistenceException("Expecting "
        + javaElement.getElementName() + " to be a type");
  }

  if (!javaElement.getJavaProject().isOpen()) {
    return null;
  }

  if (!JavaModelSearch.isValidElement(javaElement)) {
    throw new PersistenceException(
        ((IType) javaElement).getFullyQualifiedName()
        + " is not a valid Java type");
  }

  return new UiBinderSubtypeAndOwner((IType) javaElement, ownerTypeName);
}
 
Example 14
Source File: UiBinderSubtypeToUiXmlIndex.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static void loadEntry(IMemento memento,
    UiBinderSubtypeToUiXmlIndex index) throws PersistenceException {
  String uiXmlPath = memento.getString(KEY_UI_XML_PATH);
  if (uiXmlPath == null) {
    throw new PersistenceException("Missing key " + KEY_UI_XML_PATH);
  }

  String uiBinderSubtypeKey = memento.getString(KEY_UIBINDER_SUBTYPE);
  if (uiBinderSubtypeKey == null) {
    throw new PersistenceException("Missing key " + KEY_UIBINDER_SUBTYPE);
  }

  IJavaElement javaElement = JavaCore.create(uiBinderSubtypeKey);
  if (javaElement == null) {
    throw new PersistenceException("Could not create Java element with key "
        + uiBinderSubtypeKey);
  }

  if (!(javaElement instanceof IType)) {
    throw new PersistenceException("Expecting "
        + javaElement.getElementName() + " to be a type");
  }

  if (!javaElement.getJavaProject().isOpen()) {
    return;
  }

  if (!JavaModelSearch.isValidElement(javaElement)) {
    throw new PersistenceException(
        ((IType) javaElement).getFullyQualifiedName()
            + " is not a valid Java type");
  }

  // Add the subtype + ui.xml pair to the index
  index.setUiXmlPath((IType) javaElement, new Path(uiXmlPath));
}
 
Example 15
Source File: JavaClassFilter.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
private static void collectPackages(IPackageFragmentRoot root, Set<String> result) throws JavaModelException {
    for (IJavaElement javaElement : root.getChildren()) {
        String elementName = javaElement.getElementName();
        if (javaElement instanceof IPackageFragment
            && ((IPackageFragment) javaElement).hasChildren()) {
            if (StringUtils.isNotBlank(elementName)) {
                result.add(elementName);
            }
        }
    }
}
 
Example 16
Source File: JDClassFileEditor.java    From jd-eclipse with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void setupSourceMapper(IClassFile classFile) {
	try {
		// Search package fragment root and classPath
		IJavaElement packageFragment = classFile.getParent();
		IJavaElement packageFragmentRoot = packageFragment.getParent();

		if (packageFragmentRoot instanceof PackageFragmentRoot) {
			// Setup a new source mapper.
			PackageFragmentRoot root = (PackageFragmentRoot)packageFragmentRoot;				
				
			// Location of the archive file containing classes.
			IPath basePath = root.getPath();
			File baseFile = basePath.makeAbsolute().toFile();	
			
			if (!baseFile.exists()) {
				IResource resource = root.getCorrespondingResource();
				basePath = resource.getLocation();
				baseFile = basePath.makeAbsolute().toFile();
			}
			
			// Class path
			String classPath = classFile.getElementName();
			String packageName = packageFragment.getElementName();
			if ((packageName != null) && (packageName.length() > 0)) {
				classPath = packageName.replace('.', '/') + '/' + classPath;
			}
			
			// Location of the archive file containing source.
			IPath sourcePath = root.getSourceAttachmentPath();
			if (sourcePath == null) {
				sourcePath = basePath;
			}
			
			// Location of the package fragment root within the zip 
			// (empty specifies the default root).
			IPath sourceAttachmentRootPath = root.getSourceAttachmentRootPath();
			String sourceRootPath;
			
			if (sourceAttachmentRootPath == null) {
				sourceRootPath = null;
			} else {
				sourceRootPath = sourceAttachmentRootPath.toString();
				if ((sourceRootPath != null) && (sourceRootPath.length() == 0))
					sourceRootPath = null;
			}
			
			// Options
			Map options = root.getJavaProject().getOptions(true);
			
			root.setSourceMapper(new JDSourceMapper(baseFile, sourcePath, sourceRootPath, options));				
		}		
	} catch (CoreException e) {
		JavaDecompilerPlugin.getDefault().getLog().log(new Status(
			Status.ERROR, JavaDecompilerPlugin.PLUGIN_ID, 
			0, e.getMessage(), e));
	}
}
 
Example 17
Source File: ParameterGuesser.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public Variable createVariable(IJavaElement element, IType enclosingType, String expectedType, int positionScore) throws JavaModelException {
	int variableType;
	int elementType= element.getElementType();
	String elementName= element.getElementName();

	String typeSignature;
	switch (elementType) {
		case IJavaElement.FIELD: {
			IField field= (IField) element;
			if (field.getDeclaringType().equals(enclosingType)) {
				variableType= Variable.FIELD;
			} else {
				variableType= Variable.INHERITED_FIELD;
			}
			if (field.isResolved()) {
				typeSignature= new BindingKey(field.getKey()).toSignature();
			} else {
				typeSignature= field.getTypeSignature();
			}
			break;
		}
		case IJavaElement.LOCAL_VARIABLE: {
			ILocalVariable locVar= (ILocalVariable) element;
			variableType= Variable.LOCAL;
			typeSignature= locVar.getTypeSignature();
			break;
		}
		case IJavaElement.METHOD: {
			IMethod method= (IMethod) element;
			if (isMethodToSuggest(method)) {
				if (method.getDeclaringType().equals(enclosingType)) {
					variableType= Variable.METHOD;
				} else {
					variableType= Variable.INHERITED_METHOD;
				}
				if (method.isResolved()) {
					typeSignature= Signature.getReturnType(new BindingKey(method.getKey()).toSignature());
				} else {
					typeSignature= method.getReturnType();
				}
				elementName= elementName + "()";  //$NON-NLS-1$
			} else {
				return null;
			}
			break;
		}
		default:
			return null;
	}
	String type= Signature.toString(typeSignature);

	boolean isAutoboxMatch= isPrimitiveType(expectedType) != isPrimitiveType(type);
	return new Variable(type, elementName, variableType, isAutoboxMatch, positionScore);
}
 
Example 18
Source File: DocumentSymbolHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String getName(IJavaElement element) {
	String name = JavaElementLabels.getElementLabel(element, ALL_DEFAULT);
	return name == null ? element.getElementName() : name;
}
 
Example 19
Source File: JavaElementLabelComposer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the string for rendering the {@link IJavaElement#getElementName() element name} of
 * the given element.
 * <p>
 * <strong>Note:</strong> This class only calls this helper for those elements where (
 * {@link JavaElementLinks}) has the need to render the name differently.
 * </p>
 * 
 * @param element the element to render
 * @return the string for rendering the element name
 */
protected String getElementName(IJavaElement element) {
	return element.getElementName();
}
 
Example 20
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns with the human readable name of the element. For types with type
 * arguments, it is {@code Comparable<T>} instead of {@code Comparable}. First,
 * this method tries to retrieve the
 * {@link JavaElementLabels#getElementLabel(IJavaElement, long) label} of the
 * element, then falls back to {@link IJavaElement#getElementName() element
 * name}. Returns {@code null} if the argument does not have a name.
 */
public static String getName(IJavaElement element) {
	Assert.isNotNull(element, "element");
	String name = JavaElementLabels.getElementLabel(element, ALL_DEFAULT | M_APP_RETURNTYPE | ROOT_VARIABLE);
	return name == null ? element.getElementName() : name;
}