com.vaadin.copilot.javarewriter.
Class JavaRewriterUtil
Util methods for rewriting Java
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
addFieldAfter
(com.github.javaparser.ast.body.FieldDeclaration newField, com.github.javaparser.ast.body.FieldDeclaration reference) Adds a field declaration after the given reference field.
static com.github.javaparser.ast.expr.MethodCallExpr
addFunctionCall
(ComponentInfo componentInfo, String function, List<com.github.javaparser.ast.expr.Expression> parameterExpressions) Adds a function call to the given component.
static void
Adds an import to the given compilation unit if it is not already imported.
static boolean
appendExpressionAsNextSiblingInBlockAncestor
(com.github.javaparser.ast.Node original, com.github.javaparser.ast.stmt.Statement newExpression) Appends new expression to original one as sibling in a block statement.
static <T extends com.github.javaparser.ast.Node>
Tclone
(T node) Clones the node in a way that does not mess up the lexical printer.
static com.github.javaparser.ast.expr.ObjectCreationExpr
createComponentConstructor
(JavaComponent javaComponent, com.github.javaparser.ast.type.ClassOrInterfaceType componentType, String dataEntityRecordName) Creates the convenient component constructor for a new JavaComponent to be added to the code.
extractInlineVariableToLocalVariable
(ComponentInfo componentInfo) Extracts an inline variable to local variable with a new variable name.
static int
findBlockStatementIndex
(com.github.javaparser.ast.Node node) Finds the index of the statement that wraps the given node in the closest block statement.
static List<com.github.javaparser.ast.expr.MethodCallExpr>
findCalls
(Class<?> classWithMethods, ComponentInfo componentInfo) Find all calls done to methods in the given class through a reference to the given component.
static Optional<Constructor<?>>
findConstructor
(Class<? extends Component> componentType, com.github.javaparser.ast.expr.ObjectCreationExpr objectCreationExpr) Finds constructor for the given component
static int
findDeclarationIndex
(com.github.javaparser.ast.Node node) Finds the index of the given node in the block statement.
static com.github.javaparser.ast.body.FieldDeclaration
findFieldDeclaration
(com.github.javaparser.ast.Node nodeInClass, String fieldName) Finds the field declaration for the given field name in the class of the given node.
static String
findFreeRecordName
(String base, com.github.javaparser.ast.body.ClassOrInterfaceDeclaration block) static String
findFreeVariableName
(ComponentInfo componentInfo, com.github.javaparser.ast.stmt.BlockStmt block) Finds a free variable name based on the component type.
static String
findFreeVariableName
(String base, com.github.javaparser.ast.body.ClassOrInterfaceDeclaration block) Finds a free field name based on the given base name.
static String
findFreeVariableName
(String base, com.github.javaparser.ast.stmt.BlockStmt block) Finds a free variable name based on the given base name.
static InsertionPoint
findLocationAfter
(com.github.javaparser.ast.expr.Expression expr) Finds the insert location after of given expression.
static InsertionPoint
findLocationAtEnd
(com.github.javaparser.ast.stmt.Statement statement) Finds the insert location at the end of the code block containing the given statement.
static InsertionPoint
findLocationBefore
(com.github.javaparser.ast.expr.Expression expr) Finds the insert location before of given expression.
static List<com.github.javaparser.ast.expr.MethodCallExpr>
findMethodCallNonStatements
(ComponentInfo componentDefinition) Finds usage of the variable outside of method call statements, i.e.
static List<com.github.javaparser.ast.expr.MethodCallExpr>
findMethodCalls
(ComponentInfo componentInfo) Finds all method calls that are related to the given component.
static List<com.github.javaparser.ast.expr.MethodCallExpr>
findMethodCalls
(ComponentInfo componentInfo, com.github.javaparser.ast.Node.TreeTraversal traversalOrder) Finds all method calls that are related to the given component.
static List<com.github.javaparser.ast.expr.MethodCallExpr>
findMethodCallStatements
(ComponentInfo componentDefinition) Find all method calls that are statements, i.e.
static Stream<com.github.javaparser.ast.expr.Expression>
findNameReferences
(String variableName, com.github.javaparser.ast.stmt.BlockStmt scope) Finds all name references to the given variable name in the given scope.
static List<com.github.javaparser.ast.expr.Expression>
findParameterUsage
(ComponentInfo componentDefinition) Find all expressions where the given component is used as a call parameter.
static Optional<com.github.javaparser.ast.expr.Expression>
findReference
(com.github.javaparser.ast.NodeList<com.github.javaparser.ast.expr.Expression> nodes, ComponentInfo componentDefinition) Finds a node among the nodes which refer to the given component.
static Object
fromExpression
(com.github.javaparser.ast.expr.Expression arg, com.github.javaparser.resolution.types.ResolvedType expectedType) Parses the given expression and returns the object it represents.
static Optional<com.github.javaparser.ast.expr.Expression>
getAttachArgument
(ComponentInfo component) Finds the attach argument reference of the given component.
static com.github.javaparser.ast.expr.Expression
getAttachArgumentOrThrow
(ComponentInfo component) Find the attach argument reference of given component or throws
IllegalArgumentException
if not found.static Class<?>
Finds the class for the given source type.
static Enum<?>
getEnumValue
(Class<?> componentType, String setterName, String value) static String
getFieldOrVariableName
(ComponentInfo componentInfo) Gets the field or local variable name for the given component.
static String
getJavaIdentifier
(String str, int maxLength) Converts the given string into a valid Java identifier.
static String
getMappedProperty
(Constructor<?> c, int propertyIndex) Returns a property used in a constructor at the given index
static String
getNewComponentName
(JavaComponent javaComponent, com.github.javaparser.ast.type.ClassOrInterfaceType type, InsertionPoint insertionPoint) Provides a free name to be used when adding a new component.
static Optional<com.github.javaparser.ast.expr.Expression>
getOutermostScope
(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr) Gets the outermost scope for a chain of method calls.
static String
getPropertyName
(String setter) Gets the camel case property name for the given setter.
static Optional<com.github.javaparser.ast.expr.Expression>
getScopeIgnoreComposite
(ComponentInfo componentInfo, com.github.javaparser.ast.expr.MethodCallExpr expr) Returns the scope by ignoring the
getContent()
if component is in a composite container.static JavaRewriter.SetterAndValue
getSetterAndValue
(Class<?> componentType, String property, Object value) Gets the setter name and value for the given component type, property and value.
static String
getSetterName
(String property, Class<?> type, boolean includeReactConversions) Gets the setter name for the given property.
getSingleStringParamConstructor
(com.github.javaparser.ast.type.ClassOrInterfaceType type, Set<String> setters) Returns the single String parameter name from mapped properties of the component that matches an existing single String parameter constructor of the component
static boolean
Checks if the given component type has the given method.
static boolean
hasSetterForType
(Class<?> componentType, String setterName, Class<?> valueType) static boolean
hasSingleParameterMethod
(Class<? extends Component> type, String func) Checks if the given component type has a method with the given name, taking one parameter.
static boolean
isArrayArgument
(String className, String methodName, int argumentIndex) Uses reflection API for finding class name, method and the argument to find whether argument is array.
Includes the methods from extended Composite class if it is extended.static boolean
isNodeInCompositeClass
(com.github.javaparser.ast.Node node) Checks if the given node is a child of a Composite
static boolean
isRouteClass
(ComponentTypeAndSourceLocation typeAndSourceLocation, com.github.javaparser.ast.CompilationUnit compilationUnit) Checks if the given location refers to a @Route annotated class.
static boolean
removeArgumentCalls
(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr, List<? extends com.github.javaparser.ast.expr.Expression> argumentsToRemove, boolean removeMethodIfNoArgs) Removes the given arguments from the given method call.
static void
removeArgumentCalls
(List<com.github.javaparser.ast.expr.MethodCallExpr> methods, List<? extends com.github.javaparser.ast.expr.Expression> argumentsToRemove, boolean removeMethodIfNoArgs) Removes the given arguments from the given method calls.
static void
removeFromChainedStyleCall
(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr) Removes the given method call from a getStyle call chain.
static boolean
removeFromStringConcatenation
(com.github.javaparser.ast.Node node) Removes the given node from a string concatenation expression.
static void
removeStatement
(com.github.javaparser.ast.Node node) Removes the statement that wraps the given node.
static boolean
setNameExprScope
(com.github.javaparser.ast.expr.MethodCallExpr newCall, com.github.javaparser.ast.expr.NameExpr nameExpr) Sets the name expression scope for the given method call.
static boolean
typesEqual
(com.github.javaparser.resolution.types.ResolvedType javaParserType, Class<?> javaReflectionType) Checks if the given type is equal to the given reflection type.
-
Method Details
-
fromExpression
public static Object fromExpression(com.github.javaparser.ast.expr.Expression arg, com.github.javaparser.resolution.types.ResolvedType expectedType) Parses the given expression and returns the object it represents.
If the argument is a null literal, it is returned as is. Method call expressions are also returned as is.
Parameters:
arg
- the expression to parseexpectedType
- the expected type of the object or null if unknownReturns:
the object represented by the expression
-
findNameReferences
public static Stream<com.github.javaparser.ast.expr.Expression> findNameReferences(String variableName, com.github.javaparser.ast.stmt.BlockStmt scope) Finds all name references to the given variable name in the given scope.
Parameters:
variableName
- the variable namescope
- the scopeReturns:
a stream of name references
-
findMethodCallStatements
public static List<com.github.javaparser.ast.expr.MethodCallExpr> findMethodCallStatements(ComponentInfo componentDefinition) Find all method calls that are statements, i.e. calls like foo.bar() or baz.qux("zug")). Does not find usage of the variable in other expressions, like otherFunction("something" + foo.bar())
Parameters:
componentDefinition
- the component to look forReturns:
a list of method calls
-
findMethodCallNonStatements
public static List<com.github.javaparser.ast.expr.MethodCallExpr> findMethodCallNonStatements(ComponentInfo componentDefinition) Finds usage of the variable outside of method call statements, i.e. all usage not reported by
findMethodCallStatements(ComponentInfo)
.Parameters:
componentDefinition
- the component to look forReturns:
a list of method calls
-
findMethodCalls
public static List<com.github.javaparser.ast.expr.MethodCallExpr> findMethodCalls(ComponentInfo componentInfo) Finds all method calls that are related to the given component.
Parameters:
componentInfo
- the component to look forReturns:
a list of method calls
-
findMethodCalls
public static List<com.github.javaparser.ast.expr.MethodCallExpr> findMethodCalls(ComponentInfo componentInfo, com.github.javaparser.ast.Node.TreeTraversal traversalOrder) Finds all method calls that are related to the given component.
Parameters:
componentInfo
- the component to look fortraversalOrder
- the order in which the nodes are traversedReturns:
a list of method calls
-
findParameterUsage
public static List<com.github.javaparser.ast.expr.Expression> findParameterUsage(ComponentInfo componentDefinition) Find all expressions where the given component is used as a call parameter.
Parameters:
componentDefinition
- the component to look forReturns:
a list of expressions
-
extractInlineVariableToLocalVariable
public static JavaRewriter.ExtractInlineVariableResult extractInlineVariableToLocalVariable(ComponentInfo componentInfo) Extracts an inline variable to local variable with a new variable name.
Parameters:
componentInfo
- Component infoReturns:
Block, new variable name and index, null if attach call is not found.
-
isRouteClass
public static boolean isRouteClass(ComponentTypeAndSourceLocation typeAndSourceLocation, com.github.javaparser.ast.CompilationUnit compilationUnit) Checks if the given location refers to a @Route annotated class.
Parameters:
typeAndSourceLocation
- the type and source location to checkcompilationUnit
- the compilation unit that contains the codeReturns:
true
if the location refers to a @Route annotated class,false
otherwise -
hasSingleParameterMethod
Checks if the given component type has a method with the given name, taking one parameter.
Parameters:
type
- The component typefunc
- The method nameReturns:
true
if the method exists,false
otherwise -
findBlockStatementIndex
public static int findBlockStatementIndex(com.github.javaparser.ast.Node node) Finds the index of the statement that wraps the given node in the closest block statement.
Parameters:
node
- The node to find the wrapping statement forReturns:
The index of the statement in the block statement
-
findDeclarationIndex
public static int findDeclarationIndex(com.github.javaparser.ast.Node node) Finds the index of the given node in the block statement.
Parameters:
node
- The node to find the index forReturns:
The index of the node in the block statement or -1 if not found
-
findFreeVariableName
public static String findFreeVariableName(ComponentInfo componentInfo, com.github.javaparser.ast.stmt.BlockStmt block) Finds a free variable name based on the component type.
Parameters:
componentInfo
- The component infoblock
- The block the variable will be used inReturns:
A free variable name
-
findFreeVariableName
public static String findFreeVariableName(String base, com.github.javaparser.ast.stmt.BlockStmt block) Finds a free variable name based on the given base name.
Parameters:
base
- The base nameblock
- The block the variable will be used inReturns:
A free variable name
-
findFreeVariableName
public static String findFreeVariableName(String base, com.github.javaparser.ast.body.ClassOrInterfaceDeclaration block) Finds a free field name based on the given base name.
Parameters:
base
- The base nameblock
- The ClassOrInterfaceDeclaration the variable will be used inReturns:
A free variable name
-
findFreeRecordName
-
removeStatement
public static void removeStatement(com.github.javaparser.ast.Node node) Removes the statement that wraps the given node.
Parameters:
node
- the node to remove -
removeFromStringConcatenation
public static boolean removeFromStringConcatenation(com.github.javaparser.ast.Node node) Removes the given node from a string concatenation expression.
Parameters:
node
- the node to removeReturns:
true
if the node was removed,false
otherwise -
findReference
public static Optional<com.github.javaparser.ast.expr.Expression> findReference(com.github.javaparser.ast.NodeList<com.github.javaparser.ast.expr.Expression> nodes, ComponentInfo componentDefinition) Finds a node among the nodes which refer to the given component.
Parameters:
nodes
- the nodes to searchcomponentDefinition
- the component definitionReturns:
the first node that refers to the component, if any
-
findFieldDeclaration
public static com.github.javaparser.ast.body.FieldDeclaration findFieldDeclaration(com.github.javaparser.ast.Node nodeInClass, String fieldName) Finds the field declaration for the given field name in the class of the given node.
Parameters:
nodeInClass
- the node in the classfieldName
- the field nameReturns:
the field declaration
Throws:
IllegalArgumentException
- if the field is not found -
getSetterAndValue
public static JavaRewriter.SetterAndValue getSetterAndValue(Class<?> componentType, String property, Object value) Gets the setter name and value for the given component type, property and value.
Parameters:
componentType
- the component typeproperty
- the propertyvalue
- the valueReturns:
the setter name and value
-
getSetterName
Gets the setter name for the given property.
Parameters:
property
- the propertytype
- the component typeincludeReactConversions
- whether to include React property name conversions in the setter nameReturns:
the setter name
-
getPropertyName
Gets the camel case property name for the given setter.
Parameters:
setter
- the setter nameReturns:
the property name
-
getFieldOrVariableName
Gets the field or local variable name for the given component.
Parameters:
componentInfo
- the component infoReturns:
the field or local variable name
-
addImport
public static void addImport(com.github.javaparser.ast.CompilationUnit compilationUnit, String qualifiedName) Adds an import to the given compilation unit if it is not already imported.
Parameters:
compilationUnit
- the compilation unitqualifiedName
- the qualified name of the import -
getJavaIdentifier
Converts the given string into a valid Java identifier.
Parameters:
str
- the stringmaxLength
- the maximum length of the identifier, or 0 for unlimitedReturns:
the Java identifier
-
hasMethod
Checks if the given component type has the given method.
Parameters:
type
- the component typemethodName
- the method to check forReturns:
true
if the component has the method,false
otherwise -
getClass
Finds the class for the given source type.
Parameters:
name
- the class nameReturns:
the class for the given name
Throws:
IllegalArgumentException
- if the class is not found -
hasSetterForType
-
getEnumValue
-
removeArgumentCalls
public static void removeArgumentCalls(List<com.github.javaparser.ast.expr.MethodCallExpr> methods, List<? extends com.github.javaparser.ast.expr.Expression> argumentsToRemove, boolean removeMethodIfNoArgs) Removes the given arguments from the given method calls.
Parameters:
methods
- the method calls to processargumentsToRemove
- the arguments to removeremoveMethodIfNoArgs
- whether to remove the method call if no arguments are left -
removeArgumentCalls
public static boolean removeArgumentCalls(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr, List<? extends com.github.javaparser.ast.expr.Expression> argumentsToRemove, boolean removeMethodIfNoArgs) Removes the given arguments from the given method call.
Parameters:
methodCallExpr
- the method callargumentsToRemove
- the arguments to removeremoveMethodIfNoArgs
- whether to remove the method call if no arguments are leftReturns:
true
-
findLocationBefore
Finds the insert location before of given expression.
Parameters:
expr
- Reference expressionReturns:
Returns code block and index
-
findLocationAfter
Finds the insert location after of given expression.
Parameters:
expr
- Reference expressionReturns:
the insert location
-
findLocationAtEnd
Finds the insert location at the end of the code block containing the given statement.
Parameters:
statement
- The reference statementReturns:
the insert location
-
addFieldAfter
public static void addFieldAfter(com.github.javaparser.ast.body.FieldDeclaration newField, com.github.javaparser.ast.body.FieldDeclaration reference) Adds a field declaration after the given reference field.
Parameters:
newField
- the new field declarationreference
- the reference field -
clone
public static <T extends com.github.javaparser.ast.Node> T clone(T node) Clones the node in a way that does not mess up the lexical printer.
Type Parameters:
T
- the type of the nodeParameters:
node
- the node to cloneReturns:
the cloned node
-
getAttachArgument
public static Optional<com.github.javaparser.ast.expr.Expression> getAttachArgument(ComponentInfo component) Finds the attach argument reference of the given component.
Parameters:
component
- the componentReturns:
the attach argument reference, if found
-
getAttachArgumentOrThrow
public static com.github.javaparser.ast.expr.Expression getAttachArgumentOrThrow(ComponentInfo component) Find the attach argument reference of given component or throws
IllegalArgumentException
if not found.Parameters:
component
-Returns:
attach expression
-
setNameExprScope
public static boolean setNameExprScope(com.github.javaparser.ast.expr.MethodCallExpr newCall, com.github.javaparser.ast.expr.NameExpr nameExpr) Sets the name expression scope for the given method call. For a simple call like `foo.setBar()` this changes `foo` and for nested calls like `foo.baz().fo().a().b()` it also changes `foo`.
Parameters:
newCall
- the method call to changenameExpr
- the new scopeReturns:
true
if the scope was changed,false
otherwise -
typesEqual
public static boolean typesEqual(com.github.javaparser.resolution.types.ResolvedType javaParserType, Class<?> javaReflectionType) Checks if the given type is equal to the given reflection type.
Parameters:
javaParserType
- the Java parser typejavaReflectionType
- the Java reflection typeReturns:
true
if the types are equal,false
otherwise -
isArrayArgument
Uses reflection API for finding class name, method and the argument to find whether argument is array.
Includes the methods from extended Composite class if it is extended.Parameters:
className
- full class name of a class.methodName
- method nameargumentIndex
- argument to look up. It can exceed the method parameters, in that case the last argument is taken into accountReturns:
true
if argument is an array,false
otherwise -
appendExpressionAsNextSiblingInBlockAncestor
public static boolean appendExpressionAsNextSiblingInBlockAncestor(com.github.javaparser.ast.Node original, com.github.javaparser.ast.stmt.Statement newExpression) Appends new expression to original one as sibling in a block statement.
Parameters:
original
- Original expressionnewExpression
- New expressionReturns:
true if added, otherwise false.
-
getScopeIgnoreComposite
public static Optional<com.github.javaparser.ast.expr.Expression> getScopeIgnoreComposite(ComponentInfo componentInfo, com.github.javaparser.ast.expr.MethodCallExpr expr) Returns the scope by ignoring the
getContent()
if component is in a composite container. Otherwise, returns the scope of method.
getContent().add(...)
returnsempty
this.getContent().add(...)
returnsthis
setSomething()
returnsempty
abc.setSomething()
returnsabc
this.setSomething()
returnsthis
Parameters:
componentInfo
- Component Infoexpr
- Method to get scopeReturns:
Scope of the method, empty otherwise.
-
isNodeInCompositeClass
public static boolean isNodeInCompositeClass(com.github.javaparser.ast.Node node) Checks if the given node is a child of a Composite
Parameters:
node
- Any node in the treeReturns:
true
if child of a composite ,false
otherwise -
findConstructor
public static Optional<Constructor<?>> findConstructor(Class<? extends Component> componentType, com.github.javaparser.ast.expr.ObjectCreationExpr objectCreationExpr) Finds constructor for the given component
Parameters:
componentType
- Component classobjectCreationExpr
- Creation expression of the component.Returns:
Constructor if found, empty otherwise.
-
createComponentConstructor
public static com.github.javaparser.ast.expr.ObjectCreationExpr createComponentConstructor(JavaComponent javaComponent, com.github.javaparser.ast.type.ClassOrInterfaceType componentType, String dataEntityRecordName) Creates the convenient component constructor for a new JavaComponent to be added to the code.
Returns:
ObjectCreationExpr for Component
-
getSingleStringParamConstructor
public static Optional<String> getSingleStringParamConstructor(com.github.javaparser.ast.type.ClassOrInterfaceType type, Set<String> setters) Returns the single String parameter name from mapped properties of the component that matches an existing single String parameter constructor of the component
Parameters:
type
- The component typesetters
- The setters of the componentReturns:
The name of the property that is the setter of the constructor
-
getMappedProperty
Returns a property used in a constructor at the given index
Parameters:
c
- The constructorpropertyIndex
- The index of the propertyReturns:
The property name
-
getNewComponentName
public static String getNewComponentName(JavaComponent javaComponent, com.github.javaparser.ast.type.ClassOrInterfaceType type, InsertionPoint insertionPoint) Provides a free name to be used when adding a new component.
Parameters:
javaComponent
- The JavaComponent to be addedtype
- The type of the componentinsertionPoint
- The insertion pointReturns:
A free variable name
-
findCalls
public static List<com.github.javaparser.ast.expr.MethodCallExpr> findCalls(Class<?> classWithMethods, ComponentInfo componentInfo) Find all calls done to methods in the given class through a reference to the given component.
For instance, if you pass in Style.class, then it will find all invocations like
button.getStyle().set("color","red")
,button.getStyle().setColor("blue")
and alsoStyle s = button.getStyle(); s.setColor("black")
Parameters:
classWithMethods
- the class the check for callscomponentInfo
- the componentReturns:
a list of method calls
-
addFunctionCall
@Nonnull public static com.github.javaparser.ast.expr.MethodCallExpr addFunctionCall(ComponentInfo componentInfo, String function, List<com.github.javaparser.ast.expr.Expression> parameterExpressions) Adds a function call to the given component.
Parameters:
componentInfo
- the componentfunction
- the function to callparameterExpressions
- the parameters to pass to the function -
getOutermostScope
public static Optional<com.github.javaparser.ast.expr.Expression> getOutermostScope(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr) Gets the outermost scope for a chain of method calls.
E.g. for
foo.bar().baz().qux()
it will returnfoo
Parameters:
methodCallExpr
- The method call expressionReturns:
The outermost scope
-
removeFromChainedStyleCall
public static void removeFromChainedStyleCall(com.github.javaparser.ast.expr.MethodCallExpr methodCallExpr) Removes the given method call from a getStyle call chain.
If the method call is the only style call, removes the whole statement.
Parameters:
methodCallExpr
- the method call to remove
-