use of com.github.antlrjavaparser.api.ImportDeclaration in project spring-roo by spring-projects.
the class JavaParserUtils method getJavaType.
/**
* Resolves the effective {@link JavaType} a {@link NameExpr} represents.
* <p>
* You should use {@link #getJavaType(CompilationUnitServices, Type, Set)}
* where possible so that type arguments are preserved (a {@link NameExpr}
* does not contain type arguments).
* <p>
* A name expression can be either qualified or unqualified.
* <p>
* If a name expression is qualified and the qualification starts with a
* lowercase letter, that represents the fully-qualified name. If the
* qualification starts with an uppercase letter, the package name is
* prepended to the qualifier.
* <p>
* If a name expression is unqualified, the imports are scanned. If the
* unqualified name expression is found in the imports, that import
* declaration represents the fully-qualified name. If the unqualified name
* expression is not found in the imports, it indicates the name to find is
* either in the same package as the qualified name expression, or the type
* relates to a member of java.lang. If part of java.lang, the fully
* qualified name is treated as part of java.lang. Otherwise the compilation
* unit package plus unqualified name expression represents the fully
* qualified name expression.
*
* @param compilationUnitServices for package management (required)
* @param nameToFind to locate (required)
* @param typeParameters names to consider type parameters (can be null if
* there are none)
* @return the effective Java type (never null)
*/
public static JavaType getJavaType(final CompilationUnitServices compilationUnitServices, final NameExpr nameToFind, final Set<JavaSymbolName> typeParameters) {
Validate.notNull(compilationUnitServices, "Compilation unit services required");
Validate.notNull(nameToFind, "Name to find is required");
final JavaPackage compilationUnitPackage = compilationUnitServices.getCompilationUnitPackage();
if (nameToFind instanceof QualifiedNameExpr) {
final QualifiedNameExpr qne = (QualifiedNameExpr) nameToFind;
// Handle qualified name expressions that are related to inner types
// (eg Foo.Bar)
final NameExpr qneQualifier = qne.getQualifier();
final NameExpr enclosedBy = getNameExpr(compilationUnitServices.getEnclosingTypeName().getSimpleTypeName());
if (isEqual(qneQualifier, enclosedBy)) {
// This qualified name expression is simply an inner type
// reference
final String name = compilationUnitServices.getEnclosingTypeName().getFullyQualifiedTypeName() + "." + nameToFind.getName();
return new JavaType(name, compilationUnitServices.getEnclosingTypeName());
}
// package (ROO-1210)
if (qne.toString().length() > 1 && Character.isUpperCase(qne.toString().charAt(0))) {
// First letter is uppercase, so this likely requires prepending
// of some package name
final ImportDeclaration importDeclaration = getImportDeclarationFor(compilationUnitServices, qne.getQualifier());
if (importDeclaration == null) {
if (!compilationUnitPackage.getFullyQualifiedPackageName().equals("")) {
// package
return new JavaType(compilationUnitServices.getCompilationUnitPackage().getFullyQualifiedPackageName() + "." + qne.toString());
}
} else {
return new JavaType(importDeclaration.getName() + "." + qne.getName());
}
// This name expression (which contains a dot) had its qualifier
// imported, so let's use the import
} else {
// a package
return new JavaType(qne.toString());
}
}
if ("?".equals(nameToFind.getName())) {
return new JavaType(OBJECT.getFullyQualifiedTypeName(), 0, DataType.TYPE, JavaType.WILDCARD_NEITHER_ARG, null);
}
// list
if (typeParameters != null && typeParameters.contains(new JavaSymbolName(nameToFind.getName()))) {
return new JavaType(nameToFind.getName(), 0, DataType.VARIABLE, null, null);
}
// Check if we are looking for the enclosingType itself
final NameExpr enclosingTypeName = getNameExpr(compilationUnitServices.getEnclosingTypeName().getSimpleTypeName());
if (isEqual(enclosingTypeName, nameToFind)) {
return compilationUnitServices.getEnclosingTypeName();
}
// check if the compilation unit itself declares that type
for (final TypeDeclaration internalType : compilationUnitServices.getInnerTypes()) {
final NameExpr nameExpr = getNameExpr(internalType.getName());
if (isEqual(nameExpr, nameToFind)) {
// Found, so now we need to convert the internalType to a proper
// JavaType
final String name = compilationUnitServices.getEnclosingTypeName().getFullyQualifiedTypeName() + "." + nameToFind.getName();
return new JavaType(name);
}
}
final ImportDeclaration importDeclaration = getImportDeclarationFor(compilationUnitServices, nameToFind);
if (importDeclaration == null) {
if (JdkJavaType.isPartOfJavaLang(nameToFind.getName())) {
return new JavaType("java.lang." + nameToFind.getName());
}
final String name = compilationUnitPackage.getFullyQualifiedPackageName().equals("") ? nameToFind.getName() : compilationUnitPackage.getFullyQualifiedPackageName() + "." + nameToFind.getName();
return new JavaType(name);
}
return new JavaType(importDeclaration.getName().toString());
}
use of com.github.antlrjavaparser.api.ImportDeclaration in project spring-roo by spring-projects.
the class JavaParserUtils method getImportDeclarationFor.
/**
* Looks up the import declaration applicable to the presented name
* expression.
* <p>
* If a fully-qualified name is passed to this method, the corresponding
* import will be evaluated for a complete match. If a simple name is passed
* to this method, the corresponding import will be evaluated if its simple
* name matches. This therefore reflects the normal Java semantics for using
* simple type names that have been imported.
*
* @param compilationUnitServices the types in the compilation unit
* (required)
* @param nameExpr the expression to locate an import for (which would
* generally be a {@link NameExpr} and thus not have a package
* identifier; required)
* @return the relevant import, or null if there is no import for the
* expression
*/
private static ImportDeclaration getImportDeclarationFor(final CompilationUnitServices compilationUnitServices, final NameExpr nameExpr) {
Validate.notNull(compilationUnitServices, "Compilation unit services required");
Validate.notNull(nameExpr, "Name expression required");
final List<ImportDeclaration> imports = compilationUnitServices.getImports();
for (final ImportDeclaration candidate : imports) {
final NameExpr candidateNameExpr = candidate.getName();
if (!candidate.toString().contains("*")) {
Validate.isInstanceOf(QualifiedNameExpr.class, candidateNameExpr, "Expected import '%s' to use a fully-qualified type name", candidate);
}
if (nameExpr instanceof QualifiedNameExpr) {
// is a full match
if (isEqual(nameExpr, candidateNameExpr)) {
return candidate;
}
} else {
// qualified-name package
if (candidateNameExpr.getName().equals(nameExpr.getName())) {
return candidate;
}
}
}
return null;
}
use of com.github.antlrjavaparser.api.ImportDeclaration in project spring-roo by spring-projects.
the class UpdateCompilationUnitUtils method updateCompilationUnitImports.
/**
* Update {@code compilationUnit} imports, annotation, fields, methods...
* from {@code cidCompilationUnit} information
*
* @param compilationUnit
* @param cidCompilationUnit
*/
public static void updateCompilationUnitImports(final CompilationUnit compilationUnit, final CompilationUnit cidCompilationUnit) {
boolean notFound;
final List<ImportDeclaration> cidImports = new ArrayList<ImportDeclaration>();
if (cidCompilationUnit.getImports() != null) {
cidImports.addAll(cidCompilationUnit.getImports());
}
if (compilationUnit.getImports() != null) {
for (final Iterator<ImportDeclaration> originalImportIter = compilationUnit.getImports().iterator(); originalImportIter.hasNext(); ) {
final ImportDeclaration originalImport = originalImportIter.next();
notFound = true;
for (final Iterator<ImportDeclaration> newImportIter = cidImports.iterator(); newImportIter.hasNext(); ) {
final ImportDeclaration newImport = newImportIter.next();
if (equals(originalImport, newImport)) {
// new Import found in original imports
// remove from newImports to check
newImportIter.remove();
// Mark as found
notFound = false;
}
}
if (notFound) {
// If not found in newImports remove from compilation unit
originalImportIter.remove();
}
}
}
if (cidImports.isEmpty()) {
// Done it
return;
}
// Add missing new imports
compilationUnit.getImports().addAll(cidImports);
}
use of com.github.antlrjavaparser.api.ImportDeclaration in project spring-roo by spring-projects.
the class JavaParserTypeParsingService method getCompilationUnitContents.
@Override
public final String getCompilationUnitContents(final ClassOrInterfaceTypeDetails cid) {
Validate.notNull(cid, "Class or interface type details are required");
// Create a compilation unit to store the type to be created
final CompilationUnit compilationUnit = new CompilationUnit();
// NB: this import list is replaced at the end of this method by a
// sorted version
compilationUnit.setImports(new ArrayList<ImportDeclaration>());
if (!cid.getName().isDefaultPackage()) {
compilationUnit.setPackage(new PackageDeclaration(ASTHelper.createNameExpr(cid.getName().getPackage().getFullyQualifiedPackageName())));
}
// Add the class of interface declaration to the compilation unit
final List<TypeDeclaration> types = new ArrayList<TypeDeclaration>();
compilationUnit.setTypes(types);
updateOutput(compilationUnit, null, cid, null);
return compilationUnit.toString();
}
use of com.github.antlrjavaparser.api.ImportDeclaration in project spring-roo by spring-projects.
the class JavaParserClassOrInterfaceTypeDetailsBuilder method build.
@Override
public ClassOrInterfaceTypeDetails build() {
Validate.notEmpty(compilationUnit.getTypes(), "No types in compilation unit, so unable to continue parsing");
ClassOrInterfaceDeclaration clazz = null;
EnumDeclaration enumClazz = null;
final StringBuilder sb = new StringBuilder(compilationUnit.getPackage().getName().toString());
if (name.getEnclosingType() != null) {
sb.append(".").append(name.getEnclosingType().getSimpleTypeName());
}
compilationUnitPackage = new JavaPackage(sb.toString());
// Determine the type name, adding type parameters if possible
final JavaType newName = JavaParserUtils.getJavaType(compilationUnitServices, typeDeclaration);
// Revert back to the original type name (thus avoiding unnecessary
// inferences about java.lang types; see ROO-244)
name = new JavaType(newName.getFullyQualifiedTypeName(), newName.getEnclosingType(), newName.getArray(), newName.getDataType(), newName.getArgName(), newName.getParameters(), name.getModule());
final ClassOrInterfaceTypeDetailsBuilder cidBuilder = new ClassOrInterfaceTypeDetailsBuilder(declaredByMetadataId);
physicalTypeCategory = PhysicalTypeCategory.CLASS;
if (typeDeclaration instanceof ClassOrInterfaceDeclaration) {
clazz = (ClassOrInterfaceDeclaration) typeDeclaration;
if (clazz.isInterface()) {
physicalTypeCategory = PhysicalTypeCategory.INTERFACE;
}
} else if (typeDeclaration instanceof EnumDeclaration) {
enumClazz = (EnumDeclaration) typeDeclaration;
physicalTypeCategory = PhysicalTypeCategory.ENUMERATION;
}
Validate.notNull(physicalTypeCategory, "%s (%s for %s)", UNSUPPORTED_MESSAGE_PREFIX, typeDeclaration.getClass().getSimpleName(), name);
cidBuilder.setName(name);
cidBuilder.setPhysicalTypeCategory(physicalTypeCategory);
imports = compilationUnit.getImports();
if (imports == null) {
imports = new ArrayList<ImportDeclaration>();
compilationUnit.setImports(imports);
}
// Verify the package declaration appears to be correct
if (compilationUnitPackage.equals(name.getPackage()) != true) {
String warningStr = "[Warning] Compilation unit package '" + compilationUnitPackage + "' unexpected for type '" + name.getPackage() + "', it may be a nested class.";
LOGGER.log(Level.WARNING, warningStr);
}
for (final ImportDeclaration importDeclaration : imports) {
if (importDeclaration.getName() instanceof QualifiedNameExpr) {
final String qualifier = ((QualifiedNameExpr) importDeclaration.getName()).getQualifier().toString();
final String simpleName = importDeclaration.getName().getName();
final String fullName = qualifier + "." + simpleName;
// We want to calculate these...
final JavaType type = new JavaType(fullName);
final JavaPackage typePackage = importDeclaration.isAsterisk() ? new JavaPackage(fullName) : type.getPackage();
// Process any comments for the import
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, importDeclaration);
final ImportMetadataBuilder newImport = new ImportMetadataBuilder(declaredByMetadataId, 0, typePackage, type, importDeclaration.isStatic(), importDeclaration.isAsterisk());
newImport.setCommentStructure(commentStructure);
cidBuilder.add(newImport.build());
}
}
// Convert Java Parser modifier into JDK modifier
cidBuilder.setModifier(JavaParserUtils.getJdkModifier(typeDeclaration.getModifiers()));
// Type parameters
final Set<JavaSymbolName> typeParameterNames = new HashSet<JavaSymbolName>();
for (final JavaType param : name.getParameters()) {
final JavaSymbolName arg = param.getArgName();
// Fortunately type names can only appear at the top-level
if (arg != null && !JavaType.WILDCARD_NEITHER_ARG.equals(arg) && !JavaType.WILDCARD_EXTENDS_ARG.equals(arg) && !JavaType.WILDCARD_SUPER_ARG.equals(arg)) {
typeParameterNames.add(arg);
}
}
List<ClassOrInterfaceType> implementsList;
List<AnnotationExpr> annotationsList = null;
List<BodyDeclaration> members = null;
if (clazz != null) {
final List<ClassOrInterfaceType> extendsList = clazz.getExtends();
if (extendsList != null) {
for (final ClassOrInterfaceType candidate : extendsList) {
final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
cidBuilder.addExtendsTypes(javaType);
}
}
final List<JavaType> extendsTypes = cidBuilder.getExtendsTypes();
// Obtain the superclass, if this is a class and one is available
if (physicalTypeCategory == PhysicalTypeCategory.CLASS && extendsTypes.size() == 1) {
final JavaType superclass = extendsTypes.get(0);
final String superclassId = typeLocationService.getPhysicalTypeIdentifier(superclass);
PhysicalTypeMetadata superPtm = null;
if (superclassId != null) {
superPtm = (PhysicalTypeMetadata) metadataService.get(superclassId);
}
if (superPtm != null && superPtm.getMemberHoldingTypeDetails() != null) {
cidBuilder.setSuperclass(superPtm.getMemberHoldingTypeDetails());
}
}
implementsList = clazz.getImplements();
if (implementsList != null) {
for (final ClassOrInterfaceType candidate : implementsList) {
final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
cidBuilder.addImplementsType(javaType);
}
}
annotationsList = typeDeclaration.getAnnotations();
members = clazz.getMembers();
}
if (enumClazz != null) {
final List<EnumConstantDeclaration> constants = enumClazz.getEntries();
if (constants != null) {
for (final EnumConstantDeclaration enumConstants : constants) {
cidBuilder.addEnumConstant(new JavaSymbolName(enumConstants.getName()));
}
}
implementsList = enumClazz.getImplements();
annotationsList = enumClazz.getAnnotations();
members = enumClazz.getMembers();
}
if (annotationsList != null) {
for (final AnnotationExpr candidate : annotationsList) {
final AnnotationMetadata md = JavaParserAnnotationMetadataBuilder.getInstance(candidate, compilationUnitServices).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, candidate);
md.setCommentStructure(commentStructure);
cidBuilder.addAnnotation(md);
}
}
if (members != null) {
// type in the signature of the enclosing type
for (final BodyDeclaration bodyDeclaration : members) {
if (bodyDeclaration instanceof TypeDeclaration) {
// Found a type
innerTypes.add((TypeDeclaration) bodyDeclaration);
}
}
for (final BodyDeclaration member : members) {
if (member instanceof FieldDeclaration) {
final FieldDeclaration castMember = (FieldDeclaration) member;
for (final VariableDeclarator var : castMember.getVariables()) {
final FieldMetadata field = JavaParserFieldMetadataBuilder.getInstance(declaredByMetadataId, castMember, var, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
field.setCommentStructure(commentStructure);
cidBuilder.addField(field);
}
}
if (member instanceof MethodDeclaration) {
final MethodDeclaration castMember = (MethodDeclaration) member;
final MethodMetadata method = JavaParserMethodMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
method.setCommentStructure(commentStructure);
cidBuilder.addMethod(method);
}
if (member instanceof ConstructorDeclaration) {
final ConstructorDeclaration castMember = (ConstructorDeclaration) member;
final ConstructorMetadata constructor = JavaParserConstructorMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
constructor.setCommentStructure(commentStructure);
cidBuilder.addConstructor(constructor);
}
if (member instanceof TypeDeclaration) {
final TypeDeclaration castMember = (TypeDeclaration) member;
final JavaType innerType = new JavaType(castMember.getName(), name);
final String innerTypeMetadataId = PhysicalTypeIdentifier.createIdentifier(innerType, PhysicalTypeIdentifier.getPath(declaredByMetadataId));
final ClassOrInterfaceTypeDetails cid = new JavaParserClassOrInterfaceTypeDetailsBuilder(compilationUnit, compilationUnitServices, castMember, innerTypeMetadataId, innerType, metadataService, typeLocationService).build();
cidBuilder.addInnerType(cid);
}
}
}
return cidBuilder.build();
}
Aggregations