org.eclipse.jdt.core.dom.StringLiteral Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.StringLiteral. 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: SourceView.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests whether a given expression is a String contant.
 * */
boolean isStringContant(Expression arg) {
	if(arg instanceof StringLiteral) {
		return true;
	} else
	if(arg instanceof InfixExpression) {
		InfixExpression infixExpr = (InfixExpression) arg;
		if(!isStringContant(infixExpr.getLeftOperand())) return false; 
		if(!isStringContant(infixExpr.getRightOperand())) return false;
					
		for(Iterator iter2 = infixExpr.extendedOperands().iterator(); iter2.hasNext(); ) {
			if(!isStringContant((Expression) iter2.next())) {
				return false;
			}
		}
		return true;
	}
	
	return false;	
}
 
Example #2
Source File: StringFormatGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void complete() throws CoreException {
	super.complete();
	ReturnStatement rStatement= fAst.newReturnStatement();
	String formatClass;
	if (getContext().is50orHigher())
		formatClass= "java.lang.String"; //$NON-NLS-1$
	else
		formatClass= "java.text.MessageFormat"; //$NON-NLS-1$
	MethodInvocation formatInvocation= createMethodInvocation(addImport(formatClass), "format", null); //$NON-NLS-1$ 
	StringLiteral literal= fAst.newStringLiteral();
	literal.setLiteralValue(buffer.toString());
	formatInvocation.arguments().add(literal);
	if (getContext().is50orHigher()) {
		formatInvocation.arguments().addAll(arguments);
	} else {
		ArrayCreation arrayCreation= fAst.newArrayCreation();
		arrayCreation.setType(fAst.newArrayType(fAst.newSimpleType(addImport("java.lang.Object")))); //$NON-NLS-1$
		ArrayInitializer initializer= fAst.newArrayInitializer();
		arrayCreation.setInitializer(initializer);
		initializer.expressions().addAll(arguments);
		formatInvocation.arguments().add(arrayCreation);
	}
	rStatement.setExpression(formatInvocation);
	toStringMethod.getBody().statements().add(rStatement);
}
 
Example #3
Source File: NLSStringHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
Example #4
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void validateSourceAnnotationValues(Annotation annotation) throws JavaModelException {
  Expression exp = JavaASTUtils.getAnnotationValue(annotation);
  if (exp == null) {
    return;
  }

  // There will usually just be one string value
  if (exp instanceof StringLiteral) {
    validateSourceAnnotationValue((StringLiteral) exp);
  }

  // But there could be multiple values; if so, check each one.
  if (exp instanceof ArrayInitializer) {
    ArrayInitializer array = (ArrayInitializer) exp;

    for (Expression item : (List<Expression>) array.expressions()) {
      if (item instanceof StringLiteral) {
        validateSourceAnnotationValue((StringLiteral) item);
      }
    }
  }
}
 
Example #5
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private void validateSourceAnnotationValue(StringLiteral literalNode) throws JavaModelException {
  String value = literalNode.getLiteralValue();

  // Interpret the literal path as an absolute path, and then as a path
  // relative to the containing package (indexing both).
  IPath literalPath = new Path(value);
  result.addPossibleResourcePath(literalPath);
  IPath fullResourcePathIfPackageRelative = getPackagePath(literalNode).append(literalPath);
  result.addPossibleResourcePath(fullResourcePathIfPackageRelative);

  // If the @Source path was absolute and we found it, great
  if (ClasspathResourceUtilities.isResourceOnClasspath(javaProject, literalPath)) {
    return;
  }

  if (!ClasspathResourceUtilities.isResourceOnClasspath(javaProject, fullResourcePathIfPackageRelative)) {
    // Didn't work as a relative path either, so now it's an error
    IPath expectedResourcePath = computeMissingResourceExpectedPath(literalPath, fullResourcePathIfPackageRelative);
    ClientBundleProblem problem = ClientBundleProblem.createMissingResourceFile(literalNode,
        literalPath.lastSegment(), expectedResourcePath.removeLastSegments(1));
    result.addProblem(problem);
  }
}
 
Example #6
Source File: UiBinderJavaValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void validateUiHandlerFieldExistenceInUiXml(
    MethodDeclaration uiHandlerDecl) {
  Annotation annotation = JavaASTUtils.findAnnotation(uiHandlerDecl,
      UiBinderConstants.UI_HANDLER_TYPE_NAME);

  if (annotation instanceof SingleMemberAnnotation) {
    SingleMemberAnnotation uiHandlerAnnotation = (SingleMemberAnnotation) annotation;
    Expression exp = uiHandlerAnnotation.getValue();
    if (exp instanceof StringLiteral) {
      validateFieldExistenceInUiXml(
          (TypeDeclaration) uiHandlerDecl.getParent(), exp,
          ((StringLiteral) exp).getLiteralValue());
    } else if (exp instanceof ArrayInitializer) {
      for (Expression element : (List<Expression>) ((ArrayInitializer) exp).expressions()) {
        if (element instanceof StringLiteral) {
          validateFieldExistenceInUiXml(
              (TypeDeclaration) uiHandlerDecl.getParent(), element,
              ((StringLiteral) element).getLiteralValue());
        }
      }
    }
  }
}
 
Example #7
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static boolean containsAnnotationValue(Expression annotationValue,
    String value) {
  if (annotationValue.getNodeType() == ASTNode.STRING_LITERAL) {
    String valueString = ((StringLiteral) annotationValue).getLiteralValue();
    return value.equals(valueString);
  } else if (annotationValue.getNodeType() == ASTNode.ARRAY_INITIALIZER) {
    // If the annotation value is actually an array, check each element
    List<Expression> warningTypes = ((ArrayInitializer) annotationValue).expressions();
    for (Expression warningType : warningTypes) {
      if (containsAnnotationValue(warningType, value)) {
        return true;
      }
    }
  }

  return false;
}
 
Example #8
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 6 votes vote down vote up
protected boolean isTypeHolder(Object o) {
	if(o.getClass().equals(MethodInvocation.class) || o.getClass().equals(SuperMethodInvocation.class)			
			|| o.getClass().equals(NumberLiteral.class) || o.getClass().equals(StringLiteral.class)
			|| o.getClass().equals(CharacterLiteral.class) || o.getClass().equals(BooleanLiteral.class)
			|| o.getClass().equals(TypeLiteral.class) || o.getClass().equals(NullLiteral.class)
			|| o.getClass().equals(ArrayCreation.class)
			|| o.getClass().equals(ClassInstanceCreation.class)
			|| o.getClass().equals(ArrayAccess.class) || o.getClass().equals(FieldAccess.class)
			|| o.getClass().equals(SuperFieldAccess.class) || o.getClass().equals(ParenthesizedExpression.class)
			|| o.getClass().equals(SimpleName.class) || o.getClass().equals(QualifiedName.class)
			|| o.getClass().equals(CastExpression.class) || o.getClass().equals(InfixExpression.class)
			|| o.getClass().equals(PrefixExpression.class) || o.getClass().equals(InstanceofExpression.class)
			|| o.getClass().equals(ThisExpression.class) || o.getClass().equals(ConditionalExpression.class))
		return true;
	return false;
}
 
Example #9
Source File: ASTFlattenerUtils.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private Iterable<StringLiteral> collectCompatibleNodes(final InfixExpression node) {
  final ArrayList<StringLiteral> strings = CollectionLiterals.<StringLiteral>newArrayList();
  InfixExpression.Operator _operator = node.getOperator();
  boolean _notEquals = (!Objects.equal(_operator, InfixExpression.Operator.PLUS));
  if (_notEquals) {
    return strings;
  }
  final Expression left = node.getLeftOperand();
  if ((left instanceof StringLiteral)) {
    strings.add(((StringLiteral)left));
  } else {
    if ((left instanceof InfixExpression)) {
      Iterables.<StringLiteral>addAll(strings, this.collectCompatibleNodes(((InfixExpression)left)));
    }
  }
  final Expression right = node.getRightOperand();
  if ((right instanceof StringLiteral)) {
    strings.add(((StringLiteral)right));
  } else {
    if ((right instanceof InfixExpression)) {
      Iterables.<StringLiteral>addAll(strings, this.collectCompatibleNodes(((InfixExpression)right)));
    }
  }
  Iterables.<StringLiteral>addAll(strings, Iterables.<StringLiteral>filter(node.extendedOperands(), StringLiteral.class));
  return strings;
}
 
Example #10
Source File: ASTFlattenerUtils.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public boolean canConvertToRichText(final InfixExpression node) {
  final FieldDeclaration parentFieldDecl = this.<FieldDeclaration>findParentOfType(node, FieldDeclaration.class);
  if ((parentFieldDecl != null)) {
    final TypeDeclaration typeDeclr = this.<TypeDeclaration>findParentOfType(parentFieldDecl, TypeDeclaration.class);
    if ((typeDeclr.isInterface() || (this.isFinal(parentFieldDecl.modifiers()) && this.isStatic(parentFieldDecl.modifiers())))) {
      return false;
    }
  }
  final SingleMemberAnnotation parentSingleMemberAnnotation = this.<SingleMemberAnnotation>findParentOfType(node, SingleMemberAnnotation.class);
  if ((parentSingleMemberAnnotation != null)) {
    return false;
  }
  final Iterable<StringLiteral> nodes = this.collectCompatibleNodes(node);
  return ((!IterableExtensions.isEmpty(nodes)) && IterableExtensions.<StringLiteral>forall(nodes, ((Function1<StringLiteral, Boolean>) (StringLiteral it) -> {
    return Boolean.valueOf(this.canTranslate(it));
  })));
}
 
Example #11
Source File: SwitchControlCase.java    From JDeodorant with MIT License 6 votes vote down vote up
private String getLiteralValue(Expression expression)
{
	if (expression instanceof NumberLiteral)
	{
		return ((NumberLiteral)expression).getToken();
	}
	else if (expression instanceof CharacterLiteral)
	{
		return String.valueOf(((CharacterLiteral)expression).charValue());
	}
	else if (expression instanceof StringLiteral)
	{
		return ((StringLiteral)expression).getLiteralValue();
	}
	else
	{
		return null;
	}
}
 
Example #12
Source File: LapseView.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
/**
	 * Tests whether a given expression is a String contant.
	 * */
	public static boolean isStringContant(Expression arg, CompilationUnit cu, IResource resource) {
		if(arg instanceof StringLiteral) {		
			return true;
		} else
//		if(arg instanceof SimpleName) {
//			// find out if the name is final...
//		} else
		if(arg instanceof InfixExpression) {
			InfixExpression infixExpr = (InfixExpression) arg;
			if(!isStringContant(infixExpr.getLeftOperand(), cu, resource)) return false; 
			if(!isStringContant(infixExpr.getRightOperand(), cu, resource)) return false;
						
			for(Iterator iter2 = infixExpr.extendedOperands().iterator(); iter2.hasNext(); ) {
				if(!isStringContant((Expression) iter2.next(), cu, resource)) {
					return false;
				}
			}
			return true;
		} 
		// TODO: add final/const
		
		return false;	
	}
 
Example #13
Source File: Visitor.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private void processArgument(Expression argument) {
	if(argument instanceof SuperMethodInvocation ||
			argument instanceof Name ||
			argument instanceof StringLiteral ||
			argument instanceof BooleanLiteral ||
			(argument instanceof FieldAccess && ((FieldAccess)argument).getExpression() instanceof ThisExpression) ||
			(argument instanceof ArrayAccess && invalidArrayAccess((ArrayAccess)argument)) ||
			(argument instanceof InfixExpression && invalidInfix((InfixExpression)argument)))
		return;
	this.arguments.add(argument.toString());
	if(current.getUserObject() != null) {
		AnonymousClassDeclarationObject anonymous = (AnonymousClassDeclarationObject)current.getUserObject();
		anonymous.getArguments().add(argument.toString());
	}
}
 
Example #14
Source File: StringBuilderChainGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void flushBuffer() {
	if (fBuffer.length() > 0) {
		if (temporaryBlock == null)
			temporaryBlock= toStringMethod.getBody();
		StringLiteral literal= fAst.newStringLiteral();
		literal.setLiteralValue(fBuffer.toString());
		appendExpression(literal);
		fBuffer.setLength(0);
	}
}
 
Example #15
Source File: StringBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void flushBuffer(Block target) {
	if (fBuffer.length() > 0) {
		StringLiteral literal= fAst.newStringLiteral();
		literal.setLiteralValue(fBuffer.toString());
		if (target == null)
			target= toStringMethod.getBody();
		target.statements().add(fAst.newExpressionStatement(createMethodInvocation(fBuilderVariableName, APPEND_METHOD_NAME, literal)));
		fBuffer.setLength(0);
	}
}
 
Example #16
Source File: StringConcatenationGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addMemberCheckNull(Object member, boolean addSeparator) {
	ConditionalExpression cExpression= fAst.newConditionalExpression();

	// member != null ?
	InfixExpression infExpression= fAst.newInfixExpression();
	infExpression.setLeftOperand(createMemberAccessExpression(member, true, true));
	infExpression.setRightOperand(fAst.newNullLiteral());
	infExpression.setOperator(Operator.NOT_EQUALS);
	cExpression.setExpression(infExpression);

	SumExpressionBuilder builder= new SumExpressionBuilder(null);
	String[] arrayString= getContext().getTemplateParser().getBody();
	for (int i= 0; i < arrayString.length; i++) {
		addElement(processElement(arrayString[i], member), builder);
	}
	if (addSeparator)
		addElement(getContext().getTemplateParser().getSeparator(), builder);
	cExpression.setThenExpression(builder.getExpression());

	StringLiteral literal= fAst.newStringLiteral();
	literal.setLiteralValue(getContext().isSkipNulls() ? "" : "null"); //$NON-NLS-1$ //$NON-NLS-2$
	cExpression.setElseExpression(literal);

	ParenthesizedExpression pExpression= fAst.newParenthesizedExpression();
	pExpression.setExpression(cExpression);
	toStringExpressionBuilder.addExpression(pExpression);
}
 
Example #17
Source File: StringConcatenationGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void flushBuffer() {
	if (buffer.length() > 0) {
		StringLiteral bufferedStringLiteral= fAst.newStringLiteral();
		bufferedStringLiteral.setLiteralValue(buffer.toString());
		buffer.setLength(0);
		expression= createSumExpression(expression, bufferedStringLiteral);
	}
}
 
Example #18
Source File: NLSKeyHyperlinkDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
	ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
	if (region == null || textEditor == null)
		return null;

	IEditorSite site= textEditor.getEditorSite();
	if (site == null)
		return null;

	ITypeRoot javaElement= getInputJavaElement(textEditor);
	if (javaElement == null)
		return null;

	CompilationUnit ast= SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
	if (!(node instanceof StringLiteral)  && !(node instanceof SimpleName))
		return null;

	if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
		return null;

	IRegion nlsKeyRegion= new Region(node.getStartPosition(), node.getLength());
	AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, nlsKeyRegion);
	if (ref == null)
		return null;
	String keyName= null;
	if (node instanceof StringLiteral) {
		keyName= ((StringLiteral)node).getLiteralValue();
	} else {
		keyName= ((SimpleName)node).getIdentifier();
	}
	if (keyName != null)
		return new IHyperlink[] {new NLSKeyHyperlink(nlsKeyRegion, keyName, ref, textEditor)};

	return null;
}
 
Example #19
Source File: SuppressWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean addSuppressArgument(ASTRewrite rewrite, Expression value, StringLiteral newStringLiteral) {
	if (value instanceof ArrayInitializer) {
		ListRewrite listRewrite= rewrite.getListRewrite(value, ArrayInitializer.EXPRESSIONS_PROPERTY);
		listRewrite.insertLast(newStringLiteral, null);
	} else if (value instanceof StringLiteral) {
		ArrayInitializer newArr= rewrite.getAST().newArrayInitializer();
		newArr.expressions().add(rewrite.createMoveTarget(value));
		newArr.expressions().add(newStringLiteral);
		rewrite.replace(value, newArr, null);
	} else {
		return false;
	}
	return true;
}
 
Example #20
Source File: SuppressWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adds a proposal to correct the name of the SuppressWarning annotation
 * @param context the context
 * @param problem the problem
 * @param proposals the resulting proposals
 */
public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {

	ASTNode coveringNode= context.getCoveringNode();
	if (!(coveringNode instanceof StringLiteral))
		return;

	AST ast= coveringNode.getAST();
	StringLiteral literal= (StringLiteral) coveringNode;

	String literalValue= literal.getLiteralValue();
	String[] allWarningTokens= CorrectionEngine.getAllWarningTokens();
	for (int i= 0; i < allWarningTokens.length; i++) {
		String curr= allWarningTokens[i];
		if (NameMatcher.isSimilarName(literalValue, curr)) {
			StringLiteral newLiteral= ast.newStringLiteral();
			newLiteral.setLiteralValue(curr);
			ASTRewrite rewrite= ASTRewrite.create(ast);
			rewrite.replace(literal, newLiteral, null);
			String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr });
			Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
			ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image);
			proposals.add(proposal);
		}
	}
	addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
}
 
Example #21
Source File: SuppressWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addRemoveUnusedSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot());
	if (!(coveringNode instanceof StringLiteral))
		return;

	StringLiteral literal= (StringLiteral) coveringNode;

	if (coveringNode.getParent() instanceof MemberValuePair) {
		coveringNode= coveringNode.getParent();
	}

	ASTNode parent= coveringNode.getParent();

	ASTRewrite rewrite= ASTRewrite.create(coveringNode.getAST());
	if (parent instanceof SingleMemberAnnotation) {
		rewrite.remove(parent, null);
	} else if (parent instanceof NormalAnnotation) {
		NormalAnnotation annot= (NormalAnnotation) parent;
		if (annot.values().size() == 1) {
			rewrite.remove(annot, null);
		} else {
			rewrite.remove(coveringNode, null);
		}
	} else if (parent instanceof ArrayInitializer) {
		rewrite.remove(coveringNode, null);
	} else {
		return;
	}
	String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_remove_annotation_label, literal.getLiteralValue());
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_ANNOTATION, image);
	proposals.add(proposal);
}
 
Example #22
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ThrowStatement getThrowForUnexpectedDefault(Expression switchExpression, AST ast, ASTRewrite astRewrite) {
	ThrowStatement newThrowStatement = ast.newThrowStatement();
	ClassInstanceCreation newCic = ast.newClassInstanceCreation();
	newCic.setType(ast.newSimpleType(ast.newSimpleName("IllegalArgumentException"))); //$NON-NLS-1$
	InfixExpression newInfixExpr = ast.newInfixExpression();
	StringLiteral newStringLiteral = ast.newStringLiteral();
	newStringLiteral.setLiteralValue("Unexpected value: "); //$NON-NLS-1$
	newInfixExpr.setLeftOperand(newStringLiteral);
	newInfixExpr.setOperator(InfixExpression.Operator.PLUS);
	newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpression));
	newCic.arguments().add(newInfixExpr);
	newThrowStatement.setExpression(newCic);
	return newThrowStatement;
}
 
Example #23
Source File: Visitor.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public boolean visit(StringLiteral node) {
	stringLiterals.add(node.toString());
	if(current.getUserObject() != null) {
		AnonymousClassDeclarationObject anonymous = (AnonymousClassDeclarationObject)current.getUserObject();
		anonymous.getStringLiterals().add(node.toString());
	}
	return super.visit(node);
}
 
Example #24
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite,
    ImportRewrite importRewrite, boolean addComments) throws CoreException {
  AST ast = astRewrite.getAST();
  MethodDeclaration methodDecl = ast.newMethodDeclaration();

  // Method is named after the resource it accesses
  methodDecl.setName(ast.newSimpleName(getMethodName()));

  // Method return type is a ResourcePrototype subtype
  ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName());
  Type resourceType = importRewrite.addImport(resourceTypeBinding, ast);
  methodDecl.setReturnType2(resourceType);

  // Add @Source annotation if necessary
  String sourceAnnotationValue = getSourceAnnotationValue(clientBundle);
  if (sourceAnnotationValue != null) {
    // Build the annotation
    SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation();
    sourceAnnotation.setTypeName(ast.newName("Source"));
    StringLiteral annotationValue = ast.newStringLiteral();
    annotationValue.setLiteralValue(sourceAnnotationValue);
    sourceAnnotation.setValue(annotationValue);

    // Add the annotation to the method
    ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty();
    ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers);
    modifiersRewriter.insertFirst(sourceAnnotation, null);
  }

  return methodDecl;
}
 
Example #25
Source File: EnsuresPredicateFix.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method builds a {@link ClassInstanceCreation} object (i.e. "new Ensuerer(varName, predicate")
 * 
 * @param ast
 * @param varName
 * @param predicate
 * @return
 */
private ClassInstanceCreation createEnsurerClassInstance(final AST ast, String varName, String predicate) {
	final ClassInstanceCreation classInstance = ast.newClassInstanceCreation();
	classInstance.setType(createAstType(INJAR_CLASS_NAME, ast));
	final StringLiteral literalPredicate = ast.newStringLiteral();
	literalPredicate.setLiteralValue(predicate);
	classInstance.arguments().add(ast.newSimpleName(varName));
	classInstance.arguments().add(literalPredicate);

	return classInstance;
}
 
Example #26
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(StringLiteral expr) {
	/*
	 * String literal nodes.
	 */
	StyledStringStyler styler = determineDiffStyle(expr, new StyledStringStyler(stringStyle));
	styledString.append(expr.toString(), styler);
	return false;
}
 
Example #27
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private StrLiteral visit(StringLiteral node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	StrLiteral literal = new StrLiteral(startLine, endLine, node);

	literal.setValue(node.getLiteralValue());
	
	AST ast = AST.newAST(AST.JLS8);
	Type type = ast.newSimpleType(ast.newSimpleName("String"));
	literal.setType(type);
	
	return literal;
}
 
Example #28
Source File: InstanceOfLiteral.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean instanceOf(Expression expression) {
	if(expression instanceof BooleanLiteral || expression instanceof CharacterLiteral || expression instanceof StringLiteral ||
			expression instanceof NullLiteral || expression instanceof NumberLiteral || expression instanceof TypeLiteral)
		return true;
	else
		return false;
}
 
Example #29
Source File: GeneratedAnnotationPopulator.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private SingleMemberAnnotation createGeneratedAnnotation(AST ast) {
    SingleMemberAnnotation generatedAnnotation = ast.newSingleMemberAnnotation();
    generatedAnnotation.setTypeName(ast.newSimpleName("Generated"));
    StringLiteral annotationValue = ast.newStringLiteral();
    annotationValue.setLiteralValue(StaticPreferences.PLUGIN_GENERATED_ANNOTATION_NAME);
    generatedAnnotation.setValue(annotationValue);
    return generatedAnnotation;
}
 
Example #30
Source File: GeneratedAnnotationPredicate.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
@Override
public boolean test(BodyDeclaration bodyDeclaration) {
    return ((List<IExtendedModifier>) bodyDeclaration.modifiers())
            .stream()
            .filter(modifier -> modifier instanceof SingleMemberAnnotation)
            .map(modifier -> (SingleMemberAnnotation) modifier)
            .filter(modifier -> isGeneratedAnnotation(modifier))
            .filter(modifier -> modifier.getValue() instanceof StringLiteral)
            .filter(annotation -> ((StringLiteral) annotation.getValue()).getLiteralValue().equals(PLUGIN_GENERATED_ANNOTATION_NAME))
            .findFirst()
            .isPresent();
}