Search in sources :

Example 11 with CliCommand

use of org.springframework.roo.shell.CliCommand in project spring-roo by spring-projects.

the class JpaCommands method newPersistenceClassJpa.

@CliCommand(value = "entity jpa", help = "Creates a new JPA persistent entity in the directory _src/main/java_ of the selected project module (if any) with `@RooEntity` annotation.")
public void newPersistenceClassJpa(@CliOption(key = "class", optionContext = UPDATELAST_PROJECT, mandatory = true, help = "The name of the entity to create. If you consider it necessary, you can also " + "specify the package (base package can be specified with `~`). " + "Ex.: `--class ~.domain.MyEntity`. You can specify module as well, if necessary. " + "Ex.: `--class model:~.domain.MyEntity`. When working with a multi-module project, " + "if module is not specified the entity will be created in the module which has the focus.") final JavaType name, @CliOption(key = "table", mandatory = true, help = "The JPA table name to use for this entity. " + "This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final String table, @CliOption(key = "identifierColumn", mandatory = true, help = "The JPA identifier field column to use for this entity. " + "This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final String identifierColumn, @CliOption(key = "versionField", mandatory = true, help = "The JPA version field name to use for this entity. " + "This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final String versionField, @CliOption(key = "versionColumn", mandatory = true, help = "The JPA version field column to use for this entity. " + "This option is available if 'versionField' option is set." + " This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final String versionColumn, @CliOption(key = "versionType", mandatory = true, optionContext = "java-lang,project", unspecifiedDefaultValue = VERSION_DEFAULT_TYPE, help = "The data type that will be used for the JPA version field. " + "This option is available if 'versionField' option is set." + " This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final JavaType versionType, @CliOption(key = "sequenceName", mandatory = true, help = "The name of the sequence for incrementing sequence-driven primary keys." + " This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`.") final String sequenceName, @CliOption(key = "identifierStrategy", mandatory = true, specifiedDefaultValue = "AUTO", help = "The generation value strategy to be used." + " This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration setting it’s `true`. " + "Default if option present: `AUTO`.") final IdentifierStrategy identifierStrategy, @CliOption(key = "extends", mandatory = false, unspecifiedDefaultValue = "java.lang.Object", optionContext = SUPERCLASS, help = "The fully qualified name of the superclass. " + "Default if option not present: `java.lang.Object`.") final JavaType superclass, @CliOption(key = "implements", mandatory = false, optionContext = INTERFACE, help = "The fully qualified name of the interface to implement.") final JavaType implementsType, @CliOption(key = "abstract", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Whether the generated class should be marked as abstract. " + "Default if option present: `true`; default if option not present: `false`.") final boolean createAbstract, @CliOption(key = "schema", mandatory = false, help = "The JPA table schema name to use for this entity.") final String schema, @CliOption(key = "catalog", mandatory = false, help = "The JPA table catalog name to use for this entity.") final String catalog, @CliOption(key = "identifierField", mandatory = false, help = "The JPA identifier field name to use for this entity.") final String identifierField, @CliOption(key = "identifierType", mandatory = false, optionContext = "java-lang,project", unspecifiedDefaultValue = IDENTIFIER_DEFAULT_TYPE, specifiedDefaultValue = "java.lang.Long", help = "The data type that will be used for the JPA identifier field. " + "Default: `java.lang.Long`.") final JavaType identifierType, @CliOption(key = "inheritanceType", mandatory = false, help = "The JPA @Inheritance value (apply to base class)") final InheritanceType inheritanceType, @CliOption(key = "mappedSuperclass", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Apply @MappedSuperclass for this entity. " + "Default if option present: `true`; default if option not present: `false`.") final boolean mappedSuperclass, @CliOption(key = "serializable", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether the generated class should implement `java.io.Serializable`." + "Default if option present: `true`; default if option not present: `false`.") final boolean serializable, @CliOption(key = "permitReservedWords", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Indicates whether reserved words are ignored by Roo. " + "Default if option present: `true`; default if option not present: `false`.") final boolean permitReservedWords, @CliOption(key = "entityName", mandatory = false, help = "The name used to refer to the entity in queries.") final String entityName, @CliOption(key = "readOnly", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether the generated entity should be used for read operations only. " + "Default if option present: `true`; default if option not present `false`.") final boolean readOnly, @CliOption(key = "plural", mandatory = false, help = "Specify the plural of this new entity. If not provided, a calculated plural will be used by default.") String plural, @CliOption(key = "entityFormatExpression", mandatory = false, help = "The SpEL expression used to format the entity when showing it in presentation layer e.g. " + "`{#fieldA} {#fieldB}`. It adds the `value` attribute to `io.springlets.format.EntityFormat` " + "annotation.") String formatExpression, @CliOption(key = "entityFormatMessage", mandatory = false, help = "The message key used to obtain a localized SpEL expression to format the entity when " + "showing it in presentation layer. It adds the `message` attribute to " + "`io.springlets.format.EntityFormat` annotation and creates a message in all message bundles " + "with the provided key. Message value should be  modified by developer. This kind of format " + "has more priority that 'expression' format added with `--entityFormatExpression`.") String formatMessage, ShellContext shellContext) {
    Validate.isTrue(!identifierType.isPrimitive(), "Identifier type cannot be a primitive");
    // Check if exists other entity with the same name
    final String entityFilePathIdentifier = pathResolver.getCanonicalPath(name.getModule(), Path.SRC_MAIN_JAVA, name);
    if (fileManager.exists(entityFilePathIdentifier) && shellContext.isForce()) {
        fileManager.delete(entityFilePathIdentifier);
    } else if (fileManager.exists(entityFilePathIdentifier) && !shellContext.isForce()) {
        throw new IllegalArgumentException(String.format("Entity '%s' already exists and cannot be created. Try to use a " + "different entity name on --class parameter or use --force parameter to overwrite it.", name));
    }
    // Check valid value for --extends
    if (superclass == null && shellContext.getParameters().get("extends").equals("")) {
        throw new IllegalArgumentException("Option --extends must have a value when specified. Please, assign it a value.");
    }
    // ROO-3723: Add warning when using --extends with incompatible parameters
    if (superclass != null && !("java.lang.Object").equals(superclass.getFullyQualifiedTypeName()) && !shellContext.isForce()) {
        this.checkExtendsOverride(identifierColumn, identifierField, identifierStrategy, identifierType, sequenceName, versionColumn, versionField, versionType);
    }
    // and table name has not been specified
    if (!permitReservedWords && StringUtils.isBlank(table)) {
        // Use try to catch exception and show custom message for this situation
        try {
            ReservedWords.verifyReservedWordsNotPresent(name);
        } catch (IllegalStateException exception) {
            LOGGER.log(Level.INFO, "ERROR: You are trying to use a reserved word as entity name. You have the following options:\n" + "1. Change provided entity name.\n" + "2. Specify a valid table name using --table parameter.\n" + "3. Use parameter --permitReservedWords to force use of reserved words.\n");
            return;
        }
    } else if (!permitReservedWords && StringUtils.isNotBlank(table)) {
        // Use try to catch exception and show custom message for this situation
        try {
            ReservedWords.verifyReservedSqlKeywordsNotPresent(table);
        } catch (IllegalStateException exception) {
            LOGGER.log(Level.INFO, "ERROR: You are trying to use a SQL reserved word as table name. You have the following options:\n" + "1. Specify a valid table name using --table parameter.\n" + "2. Use parameter --permitReservedWords to force use of reserved words.\n");
            return;
        }
        // Use try to catch exception and show custom message for this situation
        try {
            ReservedWords.verifyReservedJavaKeywordsNotPresent(name);
        } catch (IllegalStateException exception) {
            LOGGER.log(Level.INFO, "ERROR: You are trying to use a Java reserved word as entity name. You have the following options:\n" + "1. Change provided entity name.\n" + "2. Use parameter --permitReservedWords to force use of reserved words.\n");
            return;
        }
    }
    // --permitReservedWords (see ROO-666)
    if (!BeanInfoUtils.isEntityReasonablyNamed(name)) {
        if (!permitReservedWords) {
            throw new IllegalArgumentException("Entity name rejected as conflicts with test execution defaults; please remove " + "'Test' and/or 'TestCase'");
        }
    }
    // Create entity's annotations
    final List<AnnotationMetadataBuilder> annotationBuilder = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder javaBeanAnnotationBuilder = new AnnotationMetadataBuilder(ROO_JAVA_BEAN);
    if (readOnly) {
        // ROO-3838: "ReadOnly" entities should not have setter methods.
        javaBeanAnnotationBuilder.addBooleanAttribute("settersByDefault", false);
    }
    annotationBuilder.add(javaBeanAnnotationBuilder);
    annotationBuilder.add(ROO_TO_STRING_BUILDER);
    annotationBuilder.add(getEntityAnnotationBuilder(table, schema, catalog, inheritanceType, mappedSuperclass, entityName, readOnly, formatExpression, formatMessage));
    // Add @RooEquals only if it's superclass is not an entity
    ClassOrInterfaceTypeDetails superclassCid = typeLocationService.getTypeDetails(superclass);
    if (superclassCid == null || superclassCid.getAnnotation(ROO_JPA_ENTITY) == null) {
        final AnnotationMetadataBuilder equalsAnnotationBuilder = ROO_EQUALS_BUILDER;
        equalsAnnotationBuilder.addBooleanAttribute("isJpaEntity", true);
        annotationBuilder.add(equalsAnnotationBuilder);
    }
    // Add @RooSerializable
    if (serializable) {
        annotationBuilder.add(ROO_SERIALIZABLE_BUILDER);
    }
    // ROO-3817: Including @RooPlural annotation if needed
    if (StringUtils.isNotEmpty(plural)) {
        AnnotationMetadataBuilder pluralAnnotation = new AnnotationMetadataBuilder(ROO_PLURAL);
        pluralAnnotation.addStringAttribute("value", plural);
        annotationBuilder.add(pluralAnnotation);
    }
    // Produce the entity itself
    jpaOperations.newEntity(name, createAbstract, superclass, implementsType, identifierField, identifierType, identifierColumn, sequenceName, identifierStrategy, versionField, versionType, versionColumn, inheritanceType, annotationBuilder);
    // only an embeddable class)
    if (!(identifierType.getPackage().getFullyQualifiedPackageName().startsWith("java."))) {
        jpaOperations.updateEmbeddableToIdentifier(identifierType, identifierField, identifierColumn);
    }
}
Also used : ArrayList(java.util.ArrayList) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder) CliCommand(org.springframework.roo.shell.CliCommand)

Example 12 with CliCommand

use of org.springframework.roo.shell.CliCommand in project spring-roo by spring-projects.

the class RepositoryJpaCommands method repository.

@CliCommand(value = "repository jpa", help = "Generates new Spring Data repository for specified entity or for all entities in generated " + "project.")
public void repository(@CliOption(key = "all", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Indicates if developer wants to generate repositories 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", mandatory = false, optionContext = PROJECT, help = "The domain entity this repository 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 = "interface", mandatory = true, help = "The java Spring Data repository to generate. 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 ~.domain.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 model:~.domain.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.") final JavaType interfaceType, @CliOption(key = "defaultReturnType", mandatory = false, help = "The default return type which this repository will have for all finders, including those" + "created by default. The default return type should be a Projection class associated to " + "the entity specified in `--entity` parameter. " + "Possible values are: any of the projections associated to the entity in `--entity` option. " + "This option is not available if domain entity specified in `--entity` parameter has no " + "associated Projections. " + "Default: the entity specified in the `entity` option.") JavaType defaultReturnType, @CliOption(key = "package", mandatory = false, help = "The package where repositories will be generated. In multi-module project you should " + "specify the module name before the package name. " + "Ex.: `--package model:org.springframework.roo` but, if module name is not present, " + "the Roo Shell focused module will be used. " + "This option is not available if `--all` option has not been specified. " + "Default value if not present: `~.repository` package, or 'repository:~.' if multi-module " + "project.") JavaPackage repositoriesPackage) {
    if (all) {
        // If user didn't specified some JavaPackage, use default repository package
        if (repositoriesPackage == null) {
            if (projectOperations.isMultimoduleProject()) {
                // Build default JavaPackage with module
                for (String moduleName : projectOperations.getModuleNames()) {
                    if (moduleName.equals("repository")) {
                        Pom module = projectOperations.getPomFromModuleName(moduleName);
                        repositoriesPackage = new JavaPackage(typeLocationService.getTopLevelPackageForModule(module), moduleName);
                        break;
                    }
                }
                // Check if repository found
                Validate.notNull(repositoriesPackage, "Couldn't find in project a default 'repository' " + "module. Please, use 'package' option to specify module and package.");
            } else {
                // Build default JavaPackage for single module
                repositoriesPackage = new JavaPackage(projectOperations.getFocusedTopLevelPackage().getFullyQualifiedPackageName().concat(".repository"), projectOperations.getFocusedModuleName());
            }
        }
        repositoryJpaOperations.generateAllRepositories(repositoriesPackage);
    } else {
        repositoryJpaOperations.addRepository(interfaceType, domainType, defaultReturnType, true);
    }
}
Also used : JavaPackage(org.springframework.roo.model.JavaPackage) Pom(org.springframework.roo.project.maven.Pom) CliCommand(org.springframework.roo.shell.CliCommand)

Example 13 with CliCommand

use of org.springframework.roo.shell.CliCommand in project spring-roo by spring-projects.

the class TailorCommands method tailorList.

/**
 * This method lists all available tailor configurations in the the Roo
 * shell.
 *
 * @param type
 */
@CliCommand(value = "tailor list", help = "List available tailor configurations.")
public void tailorList() {
    LOGGER.info("Available tailor configurations: ");
    final Map<String, TailorConfiguration> configs = configLocator.getAvailableConfigurations();
    final TailorConfiguration activeConfig = configLocator.getActiveTailorConfiguration();
    final Iterator<String> iterator = configs.keySet().iterator();
    while (iterator.hasNext()) {
        final String configName = iterator.next();
        final String isActive = activeConfig != null && configName.equals(activeConfig.getName()) ? " [ ACTIVE ] " : "";
        LOGGER.info("\to " + configName + isActive + " - " + configs.get(configName).getDescription());
    }
}
Also used : TailorConfiguration(org.springframework.roo.addon.tailor.config.TailorConfiguration) CliCommand(org.springframework.roo.shell.CliCommand)

Example 14 with CliCommand

use of org.springframework.roo.shell.CliCommand in project spring-roo by spring-projects.

the class MetadataCommands method metadataForModule.

@CliCommand(value = METADATA_FOR_MODULE_COMMAND, help = "Shows the ProjectMetadata for the indicated project module.")
public String metadataForModule(@CliOption(key = { "", "module" }, mandatory = false, optionContext = INCLUDE_CURRENT_MODULE, help = "The module for which to retrieve the metadata. " + "Default if option not present: the Roo Shell focused module.") final Pom pom) {
    final Pom targetPom = ObjectUtils.defaultIfNull(pom, projectOperations.getFocusedModule());
    if (targetPom == null) {
        return "This project has no modules";
    }
    final String projectMID = ProjectMetadata.getProjectIdentifier(targetPom.getModuleName());
    return metadataService.get(projectMID).toString();
}
Also used : Pom(org.springframework.roo.project.maven.Pom) CliCommand(org.springframework.roo.shell.CliCommand)

Example 15 with CliCommand

use of org.springframework.roo.shell.CliCommand in project spring-roo by spring-projects.

the class FieldCommands method insertField.

@CliCommand(value = "field other", help = "Inserts a private field into the specified file. User can choose a custom type for the field by specifying its fully qualified name.")
public void insertField(@CliOption(key = "fieldName", mandatory = true, help = "The name of the field.") final JavaSymbolName fieldName, @CliOption(key = "type", mandatory = true, help = "The Java type of this field.") final JavaType fieldType, @CliOption(key = "class", mandatory = true, unspecifiedDefaultValue = "*", optionContext = UPDATE_PROJECT, help = "The name of the class to generate the field. When working on a mono module " + "project, simply specify the name of the class in which the field will be included." + " If you consider it necessary, you can also specify the package. " + "Ex.: `--class ~.domain.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 model:~.domain.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 for this command when the focus is not set to one class. " + "Default if option not present: the class focused by Roo Shell.") final JavaType typeName, @CliOption(key = "column", mandatory = true, help = "The JPA `@Column` name." + "This option is mandatory if `spring.roo.jpa.require.schema-object-name` configuration" + " setting exists and it's `true`. " + "This option is only available for JPA entities and embeddable classes.") final String column, @CliOption(key = "transient", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Indicates to mark the field as transient, adding JPA `javax.persistence.Transient` " + "annotation. This marks the field as not persistent. " + "This option is only available for JPA entities and embeddable classes. " + "Default if option present:`true`. Default if option not present: `false`") final boolean transientModifier, @CliOption(key = "notNull", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether this value cannot be null. Adds `javax.validation.constraints.NotNull` " + "annotation to the field. " + "This option is not available if `--nullRequired` has already been specified. " + "Default if option present: `true`; default if option not present: `false`.") final boolean notNull, @CliOption(key = "nullRequired", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether this value must be null. Adds `javax.validation.constraints.Null` annotation to the field. " + "This option is not available if `--notNull` has already been specified. " + "Default if option present: `true`; default if option not present: `false`.") final boolean nullRequired, @CliOption(key = "comment", mandatory = false, help = "An optional comment for JavaDocs.") final String comment, @CliOption(key = "value", mandatory = false, help = "Inserts an optional Spring `org.springframework.beans.factory.annotation.Value` " + "annotation with the given content, typically used for expression-driven " + "dependency injection.") final String value, @CliOption(key = "permitReservedWords", mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Indicates whether reserved words are ignored by Roo. " + "Default if option present: `true`; default if option not present: `false`.") final boolean permitReservedWords, ShellContext shellContext) {
    final ClassOrInterfaceTypeDetails cid = typeLocationService.getTypeDetails(typeName);
    Validate.notNull(cid, "The type specified, '%s', doesn't exist", typeName);
    checkFieldExists(fieldName, shellContext, cid);
    getFieldCreatorProvider(typeName).createOtherField(cid, fieldType, fieldName, notNull, nullRequired, comment, column, permitReservedWords, transientModifier);
}
Also used : ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) CliCommand(org.springframework.roo.shell.CliCommand)

Aggregations

CliCommand (org.springframework.roo.shell.CliCommand)26 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)12 ArrayList (java.util.ArrayList)4 PGPPublicKeyRing (org.bouncycastle.openpgp.PGPPublicKeyRing)4 IOException (java.io.IOException)3 Pom (org.springframework.roo.project.maven.Pom)3 TemplateException (freemarker.template.TemplateException)2 Annotation (java.lang.annotation.Annotation)2 Method (java.lang.reflect.Method)2 HashMap (java.util.HashMap)2 TreeMap (java.util.TreeMap)2 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)2 ServiceReference (org.osgi.framework.ServiceReference)2 JavaPackage (org.springframework.roo.model.JavaPackage)2 CliOption (org.springframework.roo.shell.CliOption)2 CommandMarker (org.springframework.roo.shell.CommandMarker)2 MethodTarget (org.springframework.roo.shell.MethodTarget)2 Configuration (freemarker.template.Configuration)1 Template (freemarker.template.Template)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1