use of org.springframework.roo.classpath.details.annotations.AnnotatedJavaType in project spring-roo by spring-projects.
the class SecurityCommands method getAllMethodsRelatedWithProvidedClassForAuthorize.
@CliOptionAutocompleteIndicator(command = "security authorize", param = "method", help = "You must select a valid method from the provided class or a regular expression that match with existing methods", validate = false)
public List<String> getAllMethodsRelatedWithProvidedClassForAuthorize(ShellContext context) {
List<String> results = new ArrayList<String>();
String service = context.getParameters().get("class");
JavaType type = null;
if (service != null) {
type = getJavaTypeConverter().convertFromText(service, JavaType.class, PROJECT);
} else {
type = lastUsed.getJavaType();
}
MemberDetails serviceDetails = memberDetailsScanner.getMemberDetails(getClass().getName(), typeLocationService.getTypeDetails(type));
List<MethodMetadata> methods = serviceDetails.getMethods();
for (MethodMetadata method : methods) {
String methodName = method.getMethodName().getSymbolName();
List<AnnotatedJavaType> parameterTypes = method.getParameterTypes();
methodName = methodName.concat("(");
for (int i = 0; i < parameterTypes.size(); i++) {
String paramType = parameterTypes.get(i).getJavaType().getSimpleTypeName();
methodName = methodName.concat(paramType).concat(",");
}
if (!parameterTypes.isEmpty()) {
methodName = methodName.substring(0, methodName.length() - 1).concat(")");
} else {
methodName = methodName.concat(")");
}
results.add(methodName);
}
return results;
}
use of org.springframework.roo.classpath.details.annotations.AnnotatedJavaType in project spring-roo by spring-projects.
the class SecurityCommands method getAllMethodsRelatedWithProvidedClassForFiltering.
@CliOptionAutocompleteIndicator(command = "security filtering", param = "method", help = "You must select a valid method from the provided class or a regular expression that match with existing methods", validate = false)
public List<String> getAllMethodsRelatedWithProvidedClassForFiltering(ShellContext context) {
List<String> results = new ArrayList<String>();
String service = context.getParameters().get("class");
JavaType type = null;
if (service != null) {
type = getJavaTypeConverter().convertFromText(service, JavaType.class, PROJECT);
} else {
type = lastUsed.getJavaType();
}
MemberDetails serviceDetails = memberDetailsScanner.getMemberDetails(getClass().getName(), typeLocationService.getTypeDetails(type));
List<MethodMetadata> methods = serviceDetails.getMethods();
for (MethodMetadata method : methods) {
String methodName = method.getMethodName().getSymbolName();
List<AnnotatedJavaType> parameterTypes = method.getParameterTypes();
methodName = methodName.concat("(");
for (int i = 0; i < parameterTypes.size(); i++) {
String paramType = parameterTypes.get(i).getJavaType().getSimpleTypeName();
methodName = methodName.concat(paramType).concat(",");
}
if (!parameterTypes.isEmpty()) {
methodName = methodName.substring(0, methodName.length() - 1).concat(")");
} else {
methodName = methodName.concat(")");
}
results.add(methodName);
}
return results;
}
use of org.springframework.roo.classpath.details.annotations.AnnotatedJavaType in project spring-roo by spring-projects.
the class SecurityFiltersMetadataProviderImpl method checkParameters.
/**
* Check that the parameters of the method are equals of parameters list
*
* @param method Method to check
* @param methodParametersToCompare Parameters to compare
* @return true if are equals, false otherwise
*/
private boolean checkParameters(MethodMetadata method, List<?> methodParametersToCompare) {
boolean parametersAreEquals = true;
List<AnnotatedJavaType> parameterTypes = method.getParameterTypes();
if (methodParametersToCompare.size() != parameterTypes.size()) {
parametersAreEquals = false;
} else {
for (int i = 0; i < methodParametersToCompare.size(); i++) {
ClassAttributeValue methodParameterToCompare = (ClassAttributeValue) methodParametersToCompare.get(i);
AnnotatedJavaType parameterJavaType = parameterTypes.get(i);
if (!methodParameterToCompare.getValue().getSimpleTypeName().equals(parameterJavaType.getJavaType().getSimpleTypeName())) {
parametersAreEquals = false;
break;
}
}
}
return parametersAreEquals;
}
use of org.springframework.roo.classpath.details.annotations.AnnotatedJavaType in project spring-roo by spring-projects.
the class JavaParserMethodMetadataBuilder method addMethod.
public static void addMethod(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final MethodMetadata method, Set<JavaSymbolName> typeParameters) {
Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
Validate.notNull(members, "Members required");
Validate.notNull(method, "Method required");
if (typeParameters == null) {
typeParameters = new HashSet<JavaSymbolName>();
}
// Create the return type we should use
Type returnType = null;
if (method.getReturnType().isPrimitive()) {
returnType = JavaParserUtils.getType(method.getReturnType());
} else {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), method.getReturnType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(importedType);
// Add any type arguments presented for the return type
if (method.getReturnType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : method.getReturnType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (method.getReturnType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(method.getReturnType().getArray());
rt.setType(cit);
returnType = rt;
} else {
returnType = cit;
}
}
// Start with the basic method
final MethodDeclaration d = new MethodDeclaration();
d.setModifiers(JavaParserUtils.getJavaParserModifier(method.getModifier()));
d.setName(method.getMethodName().getSymbolName());
d.setType(returnType);
// Add any method-level annotations (not parameter annotations)
final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
d.setAnnotations(annotations);
for (final AnnotationMetadata annotation : method.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
}
// Add any method parameters, including their individual annotations and
// type parameters
final List<Parameter> parameters = new ArrayList<Parameter>();
d.setParameters(parameters);
int index = -1;
for (final AnnotatedJavaType methodParameter : method.getParameterTypes()) {
index++;
// Add the parameter annotations applicable for this parameter type
final List<AnnotationExpr> parameterAnnotations = new ArrayList<AnnotationExpr>();
for (final AnnotationMetadata parameterAnnotation : methodParameter.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, parameterAnnotations, parameterAnnotation);
}
// Compute the parameter name
final String parameterName = method.getParameterNames().get(index).getSymbolName();
// Compute the parameter type
Type parameterType = null;
if (methodParameter.getJavaType().isPrimitive()) {
parameterType = JavaParserUtils.getType(methodParameter.getJavaType());
} else {
final NameExpr type = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), methodParameter.getJavaType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(type);
// Add any type arguments presented for the return type
if (methodParameter.getJavaType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : methodParameter.getJavaType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (methodParameter.getJavaType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(methodParameter.getJavaType().getArray());
rt.setType(cit);
parameterType = rt;
} else {
parameterType = cit;
}
}
// Create a Java Parser method parameter and add it to the list of
// parameters
final Parameter p = new Parameter(parameterType, new VariableDeclaratorId(parameterName));
p.setVarArgs(methodParameter.isVarArgs());
p.setAnnotations(parameterAnnotations);
parameters.add(p);
}
// Add exceptions which the method my throw
if (method.getThrowsTypes().size() > 0) {
final List<NameExpr> throwsTypes = new ArrayList<NameExpr>();
for (final JavaType javaType : method.getThrowsTypes()) {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), javaType);
throwsTypes.add(importedType);
}
d.setThrows(throwsTypes);
}
// Set the body
if (StringUtils.isBlank(method.getBody())) {
// Never set the body if an abstract method
if (!Modifier.isAbstract(method.getModifier()) && !PhysicalTypeCategory.INTERFACE.equals(compilationUnitServices.getPhysicalTypeCategory())) {
d.setBody(new BlockStmt());
}
} else {
// There is a body.
// We need to make a fake method that we can have JavaParser parse.
// Easiest way to do that is to build a simple source class
// containing the required method and re-parse it.
final StringBuilder sb = new StringBuilder();
sb.append("class TemporaryClass {\n");
sb.append(" public void temporaryMethod() {\n");
sb.append(method.getBody());
sb.append("\n");
sb.append(" }\n");
sb.append("}\n");
final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
CompilationUnit ci;
try {
ci = JavaParser.parse(bais);
} catch (final IOException e) {
throw new IllegalStateException("Illegal state: Unable to parse input stream", e);
} catch (final ParseException pe) {
throw new IllegalStateException("Illegal state: JavaParser did not parse correctly", pe);
}
final List<TypeDeclaration> types = ci.getTypes();
if (types == null || types.size() != 1) {
throw new IllegalArgumentException("Method body invalid");
}
final TypeDeclaration td = types.get(0);
final List<BodyDeclaration> bodyDeclarations = td.getMembers();
if (bodyDeclarations == null || bodyDeclarations.size() != 1) {
throw new IllegalStateException("Illegal state: JavaParser did not return body declarations correctly");
}
final BodyDeclaration bd = bodyDeclarations.get(0);
if (!(bd instanceof MethodDeclaration)) {
throw new IllegalStateException("Illegal state: JavaParser did not return a method declaration correctly");
}
final MethodDeclaration md = (MethodDeclaration) bd;
d.setBody(md.getBody());
}
// ROO-3678: Add-on which include new method should be the responsible to check if method
// exists, not JavaParser.
/*// Locate where to add this method; also verify if this method already
// exists
for (final BodyDeclaration bd : members) {
if (bd instanceof MethodDeclaration) {
// Next method should appear after this current method
final MethodDeclaration md = (MethodDeclaration) bd;
/*if (md.getName().equals(d.getName())) {
if ((md.getParameters() == null || md.getParameters()
.isEmpty())
&& (d.getParameters() == null || d.getParameters()
.isEmpty())) {
throw new IllegalStateException("Method '"
+ method.getMethodName().getSymbolName()
+ "' already exists");
}
else if (md.getParameters() != null
&& md.getParameters().size() == d.getParameters()
.size()) {
// Possible match, we need to consider parameter types
// as well now
final MethodMetadata methodMetadata = JavaParserMethodMetadataBuilder
.getInstance(method.getDeclaredByMetadataId(),
md, compilationUnitServices,
typeParameters).build();
boolean matchesFully = true;
index = -1;
for (final AnnotatedJavaType existingParameter : methodMetadata
.getParameterTypes()) {
index++;
final AnnotatedJavaType parameterType = method
.getParameterTypes().get(index);
if (!existingParameter.getJavaType().equals(
parameterType.getJavaType())) {
matchesFully = false;
break;
}
}
if (matchesFully) {
throw new IllegalStateException(
"Method '"
+ method.getMethodName()
.getSymbolName()
+ "' already exists with identical parameters");
}
}
}
}
}*/
// ROO-3834: Append Javadoc
CommentStructure commentStructure = method.getCommentStructure();
if (commentStructure != null) {
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, commentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, commentStructure);
}
} else {
// ROO-3834: Include default documentation
CommentStructure defaultCommentStructure = new CommentStructure();
// ROO-3834: Append default Javadoc if not exists a comment structure,
// including method params, return and throws.
List<String> parameterNames = new ArrayList<String>();
for (JavaSymbolName name : method.getParameterNames()) {
parameterNames.add(name.getSymbolName());
}
List<String> throwsTypesNames = new ArrayList<String>();
for (JavaType type : method.getThrowsTypes()) {
throwsTypesNames.add(type.getSimpleTypeName());
}
String returnInfo = null;
JavaType returnJavaType = method.getReturnType();
if (!returnJavaType.equals(JavaType.VOID_OBJECT) && !returnJavaType.equals(JavaType.VOID_PRIMITIVE)) {
returnInfo = returnJavaType.getSimpleTypeName();
}
JavadocComment javadocComment = new JavadocComment("TODO Auto-generated method documentation", parameterNames, returnInfo, throwsTypesNames);
defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
method.setCommentStructure(defaultCommentStructure);
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, defaultCommentStructure);
}
}
// Add the method to the end of the compilation unit
members.add(d);
}
use of org.springframework.roo.classpath.details.annotations.AnnotatedJavaType in project spring-roo by spring-projects.
the class SeiMetadata method getSEIMethodFromServiceMethod.
/**
* This method obtains a SEI method from a provided service method.
*
* This method caches the generated methods
*
* @param serviceMethod defined in a service interface
*
* @return MethodMetadataBuilder that contains all the information about the new SEI method.
*/
private MethodMetadata getSEIMethodFromServiceMethod(MethodMetadata serviceMethod) {
// Check if already exists the method
if (seiMethodsFromServiceMethods.get(serviceMethod) != null) {
return seiMethodsFromServiceMethods.get(serviceMethod);
}
// If not exists, generate it and cache it.
// Obtain the necessary elements from service method
JavaSymbolName methodName = serviceMethod.getMethodName();
JavaType returnType = serviceMethod.getReturnType();
List<AnnotatedJavaType> parameterTypes = serviceMethod.getParameterTypes();
List<JavaSymbolName> parameterNames = serviceMethod.getParameterNames();
// Obtain parameterList
// Is necessary to change the method name to prevent errors
String paramList = "";
for (AnnotatedJavaType param : parameterTypes) {
paramList = paramList.concat(StringUtils.capitalize(param.getJavaType().getSimpleTypeName())).concat("And");
}
if (StringUtils.isNotBlank(paramList)) {
// Before to update, check if is a finder
if (methodName.toString().startsWith("findBy")) {
methodName = new JavaSymbolName("find");
} else if (methodName.toString().startsWith("countBy")) {
methodName = new JavaSymbolName("count");
}
paramList = paramList.substring(0, paramList.length() - "And".length());
methodName = new JavaSymbolName(methodName.toString().concat("By").concat(paramList));
}
// Annotate parameter types with @WebParam and @XmlJavaTypeAdapter if needed
List<AnnotatedJavaType> annotatedParameterTypes = new ArrayList<AnnotatedJavaType>();
for (int i = 0; i < parameterTypes.size(); i++) {
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
// Getting parameter type and parameter name
AnnotatedJavaType paramType = parameterTypes.get(i);
JavaSymbolName paramName = parameterNames.get(i);
// Creating @WebParam annotation
AnnotationMetadataBuilder webParamAnnotation = new AnnotationMetadataBuilder(JavaType.WEB_PARAM);
webParamAnnotation.addStringAttribute("name", paramName.toString());
webParamAnnotation.addStringAttribute("targetNamespace", "");
annotations.add(webParamAnnotation.build());
// Creating @XmlJavaTypeAdapter annotation
AnnotationMetadataBuilder javaTypeAdapter = new AnnotationMetadataBuilder(JavaType.XML_JAVATYPE_ADAPTER);
if (paramType.getJavaType().getFullyQualifiedTypeName().equals(JavaType.ITERABLE.getFullyQualifiedTypeName())) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_ITERABLE_ADAPTER);
annotations.add(javaTypeAdapter.build());
} else if (paramType.getJavaType().getFullyQualifiedTypeName().equals(SpringJavaType.PAGE.getFullyQualifiedTypeName())) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_PAGE_ADAPTER);
annotations.add(javaTypeAdapter.build());
} else if (paramType.getJavaType().equals(SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH)) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH_ADAPTER);
annotations.add(javaTypeAdapter.build());
} else if (paramType.getJavaType().equals(SpringJavaType.PAGEABLE)) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_PAGEABLE_ADAPTER);
annotations.add(javaTypeAdapter.build());
}
// Creating new parameter type annotated with @WebParam
AnnotatedJavaType annotatedParam = new AnnotatedJavaType(paramType.getJavaType(), annotations);
annotatedParameterTypes.add(annotatedParam);
}
MethodMetadataBuilder seiMethod = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.ABSTRACT, methodName, returnType, annotatedParameterTypes, parameterNames, null);
// Include @XmlJavaTypeAdapter annotation if needed
AnnotationMetadataBuilder javaTypeAdapter = new AnnotationMetadataBuilder(JavaType.XML_JAVATYPE_ADAPTER);
if (returnType.getFullyQualifiedTypeName().equals(JavaType.ITERABLE.getFullyQualifiedTypeName())) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_ITERABLE_ADAPTER);
seiMethod.addAnnotation(javaTypeAdapter);
} else if (returnType.getFullyQualifiedTypeName().equals(SpringJavaType.PAGE.getFullyQualifiedTypeName())) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_PAGE_ADAPTER);
seiMethod.addAnnotation(javaTypeAdapter);
} else if (returnType.equals(SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH)) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH_ADAPTER);
seiMethod.addAnnotation(javaTypeAdapter);
} else if (returnType.equals(SpringJavaType.PAGEABLE)) {
javaTypeAdapter.addClassAttribute("value", SpringletsJavaType.SPRINGLETS_PAGEABLE_ADAPTER);
seiMethod.addAnnotation(javaTypeAdapter);
}
// Include @RequestWrapper annotation
AnnotationMetadataBuilder requestWrapperAnnotation = new AnnotationMetadataBuilder(JavaType.REQUEST_WRAPPER);
requestWrapperAnnotation.addStringAttribute("className", String.format("%s.%sRequest", sei.getType().getPackage(), seiMethod.getMethodName().getSymbolNameCapitalisedFirstLetter()));
requestWrapperAnnotation.addStringAttribute("localName", String.format("%sRequest", seiMethod.getMethodName().getSymbolNameCapitalisedFirstLetter()));
requestWrapperAnnotation.addStringAttribute("targetNamespace", String.format("http://ws.%s/", StringUtils.reverseDelimited(projectTopLevelPackage.getFullyQualifiedPackageName(), '.')));
seiMethod.addAnnotation(requestWrapperAnnotation);
// Include @ResponseWrapper annotation
AnnotationMetadataBuilder responseWrapperAnnotation = new AnnotationMetadataBuilder(JavaType.RESPONSE_WRAPPER);
responseWrapperAnnotation.addStringAttribute("className", String.format("%s.%sResponse", sei.getType().getPackage(), seiMethod.getMethodName().getSymbolNameCapitalisedFirstLetter()));
responseWrapperAnnotation.addStringAttribute("localName", String.format("%sResponse", seiMethod.getMethodName().getSymbolNameCapitalisedFirstLetter()));
responseWrapperAnnotation.addStringAttribute("targetNamespace", String.format("http://ws.%s/", StringUtils.reverseDelimited(projectTopLevelPackage.getFullyQualifiedPackageName(), '.')));
seiMethod.addAnnotation(responseWrapperAnnotation);
// Include @WebMethod annotation
AnnotationMetadataBuilder webMethodAnnotation = new AnnotationMetadataBuilder(JavaType.WEB_METHOD);
webMethodAnnotation.addStringAttribute("action", String.format("urn:%s", seiMethod.getMethodName().getSymbolNameCapitalisedFirstLetter()));
seiMethod.addAnnotation(webMethodAnnotation);
// Include @WebResult annotation
AnnotationMetadataBuilder webResultAnnotation = new AnnotationMetadataBuilder(JavaType.WEB_RESULT);
webResultAnnotation.addStringAttribute("name", returnType.getBaseType().getSimpleTypeName().toLowerCase());
webResultAnnotation.addStringAttribute("targetNamespace", "");
seiMethod.addAnnotation(webResultAnnotation);
// Include @WSDLDocumentationCollection annotation
AnnotationMetadataBuilder wsdlDocumentationCollectionAnnotation = new AnnotationMetadataBuilder(new JavaType("org.apache.cxf.annotations.WSDLDocumentationCollection"));
// Create @WSDLDocumentation annotation
List<AnnotationAttributeValue<?>> documentations = new ArrayList<AnnotationAttributeValue<?>>();
AnnotationMetadataBuilder documentationAnnotation1 = new AnnotationMetadataBuilder(wsdlDocumentationType);
documentationAnnotation1.addStringAttribute("value", String.format("TODO Auto-generated documentation for %s", sei.getType().getSimpleTypeName()));
documentationAnnotation1.addEnumAttribute("placement", wsdlDocumentationType, new JavaSymbolName("Placement.DEFAULT"));
NestedAnnotationAttributeValue newDocumentation1 = new NestedAnnotationAttributeValue(new JavaSymbolName("value"), documentationAnnotation1.build());
documentations.add(newDocumentation1);
AnnotationMetadataBuilder documentationAnnotation2 = new AnnotationMetadataBuilder(wsdlDocumentationType);
documentationAnnotation2.addStringAttribute("value", String.format("TODO Auto-generated documentation for %s", sei.getType().getSimpleTypeName()));
documentationAnnotation2.addEnumAttribute("placement", wsdlDocumentationType, new JavaSymbolName("Placement.PORT_TYPE_OPERATION_OUTPUT"));
NestedAnnotationAttributeValue newDocumentation2 = new NestedAnnotationAttributeValue(new JavaSymbolName("value"), documentationAnnotation2.build());
documentations.add(newDocumentation2);
ArrayAttributeValue<AnnotationAttributeValue<?>> newDocumentations = new ArrayAttributeValue<AnnotationAttributeValue<?>>(new JavaSymbolName("value"), documentations);
wsdlDocumentationCollectionAnnotation.addAttribute(newDocumentations);
seiMethod.addAnnotation(wsdlDocumentationCollectionAnnotation);
seiMethodsFromServiceMethods.put(serviceMethod, seiMethod.build());
seiMethods.put(seiMethod.build(), serviceMethod);
return seiMethod.build();
}
Aggregations