Search in sources :

Example 11 with JavaPackage

use of org.springframework.roo.model.JavaPackage in project spring-roo by spring-projects.

the class JavaParserTypeResolutionService method getPackage.

@Override
public final JavaPackage getPackage(final String fileIdentifier) {
    Validate.notBlank(fileIdentifier, "Compilation unit path required");
    Validate.isTrue(new File(fileIdentifier).exists(), "The file doesn't exist");
    Validate.isTrue(new File(fileIdentifier).isFile(), "The identifier doesn't represent a file");
    try {
        final File file = new File(fileIdentifier);
        String typeContents = "";
        try {
            typeContents = FileUtils.readFileToString(file);
        } catch (final IOException ignored) {
        }
        if (StringUtils.isBlank(typeContents)) {
            return null;
        }
        final CompilationUnit compilationUnit = JavaParser.parse(new ByteArrayInputStream(typeContents.getBytes()));
        if (compilationUnit == null || compilationUnit.getPackage() == null) {
            return null;
        }
        return new JavaPackage(compilationUnit.getPackage().getName().toString());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    } catch (final ParseException e) {
        throw new IllegalStateException("Failed to parse " + fileIdentifier + " : " + e.getMessage());
    }
}
Also used : CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) ParseException(com.github.antlrjavaparser.ParseException) File(java.io.File) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 12 with JavaPackage

use of org.springframework.roo.model.JavaPackage in project spring-roo by spring-projects.

the class JavaParserUtils method importTypeIfRequired.

/**
 * Attempts to import the presented {@link JavaType}.
 * <p>
 * Whether imported or not, the method returns a {@link NameExpr} suitable
 * for subsequent use when referring to that type.
 * <p>
 * If an attempt is made to import a java.lang type, it is ignored.
 * <p>
 * If an attempt is made to import a type without a package, it is ignored.
 * <p>
 * We import every type usage even if the type usage is within the same
 * package and would theoretically not require an import. This is undertaken
 * so that there is no requirement to separately parse every unqualified
 * type usage within the compilation unit so as to refrain from importing
 * subsequently conflicting types.
 *
 * @param targetType the compilation unit target type (required)
 * @param imports the compilation unit's imports (required)
 * @param typeToImport the type to be imported (required)
 * @return the name expression to be used when referring to that type (never
 *         null)
 */
public static NameExpr importTypeIfRequired(final JavaType targetType, final List<ImportDeclaration> imports, final JavaType typeToImport) {
    Validate.notNull(targetType, "Target type is required");
    final JavaPackage compilationUnitPackage = targetType.getPackage();
    Validate.notNull(imports, "Compilation unit imports required");
    Validate.notNull(typeToImport, "Java type to import is required");
    // If it's a primitive, it's really easy
    if (typeToImport.isPrimitive()) {
        return new NameExpr(typeToImport.getNameIncludingTypeParameters());
    }
    // Handle if the type doesn't have a package at all
    if (typeToImport.isDefaultPackage()) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    final JavaPackage typeToImportPackage = typeToImport.getPackage();
    if (typeToImportPackage.equals(compilationUnitPackage)) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    NameExpr typeToImportExpr;
    if (typeToImport.getEnclosingType() == null) {
        typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport.getPackage().getFullyQualifiedPackageName()), typeToImport.getSimpleTypeName());
    } else {
        typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport.getEnclosingType().getFullyQualifiedTypeName()), typeToImport.getSimpleTypeName());
    }
    final ImportDeclaration newImport = new ImportDeclaration(typeToImportExpr, false, false);
    boolean addImport = true;
    boolean useSimpleTypeName = false;
    for (final ImportDeclaration existingImport : imports) {
        if (existingImport.getName().getName().equals(newImport.getName().getName())) {
            // Do not import, as there is already an import with the simple
            // type name
            addImport = false;
            // simple type name
            if (isEqual(existingImport.getName(), newImport.getName())) {
                useSimpleTypeName = true;
                break;
            }
        }
    }
    if (addImport && JdkJavaType.isPartOfJavaLang(typeToImport.getSimpleTypeName())) {
        // This simple type name would be part of java.lang if left as the
        // simple name. We want a fully-qualified name.
        addImport = false;
        useSimpleTypeName = false;
    }
    if (JdkJavaType.isPartOfJavaLang(typeToImport)) {
        // So we would have imported, but we don't need to
        addImport = false;
        // The fact we could have imported means there was no other
        // conflicting simple type names
        useSimpleTypeName = true;
    }
    if (addImport && typeToImport.getPackage().equals(compilationUnitPackage)) {
    // It is not theoretically necessary to add an import for something
    // in the same package,
    // but we elect to explicitly perform an import so future
    // conflicting types are not imported
    // addImport = true;
    // useSimpleTypeName = false;
    }
    if (addImport && targetType.getSimpleTypeName().equals(typeToImport.getSimpleTypeName())) {
        // So we would have imported it, but then it would conflict with the
        // simple name of the type
        addImport = false;
        useSimpleTypeName = false;
    }
    if (addImport) {
        imports.add(newImport);
        useSimpleTypeName = true;
    }
    // (forget imports, though!)
    if (typeToImport.getArgName() != null) {
        return new NameExpr(typeToImport.toString());
    }
    if (useSimpleTypeName) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    return new QualifiedNameExpr(new NameExpr(typeToImport.getPackage().getFullyQualifiedPackageName()), typeToImport.getSimpleTypeName());
}
Also used : QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 13 with JavaPackage

use of org.springframework.roo.model.JavaPackage in project spring-roo by spring-projects.

the class JavaParserUtils method getJavaTypeNow.

/**
 * Resolves the effective {@link JavaType} a {@link ClassOrInterfaceType}
 * represents, including any type arguments.
 *
 * @param compilationUnitServices for package management (required)
 * @param cit the class or interface type to resolve (required)
 * @return the effective Java type (never null)
 */
public static JavaType getJavaTypeNow(final CompilationUnitServices compilationUnitServices, final ClassOrInterfaceType cit, final Set<JavaSymbolName> typeParameters) {
    Validate.notNull(compilationUnitServices, "Compilation unit services required");
    Validate.notNull(cit, "ClassOrInterfaceType required");
    final JavaPackage compilationUnitPackage = compilationUnitServices.getCompilationUnitPackage();
    Validate.notNull(compilationUnitPackage, "Compilation unit package required");
    String typeName = cit.getName();
    ClassOrInterfaceType scope = cit.getScope();
    while (scope != null) {
        typeName = scope.getName() + "." + typeName;
        scope = scope.getScope();
    }
    final NameExpr nameExpr = getNameExpr(typeName);
    final JavaType effectiveType = getJavaType(compilationUnitServices, nameExpr, typeParameters);
    // Handle any type arguments
    final List<JavaType> parameterTypes = new ArrayList<JavaType>();
    if (cit.getTypeArgs() != null) {
        for (final Type ta : cit.getTypeArgs()) {
            parameterTypes.add(getJavaType(compilationUnitServices, ta, typeParameters));
        }
    }
    return new JavaType(effectiveType.getFullyQualifiedTypeName(), effectiveType.getArray(), effectiveType.getDataType(), null, parameterTypes);
}
Also used : JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) WildcardType(com.github.antlrjavaparser.api.type.WildcardType) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) DataType(org.springframework.roo.model.DataType) JdkJavaType(org.springframework.roo.model.JdkJavaType) VoidType(com.github.antlrjavaparser.api.type.VoidType) JavaType(org.springframework.roo.model.JavaType) PrimitiveType(com.github.antlrjavaparser.api.type.PrimitiveType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ArrayList(java.util.ArrayList) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 14 with JavaPackage

use of org.springframework.roo.model.JavaPackage in project spring-roo by spring-projects.

the class TypeLocationServiceImpl method getPhysicalTypeIdentifier.

public String getPhysicalTypeIdentifier(final String fileCanonicalPath) {
    Validate.notBlank(fileCanonicalPath, "File canonical path required");
    if (!doesPathIndicateJavaType(fileCanonicalPath)) {
        return null;
    }
    String physicalTypeIdentifier = getTypeCache().getTypeIdFromTypeFilePath(fileCanonicalPath);
    if (physicalTypeIdentifier != null) {
        return physicalTypeIdentifier;
    }
    final String typeDirectory = FileUtils.getFirstDirectory(fileCanonicalPath);
    final String simpleTypeName = StringUtils.replace(fileCanonicalPath, typeDirectory + File.separator, "", 1).replace(".java", "");
    final JavaPackage javaPackage = getTypeResolutionService().getPackage(fileCanonicalPath);
    if (javaPackage == null) {
        return null;
    }
    final Pom module = getProjectOperations().getModuleForFileIdentifier(fileCanonicalPath);
    Validate.notNull(module, "The module for the file '" + fileCanonicalPath + "' could not be located");
    final JavaType javaType = new JavaType(javaPackage.getFullyQualifiedPackageName() + "." + simpleTypeName, module.getModuleName());
    getTypeCache().cacheTypeAgainstModule(module, javaType);
    String reducedPath = fileCanonicalPath.replace(javaType.getRelativeFileName(), "");
    reducedPath = StringUtils.stripEnd(reducedPath, File.separator);
    for (final PhysicalPath physicalPath : module.getPhysicalPaths()) {
        if (physicalPath.getLocationPath().startsWith(reducedPath)) {
            final LogicalPath path = physicalPath.getLogicalPath();
            physicalTypeIdentifier = MetadataIdentificationUtils.create(PhysicalTypeIdentifier.class.getName(), path.getName() + "?" + javaType.getFullyQualifiedTypeName());
            break;
        }
    }
    getTypeCache().cacheFilePathAgainstTypeIdentifier(fileCanonicalPath, physicalTypeIdentifier);
    return physicalTypeIdentifier;
}
Also used : JavaType(org.springframework.roo.model.JavaType) LogicalPath(org.springframework.roo.project.LogicalPath) JavaPackage(org.springframework.roo.model.JavaPackage) PhysicalPath(org.springframework.roo.project.PhysicalPath) Pom(org.springframework.roo.project.maven.Pom)

Example 15 with JavaPackage

use of org.springframework.roo.model.JavaPackage in project spring-roo by spring-projects.

the class DbreDatabaseListenerImpl method reverseEngineer.

private void reverseEngineer(final Database database) {
    final Set<ClassOrInterfaceTypeDetails> managedEntities = getTypeLocationService().findClassesOrInterfaceDetailsWithAnnotation(ROO_DB_MANAGED);
    // Lookup the relevant destination package if not explicitly given
    final JavaPackage destinationPackage = getDestinationPackage(database, managedEntities);
    // Set the destination package in the database
    database.setDestinationPackage(destinationPackage);
    // Get tables from database
    final Set<Table> tables = new LinkedHashSet<Table>(database.getTables());
    // Manage existing entities with @RooDbManaged annotation
    for (final ClassOrInterfaceTypeDetails managedEntity : managedEntities) {
        // Remove table from set as each managed entity is processed.
        // The tables that remain in the set will be used for creation of
        // new entities later
        final Table table = updateOrDeleteManagedEntity(managedEntity, database);
        if (table != null) {
            tables.remove(table);
        }
    }
    // Create new entities from tables
    final List<ClassOrInterfaceTypeDetails> newEntities = new ArrayList<ClassOrInterfaceTypeDetails>();
    for (final Table table : tables) {
        // Don't create types from join tables in many-to-many associations
        if (!table.isJoinTable()) {
            JavaPackage schemaPackage = destinationPackage;
            if (database.hasMultipleSchemas()) {
                schemaPackage = new JavaPackage(destinationPackage.getFullyQualifiedPackageName() + "." + DbreTypeUtils.suggestPackageName(table.getSchema().getName()));
            }
            final JavaType javaType = DbreTypeUtils.suggestTypeNameForNewTable(table.getName(), schemaPackage);
            if (getTypeLocationService().getTypeDetails(javaType) == null) {
                table.setIncludeNonPortableAttributes(database.isIncludeNonPortableAttributes());
                table.setDisableVersionFields(database.isDisableVersionFields());
                table.setDisableGeneratedIdentifiers(database.isDisableGeneratedIdentifiers());
                newEntities.add(createNewManagedEntityFromTable(javaType, table));
            }
        }
    }
    // Create repositories if required
    if (database.isRepository()) {
        for (final ClassOrInterfaceTypeDetails entity : newEntities) {
            final JavaType type = entity.getType();
            getRepositoryJpaOperations().addRepository(new JavaType(type.getFullyQualifiedTypeName() + "Repository"), type, null);
        }
    }
    // Create services if required
    if (database.isService()) {
        for (final ClassOrInterfaceTypeDetails entity : newEntities) {
            final JavaType type = entity.getType();
            final String typeName = type.getFullyQualifiedTypeName();
            getServiceOperations().addService(type, new JavaType(typeName + "Service"), null);
        }
    }
    // Create integration tests if required
    if (database.isTestAutomatically()) {
        for (final ClassOrInterfaceTypeDetails entity : newEntities) {
            getIntegrationTestOperations().newIntegrationTest(entity.getType());
        }
    }
    // Notify
    final List<ClassOrInterfaceTypeDetails> allEntities = new ArrayList<ClassOrInterfaceTypeDetails>();
    allEntities.addAll(newEntities);
    allEntities.addAll(managedEntities);
    notify(allEntities);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) Table(org.springframework.roo.addon.dbre.addon.model.Table) ArrayList(java.util.ArrayList) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JavaPackage(org.springframework.roo.model.JavaPackage)

Aggregations

JavaPackage (org.springframework.roo.model.JavaPackage)24 JavaType (org.springframework.roo.model.JavaType)11 ArrayList (java.util.ArrayList)7 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)6 QualifiedNameExpr (com.github.antlrjavaparser.api.expr.QualifiedNameExpr)5 Pom (org.springframework.roo.project.maven.Pom)5 ImportDeclaration (com.github.antlrjavaparser.api.ImportDeclaration)4 NameExpr (com.github.antlrjavaparser.api.expr.NameExpr)4 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)4 JdkJavaType (org.springframework.roo.model.JdkJavaType)4 TypeDeclaration (com.github.antlrjavaparser.api.body.TypeDeclaration)3 ClassOrInterfaceType (com.github.antlrjavaparser.api.type.ClassOrInterfaceType)3 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)3 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)3 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)3 BodyDeclaration (com.github.antlrjavaparser.api.body.BodyDeclaration)2 ClassOrInterfaceDeclaration (com.github.antlrjavaparser.api.body.ClassOrInterfaceDeclaration)2 EnumConstantDeclaration (com.github.antlrjavaparser.api.body.EnumConstantDeclaration)2 EnumDeclaration (com.github.antlrjavaparser.api.body.EnumDeclaration)2 AnnotationExpr (com.github.antlrjavaparser.api.expr.AnnotationExpr)2