Search in sources :

Example 16 with JavaPackage

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

the class DatabaseXmlUtils method readDatabaseWithDom.

static Database readDatabaseWithDom(final InputStream inputStream) {
    final Document document = XmlUtils.readXml(inputStream);
    final Element databaseElement = document.getDocumentElement();
    final Set<Table> tables = new LinkedHashSet<Table>();
    final List<Element> tableElements = XmlUtils.findElements("table", databaseElement);
    for (final Element tableElement : tableElements) {
        final String alias = tableElement.getAttribute("alias");
        final String schemaName = StringUtils.defaultIfEmpty(alias, databaseElement.getAttribute(NAME));
        final Table table = new Table(tableElement.getAttribute(NAME), new Schema(schemaName));
        if (StringUtils.isNotBlank(tableElement.getAttribute(DESCRIPTION))) {
            table.setDescription(tableElement.getAttribute(DESCRIPTION));
        }
        final List<Element> columnElements = XmlUtils.findElements("column", tableElement);
        for (final Element columnElement : columnElements) {
            final String type = columnElement.getAttribute("type");
            final String[] dataTypeAndName = StringUtils.split(type, ",");
            final int dataType = Integer.parseInt(dataTypeAndName[0]);
            final String typeName = dataTypeAndName[1];
            final int columnSize = Integer.parseInt(columnElement.getAttribute("size"));
            final int scale = Integer.parseInt(columnElement.getAttribute("scale"));
            final Column column = new Column(columnElement.getAttribute(NAME), dataType, typeName, columnSize, scale);
            column.setDescription(columnElement.getAttribute(DESCRIPTION));
            column.setPrimaryKey(Boolean.parseBoolean(columnElement.getAttribute("primaryKey")));
            column.setRequired(Boolean.parseBoolean(columnElement.getAttribute("required")));
            table.addColumn(column);
        }
        final List<Element> foreignKeyElements = XmlUtils.findElements("foreign-key", tableElement);
        for (final Element foreignKeyElement : foreignKeyElements) {
            final ForeignKey foreignKey = new ForeignKey(foreignKeyElement.getAttribute(NAME), foreignKeyElement.getAttribute(FOREIGN_TABLE));
            foreignKey.setOnDelete(CascadeAction.getCascadeAction(foreignKeyElement.getAttribute(ON_DELETE)));
            foreignKey.setOnUpdate(CascadeAction.getCascadeAction(foreignKeyElement.getAttribute(ON_UPDATE)));
            final List<Element> optionElements = XmlUtils.findElements("option", foreignKeyElement);
            for (final Element optionElement : optionElements) {
                final String key = optionElement.getAttribute("key");
                final String value = optionElement.getAttribute("value");
                if (key.equals("exported")) {
                    foreignKey.setExported(Boolean.parseBoolean(value));
                }
                if (key.equals("foreignSchemaName")) {
                    foreignKey.setForeignSchemaName(value);
                }
            }
            final List<Element> referenceElements = XmlUtils.findElements(REFERENCE, foreignKeyElement);
            for (final Element referenceElement : referenceElements) {
                final Reference reference = new Reference(referenceElement.getAttribute(LOCAL), referenceElement.getAttribute(FOREIGN));
                foreignKey.addReference(reference);
            }
            table.addImportedKey(foreignKey);
        }
        addIndices(table, tableElement, IndexType.INDEX);
        addIndices(table, tableElement, IndexType.UNIQUE);
        tables.add(table);
    }
    JavaPackage destinationPackage = null;
    if (StringUtils.isNotBlank(databaseElement.getAttribute("package"))) {
        destinationPackage = new JavaPackage(databaseElement.getAttribute("package"));
    }
    final Database database = new Database(tables);
    database.setDestinationPackage(destinationPackage);
    final List<Element> optionElements = XmlUtils.findElements("option", databaseElement);
    for (final Element optionElement : optionElements) {
        final String key = optionElement.getAttribute("key");
        final String value = optionElement.getAttribute("value");
        if (key.equals("moduleName")) {
            database.setModuleName(value);
        }
        if (key.equals("repository")) {
            database.setRepository(Boolean.parseBoolean(value));
        }
        if (key.equals("service")) {
            database.setService(Boolean.parseBoolean(value));
        }
        if (key.equals("testAutomatically")) {
            database.setTestAutomatically(Boolean.parseBoolean(value));
        }
        if (key.equals("includeNonPortableAttributes")) {
            database.setIncludeNonPortableAttributes(Boolean.parseBoolean(value));
        }
        if (key.equals("disableVersionFields")) {
            database.setDisableVersionFields(Boolean.parseBoolean(value));
        }
        if (key.equals("disableGeneratedIdentifiers")) {
            database.setDisableGeneratedIdentifiers(Boolean.parseBoolean(value));
        }
    }
    return database;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 17 with JavaPackage

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

the class ServiceCommands method service.

@CliCommand(value = "service", help = "Creates new service interface and its implementation related to an entity, or for all the " + "entities in generated project, with some basic management methods by using Spring Data repository methods.")
public void service(@CliOption(key = "all", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Indicates if developer wants to generate service interfaces and their implementations " + "for every entity of current project. " + "This option is mandatory if `--entity` is not specified. Otherwise, using `--entity` " + "will cause the parameter `--all` won't be available. " + "Default if option present: `true`; default if option not present: `false`.") boolean all, @CliOption(key = "entity", optionContext = PROJECT, mandatory = false, help = "The domain entity this service should manage. When working on a single module " + "project, simply specify the name of the entity. If you consider it necessary, you can " + "also specify the package. Ex.: `--class ~.domain.MyEntity` (where `~` is the base package). " + "When working with multiple modules, you should specify the name of the entity and the " + "module where it is. Ex.: `--class model:~.domain.MyEntity`. If the module is not specified, " + "it is assumed that the entity is in the module which has the focus. " + "Possible values are: any of the entities in the project. " + "This option is mandatory if `--all` is not specified. Otherwise, using `--all` " + "will cause the parameter `--entity` won't be available.") final JavaType domainType, @CliOption(key = "repository", optionContext = PROJECT, mandatory = true, help = "The repository this service should expose. When working on a single module project, " + "simply specify the name of the class. If you consider it necessary, you can also " + "specify the package. Ex.: `--class ~.repository.MyClass` (where `~` is the base " + "package). When working with multiple modules, you should specify the name of the class " + "and the module where it is. Ex.: `--class repository:~.MyClass`. If the module is not " + "specified, it is assumed that the class is in the module which has the focus. " + "Possible values are: any of the repositories annotated with `@RooJpaRepository` and " + "associated to the entity specified in `--entity`. " + "This option is mandatory if `--entity` has been already specified and the project is " + "multi-module. " + "This option is available only when `--entity` has been specified. " + "Default if option not present: first repository annotated with `@RooJpaRepository` and " + "associated to the entity specified in `--entity`.") final JavaType repositoryType, @CliOption(key = "interface", mandatory = true, help = "The service interface to be generated. When working on a single module project, simply " + "specify the name of the class. If you consider it necessary, you can also specify the " + "package. Ex.: `--class ~.service.api.MyClass` (where `~` is the base package). When " + "working with multiple modules, you should specify the name of the class and the module " + "where it is. Ex.: `--class service-api:~.MyClass`. If the module is not specified, it " + "is assumed that the class is in the module which has the focus. " + "This option is mandatory if `--entity` has been already specified and the project is " + "multi-module. " + "This option is available only when `--entity` has been specified. " + "Default if option not present: concatenation of entity simple name with 'Service' in " + "`~.service.api` package, or 'service-api:~.' if multi-module project.") final JavaType interfaceType, @CliOption(key = "class", mandatory = false, help = "The service implementation to be generated. When working on a single module " + "project, simply specify the name of the class. If you consider it necessary, you can " + "also specify the package. Ex.: `--class ~.service.impl.MyClass` (where `~` is the base " + "package). When working with multiple modules, you should specify the name of the class " + "and the module where it is. Ex.: `--class service-impl:~.MyClass`. If the module is not " + "specified, it is assumed that the class is in the module which has the focus. " + "This option is available only when `--entity` has been specified. " + "Default if option not present: concatenation of entity simple name with 'ServiceImpl' " + "in `~.service.impl` package, or 'service-impl:~.' if multi-module project.") final JavaType implType, @CliOption(key = "apiPackage", mandatory = false, help = "The java interface package. In multi-module project you should specify the module name" + " before the package name. Ex.: `--apiPackage service-api:org.springframework.roo` but, " + "if module name is not present, the Roo Shell focused module will be used. " + "This option is available only when `--all` parameter has been specified. " + "Default value if not present: `~.service.api` package, or 'service-api:~.' if " + "multi-module project.") JavaPackage apiPackage, @CliOption(key = "implPackage", mandatory = false, help = "The java package of the implementation classes for the interfaces. In multi-module " + "project you should specify the module name before the package name. Ex.: `--implPackage " + "service-impl:org.springframework.roo` but, if module name is not present, the Roo Shell " + "focused module will be used. " + "This option is available only when `--all` parameter has been specified. " + "Default value if not present: `~.service.impl` package, or 'service-impl:~.' if " + "multi-module project.") JavaPackage implPackage) {
    if (all) {
        // If user didn't specified some API package, use default API package
        if (apiPackage == null) {
            if (projectOperations.isMultimoduleProject()) {
                // Build default JavaPackage with module
                for (String moduleName : projectOperations.getModuleNames()) {
                    if (moduleName.equals("service-api")) {
                        Pom module = projectOperations.getPomFromModuleName(moduleName);
                        apiPackage = new JavaPackage(typeLocationService.getTopLevelPackageForModule(module), moduleName);
                        break;
                    }
                }
                // Check if repository found
                Validate.notNull(apiPackage, "Couldn't find in project a default service.api " + "package. Please, use 'apiPackage' option to specify it.");
            } else {
                // Build default JavaPackage for single module
                apiPackage = new JavaPackage(projectOperations.getFocusedTopLevelPackage().getFullyQualifiedPackageName().concat(".service.api"), projectOperations.getFocusedModuleName());
            }
        }
        // If user didn't specified some impl package, use default impl package
        if (implPackage == null) {
            if (projectOperations.isMultimoduleProject()) {
                // Build default JavaPackage with module
                for (String moduleName : projectOperations.getModuleNames()) {
                    if (moduleName.equals("service-impl")) {
                        Pom module = projectOperations.getPomFromModuleName(moduleName);
                        implPackage = new JavaPackage(typeLocationService.getTopLevelPackageForModule(module), moduleName);
                        break;
                    }
                }
                // Check if repository found
                Validate.notNull(implPackage, "Couldn't find in project a default service.impl " + "package. Please, use 'implPackage' option to specify it.");
            } else {
                // Build default JavaPackage for single module
                implPackage = new JavaPackage(projectOperations.getFocusedTopLevelPackage().getFullyQualifiedPackageName().concat(".service.impl"), projectOperations.getFocusedModuleName());
            }
        }
        serviceOperations.addAllServices(apiPackage, implPackage);
    } else {
        serviceOperations.addService(domainType, repositoryType, interfaceType, implType);
    }
}
Also used : JavaPackage(org.springframework.roo.model.JavaPackage) Pom(org.springframework.roo.project.maven.Pom) CliCommand(org.springframework.roo.shell.CliCommand)

Example 18 with JavaPackage

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

the class PushInOperationsImpl method pushInAll.

@Override
public List<Object> pushInAll(boolean writeOnDisk, boolean force) {
    List<Object> pushedElements = new ArrayList<Object>();
    List<JavaPackage> projectPackages = new ArrayList<JavaPackage>();
    // Getting all JavaTypes on current project
    for (String moduleName : getProjectOperations().getModuleNames()) {
        // ROO-3833: Push-in all following a specific order to avoid
        // metadata dependencies errors
        List<JavaPackage> packagesForModule = getTypeLocationService().getPackagesForModule(getProjectOperations().getPomFromModuleName(moduleName));
        for (JavaPackage modulePackage : packagesForModule) {
            projectPackages.add(modulePackage);
        }
        Collection<JavaType> allDeclaredTypes = getTypeLocationService().getTypesForModule(getProjectOperations().getPomFromModuleName(moduleName));
        if (!force) {
            for (JavaType declaredType : allDeclaredTypes) {
                // Push-in all content from .aj files to .java files
                pushedElements.addAll(pushInClass(declaredType, writeOnDisk, force));
            }
        } else {
            for (JavaPackage modulePackage : packagesForModule) {
                pushIn(modulePackage, null, null, writeOnDisk);
                getFileManager().scan();
            }
        }
    }
    if (!force) {
        LOGGER.log(Level.INFO, "All these changes will be applied. Execute your previous push-in command using --force parameter to apply them.");
    }
    return pushedElements;
}
Also used : AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) ArrayList(java.util.ArrayList) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 19 with JavaPackage

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

the class LoggingOperationsImpl method setupProperties.

private void setupProperties(final LogLevel logLevel, final LoggerPackage loggerPackage) {
    final String filePath = pathResolver.getFocusedIdentifier(Path.SRC_MAIN_RESOURCES, "log4j.properties");
    MutableFile log4jMutableFile = null;
    final Properties props = new Properties();
    InputStream inputStream = null;
    try {
        if (fileManager.exists(filePath)) {
            log4jMutableFile = fileManager.updateFile(filePath);
            inputStream = log4jMutableFile.getInputStream();
            props.load(inputStream);
        } else {
            log4jMutableFile = fileManager.createFile(filePath);
            inputStream = FileUtils.getInputStream(getClass(), "log4j-template.properties");
            Validate.notNull(inputStream, "Could not acquire log4j configuration template");
            props.load(inputStream);
        }
    } catch (final IOException ioe) {
        throw new IllegalStateException(ioe);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    final JavaPackage topLevelPackage = projectOperations.getTopLevelPackage(projectOperations.getFocusedModuleName());
    final String logStr = "log4j.logger.";
    switch(loggerPackage) {
        case ROOT:
            props.remove("log4j.rootLogger");
            props.setProperty("log4j.rootLogger", logLevel.name() + ", stdout");
            break;
        case PROJECT:
            props.remove(logStr + topLevelPackage.getFullyQualifiedPackageName());
            props.setProperty(logStr + topLevelPackage.getFullyQualifiedPackageName(), logLevel.name());
            break;
        default:
            for (final String packageName : loggerPackage.getPackageNames()) {
                props.remove(logStr + packageName);
                props.setProperty(logStr + packageName, logLevel.name());
            }
            break;
    }
    OutputStream outputStream = null;
    try {
        outputStream = log4jMutableFile.getOutputStream();
        props.store(outputStream, "Updated at " + new Date());
    } catch (final IOException ioe) {
        throw new IllegalStateException(ioe);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Properties(java.util.Properties) JavaPackage(org.springframework.roo.model.JavaPackage) Date(java.util.Date) MutableFile(org.springframework.roo.process.manager.MutableFile)

Example 20 with JavaPackage

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

the class ControllerOperationsImpl method getDefaultControllerPackage.

/**
 * Get default package to set it to a controller or a detail controller.
 * Search classes with @SpringBootApplication annotation to establish the
 * module and package.
 *
 * @return project's default controller package
 */
private JavaPackage getDefaultControllerPackage() {
    String module = "";
    String topLevelPackage = "";
    if (getProjectOperations().isMultimoduleProject()) {
        // scan all modules to get that modules that contains a class
        // annotated with @SpringBootApplication
        Set<ClassOrInterfaceTypeDetails> applicationClasses = getTypeLocationService().findClassesOrInterfaceDetailsWithAnnotation(SpringJavaType.SPRING_BOOT_APPLICATION);
        // Compare the focus module. If it is an 'application' module,
        // set it like controllerPackage
        boolean controllersPackageNotSet = true;
        String focusedModuleName = getProjectOperations().getFocusedModuleName();
        for (ClassOrInterfaceTypeDetails applicationClass : applicationClasses) {
            if (focusedModuleName.equals(applicationClass.getType().getModule())) {
                module = focusedModuleName;
                topLevelPackage = applicationClass.getType().getPackage().getFullyQualifiedPackageName();
                controllersPackageNotSet = false;
                break;
            }
        }
        if (controllersPackageNotSet) {
            // if exists more than one module, show error message
            if (applicationClasses.size() > 1) {
                LOGGER.log(Level.INFO, String.format("ERROR: Exists more than one module 'application'. Specify --package parameter to set the indicated"));
                return null;
            } else {
                ClassOrInterfaceTypeDetails applicationClass = applicationClasses.iterator().next();
                module = applicationClass.getType().getModule();
                topLevelPackage = applicationClass.getType().getPackage().getFullyQualifiedPackageName();
            }
        }
    } else {
        topLevelPackage = getProjectOperations().getFocusedTopLevelPackage().getFullyQualifiedPackageName();
    }
    String packageStr = topLevelPackage;
    if (StringUtils.isNotEmpty(module)) {
        packageStr = packageStr.concat(".").concat(module);
    }
    return new JavaPackage(packageStr.concat(".web"), module);
}
Also used : 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