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

The following examples show how to use org.eclipse.jdt.internal.corext.util.Strings. 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
Source Project: gwt-eclipse-plugin   Source File: TypeCreator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private String formatJava(IType type) throws JavaModelException {
  String source = type.getCompilationUnit().getSource();
  CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true));
  TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0,
      source.length(), 0, lineDelimiter);
  if (formatEdit == null) {
    CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName());
    return source;
  }

  Document document = new Document(source);
  try {
    formatEdit.apply(document);
    source = document.get();
  } catch (BadLocationException e) {
    CorePluginLog.logError(e);
  }

  source = Strings.trimLeadingTabsAndSpaces(source);
  return source;
}
 
Example 2
/**
 * Creates the method content of the moved method.
 *
 * @param document
 *            the document representing the source compilation unit
 * @param declaration
 *            the source method declaration
 * @param rewrite
 *            the ast rewrite to use
 * @return the string representing the moved method body
 * @throws BadLocationException
 *             if an offset into the document is invalid
 */
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
	final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
	final IJavaProject project= fMethod.getJavaProject();
	final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
	for (int index= 0; index < edits.length; index++)
		marker.addChild(edits[index]);
	final MultiTextEdit result= new MultiTextEdit();
	result.addChild(marker);
	final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
	processor.getRoot().addChild(result);
	processor.performEdits();
	final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
	return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
 
Example 3
/**
 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
 *
 * @throws JavaModelException
 */
public void createEdit() throws JavaModelException {
	try {
		IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
		TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
		edit.apply(document, TextEdit.UPDATE_REGIONS);

		String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
				fPreferences.tabWidth, fPreferences.indentWidth, false);

		ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());

		CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
		ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
		if (fCopy)
			if (fInsertBefore)
				bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
			else
				bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
		else
			bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);

	} catch (BadLocationException e) {
		JavaPlugin.log(e);
	}
}
 
Example 4
public static int getIndentationLevel(ASTNode node, ICompilationUnit unit) throws CoreException {
	IPath fullPath= unit.getCorrespondingResource().getFullPath();
	try{
		FileBuffers.getTextFileBufferManager().connect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
		ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(fullPath, LocationKind.IFILE);
		try {
			IRegion region= buffer.getDocument().getLineInformationOfOffset(node.getStartPosition());
			return Strings.computeIndentUnits(buffer.getDocument().get(region.getOffset(), region.getLength()), unit.getJavaProject());
		} catch (BadLocationException exception) {
			JavaPlugin.log(exception);
		}
		return 0;
	} finally {
		FileBuffers.getTextFileBufferManager().disconnect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
	}
}
 
Example 5
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example 6
public static String getMethodBodyContent(boolean isConstructor, IJavaProject project, String destTypeName, String methodName, String bodyStatement, String lineDelimiter) throws CoreException {
	String templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB_ID : CodeTemplateContextType.METHODSTUB_ID;
	Template template= getCodeTemplate(templateName, project);
	if (template == null) {
		return bodyStatement;
	}
	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
	context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
	context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
	context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement);
	String str= evaluateTemplate(context, template, new String[] { CodeTemplateContextType.BODY_STATEMENT });
	if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) {
		return bodyStatement;
	}
	return str;
}
 
Example 7
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
	IDocument doc= new Document(buffer.getString());
	int nLines= doc.getNumberOfLines();
	MultiTextEdit edit= new MultiTextEdit();
	HashSet<Integer> removedLines= new HashSet<Integer>();
	for (int i= 0; i < variables.length; i++) {
		TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
		if (position == null || position.getLength() > 0) {
			continue;
		}
		int[] offsets= position.getOffsets();
		for (int k= 0; k < offsets.length; k++) {
			int line= doc.getLineOfOffset(offsets[k]);
			IRegion lineInfo= doc.getLineInformation(line);
			int offset= lineInfo.getOffset();
			String str= doc.get(offset, lineInfo.getLength());
			if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
				int nextStart= doc.getLineOffset(line + 1);
				edit.addChild(new DeleteEdit(offset, nextStart - offset));
			}
		}
	}
	edit.apply(doc, 0);
	return doc.get();
}
 
Example 8
/**
 * Creates and returns a parameter list of the given method or type proposal suitable for
 * display. The list does not include parentheses. The lower bound of parameter types is
 * returned.
 * <p>
 * Examples:
 * 
 * <pre>
 *   &quot;void method(int i, String s)&quot; -&gt; &quot;int i, String s&quot;
 *   &quot;? extends Number method(java.lang.String s, ? super Number n)&quot; -&gt; &quot;String s, Number n&quot;
 * </pre>
 * 
 * </p>
 * 
 * @param proposal the proposal to create the parameter list for
 * @return the list of comma-separated parameters suitable for display
 */
public String createParameterList(CompletionProposal proposal) {
	String paramList;
	int kind= proposal.getKind();
	switch (kind) {
		case CompletionProposal.METHOD_REF:
		case CompletionProposal.CONSTRUCTOR_INVOCATION:
			paramList= appendUnboundedParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		case CompletionProposal.TYPE_REF:
		case CompletionProposal.JAVADOC_TYPE_REF:
			paramList= appendTypeParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
		case CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION:
			paramList= appendUnboundedParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		default:
			Assert.isLegal(false);
			return null; // dummy
	}
}
 
Example 9
StyledString createAnonymousTypeLabel(CompletionProposal proposal) {
	char[] declaringTypeSignature= proposal.getDeclarationSignature();
	declaringTypeSignature= Signature.getTypeErasure(declaringTypeSignature);

	StyledString buffer= new StyledString();
	buffer.append(Signature.getSignatureSimpleName(declaringTypeSignature));
	buffer.append('(');
	appendUnboundedParameterList(buffer, proposal);
	buffer.append(')');
	buffer.append("  "); //$NON-NLS-1$
	buffer.append(JavaTextMessages.ResultCollector_anonymous_type);

	if (proposal.getRequiredProposals() != null) {
		char[] signatureQualifier= Signature.getSignatureQualifier(declaringTypeSignature);
		if (signatureQualifier.length > 0) {
			buffer.append(JavaElementLabels.CONCAT_STRING, StyledString.QUALIFIER_STYLER);
			buffer.append(signatureQualifier, StyledString.QUALIFIER_STYLER);
		}
	}

	return Strings.markJavaElementLabelLTR(buffer);
}
 
Example 10
/**
 * Returns the styled label of the given object. The object must be of type {@link IJavaElement} or adapt to {@link IWorkbenchAdapter}.
 * If the element type is not known, the empty string is returned.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param obj object to get the label for
 * @param flags the rendering flags
 * @return the label or the empty string if the object type is not supported
 *
 * @since 3.4
 */
public static StyledString getStyledTextLabel(Object obj, long flags) {
	if (obj instanceof IJavaElement) {
		return getStyledElementLabel((IJavaElement) obj, flags);

	} else if (obj instanceof IResource) {
		return getStyledResourceLabel((IResource) obj);

	} else if (obj instanceof ClassPathContainer) {
		ClassPathContainer container= (ClassPathContainer) obj;
		return getStyledContainerEntryLabel(container.getClasspathEntry().getPath(), container.getJavaProject());

	} else if (obj instanceof IStorage) {
		return getStyledStorageLabel((IStorage) obj);

	} else if (obj instanceof IAdaptable) {
		IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
		if (wbadapter != null) {
			return Strings.markLTR(new StyledString(wbadapter.getLabel(obj)));
		}
	}
	return new StyledString();
}
 
Example 11
private String computeContextString(LazyGenericTypeProposal proposal) {
	try {
		TypeArgumentProposal[] proposals= proposal.computeTypeArgumentProposals();
		if (proposals.length == 0)
			return null;

		StringBuffer buf= new StringBuffer();
		for (int i= 0; i < proposals.length; i++) {
			buf.append(proposals[i].getDisplayName());
			if (i < proposals.length - 1)
				buf.append(", "); //$NON-NLS-1$
		}
		return Strings.markJavaElementLabelLTR(buf.toString());

	} catch (JavaModelException e) {
		return null;
	}
}
 
Example 12
/**
 * Removes start and end of a comment and corrects indentation and line
 * delimiters.
 *
 * @param comment the computed comment
 * @param indentation the base indentation
 * @param project the Java project for the formatter settings, or <code>null</code> for global preferences
 * @param lineDelimiter the line delimiter
 * @return a trimmed version of <code>comment</code>
 */
private String prepareTemplateComment(String comment, String indentation, IJavaProject project, String lineDelimiter) {
	//	trim comment start and end if any
	if (comment.endsWith("*/")) //$NON-NLS-1$
		comment= comment.substring(0, comment.length() - 2);
	comment= comment.trim();
	if (comment.startsWith("/*")) { //$NON-NLS-1$
		if (comment.length() > 2 && comment.charAt(2) == '*') {
			comment= comment.substring(3); // remove '/**'
		} else {
			comment= comment.substring(2); // remove '/*'
		}
	}
	// trim leading spaces, but not new lines
	int nonSpace= 0;
	int len= comment.length();
	while (nonSpace < len && Character.getType(comment.charAt(nonSpace)) == Character.SPACE_SEPARATOR)
			nonSpace++;
	comment= comment.substring(nonSpace);

	return Strings.changeIndent(comment, 0, project, indentation, lineDelimiter);
}
 
Example 13
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
	try {
		String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
		final IJavaProject project= getCompilationUnit().getJavaProject();
		IRegion region= document.getLineInformationOfOffset(fInsertPosition);

		String lineContent= document.get(region.getOffset(), region.getLength());
		String indentString= Strings.getIndentString(lineContent, project);
		String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
		InsertEdit edit= new InsertEdit(fInsertPosition, str);
		rootEdit.addChild(edit);
		if (fComment.charAt(fComment.length() - 1) != '\n') {
			rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
			rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
		}
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example 14
/**
 * Returns the label for a Java element with the flags as defined by {@link JavaElementLabels}.
 * @param binding The binding to render.
 * @param flags The text flags as defined in {@link JavaElementLabels}
 * @return the label of the binding
 */
public static String getBindingLabel(IBinding binding, long flags) {
	StringBuffer buffer= new StringBuffer(60);
	if (binding instanceof ITypeBinding) {
		getTypeLabel(((ITypeBinding) binding), flags, buffer);
	} else if (binding instanceof IMethodBinding) {
		getMethodLabel(((IMethodBinding) binding), flags, buffer);
	} else if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		if (variable.isField())
			getFieldLabel(variable, flags, buffer);
		else
			getLocalVariableLabel(variable, flags, buffer);
	}
	return Strings.markLTR(buffer.toString());
}
 
Example 15
public boolean matches(String text) {
	switch (fMatchKind) {
		case SearchPattern.R_PATTERN_MATCH:
			return fStringMatcher.match(text);
		case SearchPattern.R_EXACT_MATCH:
			return fPattern.equalsIgnoreCase(text);
		case SearchPattern.R_CAMELCASE_SAME_PART_COUNT_MATCH:
			return SearchPattern.camelCaseMatch(fPattern, text, true);
		case SearchPattern.R_CAMELCASE_MATCH:
			if (SearchPattern.camelCaseMatch(fPattern, text)) {
				return true;
			}
			// fall back to prefix match if camel case failed (bug 137244)
			return Strings.startsWithIgnoreCase(text, fPattern);
		default:
			return Strings.startsWithIgnoreCase(text, fPattern);
	}
}
 
Example 16
private String[] getBlocks(RangeMarker[] markers) throws BadLocationException {
	String[] result= new String[markers.length];
	for (int i= 0; i < markers.length; i++) {
		RangeMarker marker= markers[i];
		String content= fDocument.get(marker.getOffset(), marker.getLength());
		String lines[]= Strings.convertIntoLines(content);
		Strings.trimIndentation(lines, fTypeRoot.getJavaProject(), false);
		if (fMarkerMode == STATEMENT_MODE && lines.length == 2 && isSingleControlStatementWithoutBlock()) {
			lines[1]= CodeFormatterUtil.createIndentString(1, fTypeRoot.getJavaProject()) + lines[1];
		}
		result[i]= Strings.concatenate(lines, TextUtilities.getDefaultLineDelimiter(fDocument));
	}
	return result;
}
 
Example 17
private static String getUnindentedSource(ISourceReference sourceReference) throws JavaModelException {

			String[] lines= Strings.convertIntoLines(sourceReference.getSource());
			final IJavaProject project= ((IJavaElement) sourceReference).getJavaProject();
			Strings.trimIndentation(lines, project, false);
			return Strings.concatenate(lines, StubUtility.getLineDelimiterUsed((IJavaElement) sourceReference));
		}
 
Example 18
private void parsePropertyDocument(IDocument document) {
      fKeyValuePairs = new ArrayList<KeyValuePairModell>();

      SimpleLineReader reader = new SimpleLineReader(document);
      int offset = 0;
      String line = reader.readLine();
      int leadingWhiteSpaces = 0;
      while (line != null) {
          if (!SimpleLineReader.isCommentOrWhiteSpace(line)) {
              int idx = getIndexOfSeparationCharacter(line);
              if (idx != -1) {
			String key= line.substring(0, idx);
			String trimmedKey= key.trim();
			String value= line.substring(idx + 1);
			String trimmedValue= Strings.trimLeadingTabsAndSpaces(value);
			int length= key.length() + 1 + value.length();
                  fKeyValuePairs.add(new KeyValuePairModell(trimmedKey, trimmedValue, offset, length, leadingWhiteSpaces));
                  leadingWhiteSpaces = 0;
              }
          } else {
              leadingWhiteSpaces += line.length();
          }
          offset += line.length();
          line = reader.readLine();
      }
      int lastLine= document.getNumberOfLines() - 1;
      boolean needsNewLine= false;
      try {
      	needsNewLine= !(document.getLineLength(lastLine) == 0);
} catch (BadLocationException ignore) {
	// treat last line having no new line
}
      LastKeyValuePair lastKeyValuePair = new LastKeyValuePair(offset, needsNewLine);
fKeyValuePairs.add(lastKeyValuePair);
  }
 
Example 19
private static String getSourceOfDeclararationNode(IJavaElement elem, ICompilationUnit cu) throws JavaModelException, CoreException {
	Assert.isTrue(elem.getElementType() != IJavaElement.IMPORT_CONTAINER);
	if (elem instanceof ISourceReference) {
		ISourceReference reference= (ISourceReference) elem;
		String source= reference.getSource();
		if (source != null)
			return Strings.trimIndentation(source, cu.getJavaProject(), false);
	}
	return ""; //$NON-NLS-1$
}
 
Example 20
private int compareName(String leftString, String rightString) {
	int result= leftString.compareToIgnoreCase(rightString);
	if (result != 0 || rightString.length() == 0) {
		return result;
	} else if (Strings.isLowerCase(leftString.charAt(0)) &&
		!Strings.isLowerCase(rightString.charAt(0))) {
    		return +1;
	} else if (Strings.isLowerCase(rightString.charAt(0)) &&
    		!Strings.isLowerCase(leftString.charAt(0))) {
    		return -1;
	} else {
		return leftString.compareTo(rightString);
	}
}
 
Example 21
private void setSourceViewerContents(String contents) {
	if (contents != null) {
		final IJavaProject project= fProcessor.getDestinationType().getJavaProject();
		final String[] lines= Strings.convertIntoLines(contents);
		if (lines.length > 0) {
			final int indent= Strings.computeIndentUnits(lines[lines.length - 1], project);
			contents= Strings.changeIndent(contents, indent, project, "", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}
	final IDocument document= (contents == null) ? new Document() : new Document(contents);
	JavaPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document);
	fSourceViewer.setDocument(document);
}
 
Example 22
/**
 * Returns the indentation level at the position of code completion.
 *
 * @return the indentation level at the position of the code completion
 */
private int getIndentation() {
	int start= getStart();
	IDocument document= getDocument();
	try {
		IRegion region= document.getLineInformationOfOffset(start);
		String lineContent= document.get(region.getOffset(), region.getLength());
		IJavaProject project= getJavaProject();
		return Strings.computeIndentUnits(lineContent, project);
	} catch (BadLocationException e) {
		return 0;
	}
}
 
Example 23
/**
 * Returns the indentation level at the position of code completion.
 *
 * @return the indentation level at the position of the code completion
 */
private int getIndentation() {
	int start= getStart();
	IDocument document= getDocument();
	try {
		IRegion region= document.getLineInformationOfOffset(start);
		String lineContent= document.get(region.getOffset(), region.getLength());
		IJavaProject project= getJavaProject();
		return Strings.computeIndentUnits(lineContent, project);
	} catch (BadLocationException e) {
		return 0;
	}
}
 
Example 24
/**
 * Tries to find the given type name and add it to the import structure.
 * @param ref the name node
 */
public void add(SimpleName ref) {
	String typeName= ref.getIdentifier();

	if (fImportsAdded.contains(typeName)) {
		return;
	}

	IBinding binding= ref.resolveBinding();
	if (binding != null) {
		if (binding.getKind() != IBinding.TYPE) {
			return;
		}
		ITypeBinding typeBinding= (ITypeBinding) binding;
		if (typeBinding.isArray()) {
			typeBinding= typeBinding.getElementType();
		}
		typeBinding= typeBinding.getTypeDeclaration();
		if (!typeBinding.isRecovered()) {
			if (needsImport(typeBinding, ref)) {
				fImpStructure.addImport(typeBinding);
				fImportsAdded.add(typeName);
			}
			return;
		}
	} else {
		if (fDoIgnoreLowerCaseNames && typeName.length() > 0) {
			char ch= typeName.charAt(0);
			if (Strings.isLowerCase(ch) && Character.isLetter(ch)) {
				return;
			}
		}
	}
	fImportsAdded.add(typeName);
	fUnresolvedTypes.put(typeName, new UnresolvedTypeData(ref));
}
 
Example 25
public static int getIndentUsed(IBuffer buffer, int offset, IJavaProject project) {
	int i= offset;
	// find beginning of line
	while (i > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(i - 1))) {
		i--;
	}
	return Strings.computeIndentUnits(buffer.getText(i, offset - i), project);
}
 
Example 26
/**
 * Creates a display label for the given method proposal. 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
 * @return the display label for the given method proposal
 */
StyledString createMethodProposalLabel(CompletionProposal methodProposal) {
	StyledString nameBuffer= new StyledString();

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

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

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

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

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

	declaringType= Signature.getSimpleName(declaringType);
	nameBuffer.append(declaringType, StyledString.QUALIFIER_STYLER);
	return Strings.markJavaElementLabelLTR(nameBuffer);
}
 
Example 27
StyledString createTypeProposalLabel(char[] fullName) {
	// only display innermost type name as type name, using any
	// enclosing types as qualification
	int qIndex= findSimpleNameStart(fullName);

	StyledString buf= new StyledString();
	buf.append(new String(fullName, qIndex, fullName.length - qIndex));
	if (qIndex > 0) {
		buf.append(JavaElementLabels.CONCAT_STRING, StyledString.QUALIFIER_STYLER);
		buf.append(new String(fullName, 0, qIndex - 1), StyledString.QUALIFIER_STYLER);
	}
	return Strings.markJavaElementLabelLTR(buf);
}
 
Example 28
StyledString createJavadocTypeProposalLabel(char[] fullName) {
	// only display innermost type name as type name, using any
	// enclosing types as qualification
	int qIndex= findSimpleNameStart(fullName);

	StyledString buf= new StyledString("{@link "); //$NON-NLS-1$
	buf.append(new String(fullName, qIndex, fullName.length - qIndex));
	buf.append('}');
	if (qIndex > 0) {
		buf.append(JavaElementLabels.CONCAT_STRING, StyledString.QUALIFIER_STYLER);
		buf.append(new String(fullName, 0, qIndex - 1), StyledString.QUALIFIER_STYLER);
	}
	return Strings.markJavaElementLabelLTR(buf);
}
 
Example 29
StyledString createSimpleLabelWithType(CompletionProposal proposal) {
	StyledString buf= new StyledString();
	buf.append(proposal.getCompletion());
	char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
	if (typeName.length > 0) {
		buf.append(VAR_TYPE_SEPARATOR);
		buf.append(typeName);
	}
	return Strings.markJavaElementLabelLTR(buf);
}
 
Example 30
StyledString createLabelWithTypeAndDeclaration(CompletionProposal proposal) {
	char[] name= proposal.getCompletion();
	if (!isThisPrefix(name))
		name= proposal.getName();

	StyledString buf= new StyledString();
	buf.append(name);
	char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
	if (typeName.length > 0) {
		buf.append(VAR_TYPE_SEPARATOR);
		buf.append(typeName);
	}
	char[] declaration= proposal.getDeclarationSignature();
	if (declaration != null) {
		declaration= Signature.getSignatureSimpleName(declaration);
		if (declaration.length > 0) {
			buf.append(QUALIFIER_SEPARATOR, StyledString.QUALIFIER_STYLER);
			if (proposal.getRequiredProposals() != null) {
				String declaringType= extractDeclaringTypeFQN(proposal);
				String qualifier= Signature.getQualifier(declaringType);
				if (qualifier.length() > 0) {
					buf.append(qualifier, StyledString.QUALIFIER_STYLER);
					buf.append('.', StyledString.QUALIFIER_STYLER);
				}
			}
			buf.append(declaration, StyledString.QUALIFIER_STYLER);
		}
	}

	return Strings.markJavaElementLabelLTR(buf);
}