Java Code Examples for org.eclipse.jdt.core.Signature#getSimpleName()

The following examples show how to use org.eclipse.jdt.core.Signature#getSimpleName() . 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: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean sameParams(IMethod method, IMethod method2) {

		if (method.getNumberOfParameters() != method2.getNumberOfParameters())
			return false;

		String[] params= method.getParameterTypes();
		String[] params2= method2.getParameterTypes();

		for (int i= 0; i < params.length; i++) {
			String t1= Signature.getSimpleName(Signature.toString(params[i]));
			String t2= Signature.getSimpleName(Signature.toString(params2[i]));
			if (!t1.equals(t2)) {
				return false;
			}
		}
		return true;
	}
 
Example 2
Source File: NLSHintHelper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IStorage getResourceBundle(IJavaProject javaProject, AccessorClassReference accessorClassReference) throws JavaModelException {
	String resourceBundle= accessorClassReference.getResourceBundleName();
	if (resourceBundle == null)
		return null;

	String resourceName= Signature.getSimpleName(resourceBundle) + NLSRefactoring.PROPERTY_FILE_EXT;
	String packName= Signature.getQualifier(resourceBundle);
	ITypeBinding accessorClass= accessorClassReference.getBinding();

	if (accessorClass.isFromSource())
		return getResourceBundle(javaProject, packName, resourceName);
	else if (accessorClass.getJavaElement() != null)
		return getResourceBundle((IPackageFragmentRoot)accessorClass.getJavaElement().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT), packName, resourceName);

	return null;
}
 
Example 3
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isSourceAnnotation(ASTNode node) {
  if (node instanceof Annotation) {
    Annotation annotation = (Annotation) node;
    String typeName = annotation.getTypeName().getFullyQualifiedName();

    // Annotation can be used with its fully-qualified name
    if (typeName.equals(ClientBundleUtilities.CLIENT_BUNDLE_SOURCE_ANNOTATION_NAME)) {
      return true;
    }

    // Simple name is fine, too
    String sourceAnnotationSimpleName =
        Signature.getSimpleName(ClientBundleUtilities.CLIENT_BUNDLE_SOURCE_ANNOTATION_NAME);
    if (typeName.equals(sourceAnnotationSimpleName)) {
      return true;
    }
  }
  return false;
}
 
Example 4
Source File: JavaProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an {@link ICompilationUnit} with the given fully qualified name and
 * code in the <code>javaProject</code>.
 *
 * @param javaProject java project to host the new class
 * @param fullyQualifiedClassName fully qualified name for the class
 * @param source code for the classs
 * @return newly created {@link ICompilationUnit}
 * @throws JavaModelException
 */
public static ICompilationUnit createCompilationUnit(
    IJavaProject javaProject, String fullyQualifiedClassName, String source)
    throws JavaModelException {
  IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  if (root == null) {
    addRawClassPathEntry(javaProject,
        JavaCore.newSourceEntry(javaProject.getPath()));
    root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  }

  String qualifier = Signature.getQualifier(fullyQualifiedClassName);
  IProgressMonitor monitor = new NullProgressMonitor();
  IPackageFragment packageFragment = root.createPackageFragment(qualifier,
      true, monitor);
  String name = Signature.getSimpleName(fullyQualifiedClassName);
  ICompilationUnit cu = packageFragment.createCompilationUnit(name + ".java",
      source, false, monitor);
  JobsUtilities.waitForIdle();
  return cu;
}
 
Example 5
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the display string for a java type signature.
 *
 * @param typeSignature the type signature to create a display name for
 * @return the display name for <code>typeSignature</code>
 * @throws IllegalArgumentException if <code>typeSignature</code> is not a
 *         valid signature
 * @see Signature#toCharArray(char[])
 * @see Signature#getSimpleName(char[])
 */
private char[] createTypeDisplayName(char[] typeSignature) throws IllegalArgumentException {
	char[] displayName= Signature.getSimpleName(Signature.toCharArray(typeSignature));

	// XXX see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84675
	boolean useShortGenerics= false;
	if (useShortGenerics) {
		StringBuffer buf= new StringBuffer();
		buf.append(displayName);
		int pos;
		do {
			pos= buf.indexOf("? extends "); //$NON-NLS-1$
			if (pos >= 0) {
				buf.replace(pos, pos + 10, "+"); //$NON-NLS-1$
			} else {
				pos= buf.indexOf("? super "); //$NON-NLS-1$
				if (pos >= 0)
					buf.replace(pos, pos + 8, "-"); //$NON-NLS-1$
			}
		} while (pos >= 0);
		return buf.toString().toCharArray();
	}
	return displayName;
}
 
Example 6
Source File: PipelineOptionsSelectionDialog.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public String getText(Object element) {
  if (element == null) {
    return null;
  }
  String simpleName = Signature.getSimpleName(element.toString());
  return String.format("%s - %s", simpleName, element.toString()); //$NON-NLS-1$
}
 
Example 7
Source File: WidgetProposalComputer.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ICompletionProposal createProposal(CompletionProposal proposal) {
  if (proposal.getKind() != CompletionProposal.TYPE_REF) {
    return null;
  }

  // NOTE: Resulting qualified name is dot-separated, even for enclosing
  // types. Generic signatures are not produced. See
  // org.eclipse.jdt.internal.codeassist.CompletionEngine.createTypeProposal.
  String qualifiedTypeName = String.valueOf(Signature.toCharArray(proposal.getSignature()));
  String typePackage = JavaUtilities.getPackageName(qualifiedTypeName);
  String typeSimpleName = Signature.getSimpleName(qualifiedTypeName);

  if (packageName != null && !typePackage.equals(packageName)) {
    return null;
  }

  ICompletionProposal javaCompletionProposal = JavaContentAssistUtilities.getJavaCompletionProposal(
      proposal, getContext(), getJavaProject());
  if (javaCompletionProposal != null) {
    return new WidgetProposal(typeSimpleName, typePackage, null,
        javaCompletionProposal.getDisplayString(),
        javaCompletionProposal.getImage(), getReplaceOffset(),
        getReplaceLength(), packageManager);
  } else {
    return new WidgetProposal(typeSimpleName, typePackage, null,
        typeSimpleName, null, getReplaceOffset(), getReplaceLength(),
        packageManager);
  }
}
 
Example 8
Source File: AddGetterSetterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a key used in hash maps for a method signature (gettersettername+arguments(fqn)).
 * 
 * @param methodName the method name
 * @param field the filed
 * @return the signature
 * @throws JavaModelException if getting the field's type signature fails
 */
private static String createSignatureKey(String methodName, IField field) throws JavaModelException {
	StringBuffer buffer= new StringBuffer();
	buffer.append(methodName);
	String fieldType= field.getTypeSignature();
	String signature= Signature.getSimpleName(Signature.toString(fieldType));
	buffer.append("#"); //$NON-NLS-1$
	buffer.append(signature);

	return buffer.toString();
}
 
Example 9
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
StyledString createOverrideMethodProposalLabel(CompletionProposal methodProposal) {
	StyledString nameBuffer= new StyledString();

	// method name
	nameBuffer.append(methodProposal.getName());

	// parameters
	nameBuffer.append('(');
	appendUnboundedParameterList(nameBuffer, methodProposal);
	nameBuffer.append(')');

	nameBuffer.append(RETURN_TYPE_SEPARATOR);

	// return type
	// TODO remove SignatureUtil.fix83600 call when bugs are fixed
	char[] returnType= createTypeDisplayName(SignatureUtil.getUpperBound(Signature.getReturnType(SignatureUtil.fix83600(methodProposal.getSignature()))));
	nameBuffer.append(returnType);

	// declaring type
	nameBuffer.append(QUALIFIER_SEPARATOR, StyledString.QUALIFIER_STYLER);

	String declaringType= extractDeclaringTypeFQN(methodProposal);
	declaringType= Signature.getSimpleName(declaringType);
	nameBuffer.append(Messages.format(JavaTextMessages.ResultCollector_overridingmethod, BasicElementLabels.getJavaElementName(declaringType)), StyledString.QUALIFIER_STYLER);

	return nameBuffer;
}
 
Example 10
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean areTypeParametersCompatible(IMethod method, char[][] typeParameterNames, char[][][] typeParameterBoundNames) {
	try {
		ITypeParameter[] typeParameters = method.getTypeParameters();
		int length1 = typeParameters == null ? 0 : typeParameters.length;
		int length2 = typeParameterNames == null ? 0 : typeParameterNames.length;
		if (length1 != length2) {
			return false;
		} else {
			for (int j = 0; j < length1; j++) {
				ITypeParameter typeParameter = typeParameters[j];
				String typeParameterName = typeParameter.getElementName();
				if (!typeParameterName.equals(new String(typeParameterNames[j]))) {
					return false;
				}

				String[] bounds = typeParameter.getBounds();
				int boundCount = typeParameterBoundNames[j] == null ? 0 : typeParameterBoundNames[j].length;

				if (bounds.length != boundCount) {
					return false;
				} else {
					for (int k = 0; k < boundCount; k++) {
						String simpleName = Signature.getSimpleName(bounds[k]);
						int index = simpleName.indexOf('<');
						if (index != -1) {
							simpleName = simpleName.substring(0, index);
						}
						if (!simpleName.equals(new String(typeParameterBoundNames[j][k]))) {
							return false;
						}
					}
				}
			}
		}
	} catch (JavaModelException e) {
		return false;
	}
	return true;
}
 
Example 11
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private String computeTypeProposal(ITypeParameter parameter) throws JavaModelException {
	String[] bounds= parameter.getBounds();
	String elementName= parameter.getElementName();
	if (bounds.length == 1 && !"java.lang.Object".equals(bounds[0])) {
		return Signature.getSimpleName(bounds[0]);
	} else {
		return elementName;
	}
}
 
Example 12
Source File: MethodProposalInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the simple erased name for a given type signature, possibly replacing type variables.
 *
 * @param signature the type signature
 * @param typeVariables the Map&lt;SimpleName, VariableName>
 * @return the simple erased name for signature
 */
private String computeSimpleTypeName(String signature, Map<String, char[]> typeVariables) {
	// method equality uses erased types
	String erasure= Signature.getTypeErasure(signature);
	erasure= erasure.replaceAll("/", ".");  //$NON-NLS-1$//$NON-NLS-2$
	String simpleName= Signature.getSimpleName(Signature.toString(erasure));
	char[] typeVar= typeVariables.get(simpleName);
	if (typeVar != null)
		simpleName= String.valueOf(Signature.getSignatureSimpleName(typeVar));
	return simpleName;
}
 
Example 13
Source File: BundledResourcesSelectionBlock.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public String getColumnText(Object element, int columnIndex) {
  ClientBundleResource resource = (ClientBundleResource) element;
  switch (columnIndex) {
    case COL_FILE:
      return resource.getFile().getName();
    case COL_TYPE:
      return Signature.getSimpleName(resource.getResourceTypeName());
    case COL_METHOD:
      return resource.getMethodName();
    default:
      return "";
  }
}
 
Example 14
Source File: CompletionProposalDescriptionProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates a display label for the given method proposal to item. The display label
 * consists of:
 * <ul>
 *   <li>the method name</li>
 *   <li>the parameter list (see {@link #createParameterList(CompletionProposal)})</li>
 *   <li>the upper bound of the return type (see {@link SignatureUtil#getUpperBound(String)})</li>
 *   <li>the raw simple name of the declaring type</li>
 * </ul>
 * <p>
 * Examples:
 * For the <code>get(int)</code> method of a variable of type <code>List<? extends Number></code>, the following
 * display name is returned: <code>get(int index)  Number - List</code>.<br>
 * For the <code>add(E)</code> method of a variable of type <code>List<? super Number></code>, the following
 * display name is returned: <code>add(Number o)  void - List</code>.<br>
 * </p>
 *
 * @param methodProposal the method proposal to display
 * @param item to update
 */
private void createMethodProposalLabel(CompletionProposal methodProposal, CompletionItem item) {
	StringBuilder description = this.createMethodProposalDescription(methodProposal);
	item.setLabel(description.toString());
	item.setInsertText(String.valueOf(methodProposal.getName()));

	// declaring type
	StringBuilder typeInfo = new StringBuilder();
	String declaringType= extractDeclaringTypeFQN(methodProposal);

	if (methodProposal.getRequiredProposals() != null) {
		String qualifier= Signature.getQualifier(declaringType);
		if (qualifier.length() > 0) {
			typeInfo.append(qualifier);
			typeInfo.append('.');
		}
	}

	declaringType= Signature.getSimpleName(declaringType);
	typeInfo.append(declaringType);
	StringBuilder detail = new StringBuilder();
	if (typeInfo.length() > 0) {
		detail.append(typeInfo);
		detail.append('.');
	}
	detail.append(description);
	item.setDetail(detail.toString());

	setSignature(item, String.valueOf(methodProposal.getSignature()));
	setDeclarationSignature(item, String.valueOf(methodProposal.getDeclarationSignature()));
	setName(item, String.valueOf(methodProposal.getName()));

}
 
Example 15
Source File: JavaMethodParameterCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
private String getParameterLabel(IMethod method, ITypeBinding calledTypeBinding) throws JavaModelException {
	ParameterMiningLabelBuilder label = new ParameterMiningLabelBuilder();
	if (showType) {
		String paramType = "";
		if (calledTypeBinding.isParameterizedType()) {
			// ex : List<String>
			ITypeBinding typeArgument = calledTypeBinding.getTypeArguments()[parameterIndex];
			paramType = typeArgument.getName();
		} else {
			paramType = method.getParameterTypes()[parameterIndex];
			paramType = Signature.getSimpleName(Signature.toString(Signature.getTypeErasure(paramType)));
			// replace [] with ... when varArgs
			if (parameterIndex == method.getParameterTypes().length - 1 && Flags.isVarargs(method.getFlags())) {
				paramType = paramType.substring(0, paramType.length() - 2) + "...";
			}
		}
		label.addParameterInfo(paramType);
	}
	if (showName) {
		String paramName = method.getParameterNames()[parameterIndex];
		if (!isArgNumber(paramName, method)) {
			label.addParameterInfo(paramName);
		}
	}
	return label.toString();

}
 
Example 16
Source File: RewriteEventStore.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void validateHasChildProperty(ASTNode parent, StructuralPropertyDescriptor property) {
	if (!parent.structuralPropertiesForType().contains(property)) {
		String message= Signature.getSimpleName(parent.getClass().getName()) + " has no property " + property.getId(); //$NON-NLS-1$
		throw new IllegalArgumentException(message);
	}
}
 
Example 17
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String computeJavaTypeReplacementString(CompletionProposal proposal) {
	String replacement = String.valueOf(proposal.getCompletion());

	/* No import rewriting ever from within the import section. */
	if (isImportCompletion(proposal)) {
		return replacement;
	}

	/*
	 * Always use the simple name for non-formal javadoc references to
	 * types.
	 */
	// TODO fix
	if (proposal.getKind() == CompletionProposal.TYPE_REF
			&& context.isInJavadocText()) {
		return SignatureUtil.getSimpleTypeName(proposal);
	}

	String qualifiedTypeName = SignatureUtil.getQualifiedTypeName(proposal);

	// Type in package info must be fully qualified.
	if (compilationUnit != null
			&& TypeProposalUtils.isPackageInfo(compilationUnit)) {
		return qualifiedTypeName;
	}

	if (qualifiedTypeName.indexOf('.') == -1 && replacement.length() > 0) {
		// default package - no imports needed
		return qualifiedTypeName;
	}

	/*
	 * If the user types in the qualification, don't force import rewriting
	 * on him - insert the qualified name.
	 */
	String prefix="";
	try{
		IDocument document = JsonRpcHelpers.toDocument(this.compilationUnit.getBuffer());
		IRegion region= document.getLineInformationOfOffset(proposal.getReplaceEnd());
		prefix =  document.get(region.getOffset(), proposal.getReplaceEnd() -region.getOffset()).trim();
	}catch(BadLocationException | JavaModelException e){

	}
	int dotIndex = prefix.lastIndexOf('.');
	// match up to the last dot in order to make higher level matching still
	// work (camel case...)
	if (dotIndex != -1
			&& qualifiedTypeName.toLowerCase().startsWith(
					prefix.substring(0, dotIndex + 1).toLowerCase())) {
		return qualifiedTypeName;
	}

	/*
	 * The replacement does not contain a qualification (e.g. an inner type
	 * qualified by its parent) - use the replacement directly.
	 */
	if (replacement.indexOf('.') == -1) {
		if (isInJavadoc())
		{
			return SignatureUtil.getSimpleTypeName(proposal); // don't use
		}
		// the
		// braces
		// added for
		// javadoc
		// link
		// proposals
		return replacement;
	}

	/* Add imports if the preference is on. */
	if (importRewrite != null) {
		return importRewrite.addImport(qualifiedTypeName, null);
	}

	// fall back for the case we don't have an import rewrite (see
	// allowAddingImports)

	/* No imports for implicit imports. */
	if (compilationUnit != null
			&& TypeProposalUtils.isImplicitImport(
					Signature.getQualifier(qualifiedTypeName),
					compilationUnit)) {
		return Signature.getSimpleName(qualifiedTypeName);
	}


	/* Default: use the fully qualified type name. */
	return qualifiedTypeName;
}
 
Example 18
Source File: LazyJavaTypeCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected String computeReplacementString() {
	String replacement= super.computeReplacementString();

	/* No import rewriting ever from within the import section. */
	if (isImportCompletion())
		return replacement;

	/* Always use the simple name for non-formal javadoc references to types. */
	// TODO fix
	 if (fProposal.getKind() == CompletionProposal.TYPE_REF &&  fInvocationContext.getCoreContext().isInJavadocText())
		 return getSimpleTypeName();

	String qualifiedTypeName= getQualifiedTypeName();

	// Type in package info must be fully qualified.
	if (fCompilationUnit != null && JavaModelUtil.isPackageInfo(fCompilationUnit))
		return qualifiedTypeName;

	if (qualifiedTypeName.indexOf('.') == -1 && replacement.length() > 0)
			// default package - no imports needed
			return qualifiedTypeName;

		/*
	 * If the user types in the qualification, don't force import rewriting on him - insert the
	 * qualified name.
	 */
		IDocument document= fInvocationContext.getDocument();
	if (document != null) {
		String prefix= getPrefix(document, getReplacementOffset() + getReplacementLength());
		int dotIndex= prefix.lastIndexOf('.');
		// match up to the last dot in order to make higher level matching still work (camel case...)
		if (dotIndex != -1 && qualifiedTypeName.toLowerCase().startsWith(prefix.substring(0, dotIndex + 1).toLowerCase()))
			return qualifiedTypeName;
	}

	/*
	 * The replacement does not contain a qualification (e.g. an inner type qualified by its
	 * parent) - use the replacement directly.
	 */
	if (replacement.indexOf('.') == -1) {
		if (isInJavadoc())
			return getSimpleTypeName(); // don't use the braces added for javadoc link proposals
		return replacement;
	}

	/* Add imports if the preference is on. */
	if (fImportRewrite == null)
		fImportRewrite= createImportRewrite();
	if (fImportRewrite != null) {
		return fImportRewrite.addImport(qualifiedTypeName, fImportContext);
	}

	// fall back for the case we don't have an import rewrite (see allowAddingImports)

	/* No imports for implicit imports. */
	if (fCompilationUnit != null && JavaModelUtil.isImplicitImport(Signature.getQualifier(qualifiedTypeName), fCompilationUnit)) {
		return Signature.getSimpleName(qualifiedTypeName);
	}

	/* Default: use the fully qualified type name. */
	return qualifiedTypeName;
}
 
Example 19
Source File: JavaTypeCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public JavaTypeCompletionProposal(String replacementString, ICompilationUnit cu, int replacementOffset, int replacementLength, Image image, StyledString displayString, int relevance, String fullyQualifiedTypeName, JavaContentAssistInvocationContext invocationContext) {
	super(replacementString, replacementOffset, replacementLength, image, displayString, relevance, false, invocationContext);
	fCompilationUnit= cu;
	fFullyQualifiedTypeName= fullyQualifiedTypeName;
	fUnqualifiedTypeName= fullyQualifiedTypeName != null ? Signature.getSimpleName(fullyQualifiedTypeName) : null;
}
 
Example 20
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a display label for the given method proposal. The display label consists of:
 * <ul>
 * <li>the method name</li>
 * <li>the raw simple name of the declaring type</li>
 * </ul>
 * <p>
 * Examples: For the <code>get(int)</code> method of a variable of type
 * <code>List<? extends Number></code>, the following display name is returned <code>get(int) - List</code>.<br>
 * For the <code>add(E)</code> method of a variable of type <code>List</code>, the
 * following display name is returned:
 * <code>add(Object) - List</code>.<br>
 * </p>
 *
 * @param methodProposal the method proposal to display
 * @return the display label for the given method proposal
 * @since 3.2
 */
StyledString createJavadocMethodProposalLabel(CompletionProposal methodProposal) {
	StyledString nameBuffer= new StyledString();

	// method name
	nameBuffer.append(methodProposal.getCompletion());

	// declaring type
	nameBuffer.append(QUALIFIER_SEPARATOR, StyledString.QUALIFIER_STYLER);
	String declaringType= extractDeclaringTypeFQN(methodProposal);
	declaringType= Signature.getSimpleName(declaringType);
	nameBuffer.append(declaringType, StyledString.QUALIFIER_STYLER);

	return Strings.markJavaElementLabelLTR(nameBuffer);
}