Search in sources :

Example 81 with JavaType

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

the class JspMetadataListener method get.

public MetadataItem get(final String jspMetadataId) {
    // Work out the MIDs of the other metadata we depend on
    // NB: The JavaType and Path are to the corresponding web scaffold
    // controller class
    final String webScaffoldMetadataKey = WebScaffoldMetadata.createIdentifier(JspMetadata.getJavaType(jspMetadataId), JspMetadata.getPath(jspMetadataId));
    final WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) getMetadataService().get(webScaffoldMetadataKey);
    if (webScaffoldMetadata == null || !webScaffoldMetadata.isValid()) {
        // to manage any JSPs at this time
        return null;
    }
    final JavaType formBackingType = webScaffoldMetadata.getAnnotationValues().getFormBackingObject();
    final MemberDetails memberDetails = getWebMetadataService().getMemberDetails(formBackingType);
    final JavaTypeMetadataDetails formBackingTypeMetadataDetails = getWebMetadataService().getJavaTypeMetadataDetails(formBackingType, memberDetails, jspMetadataId);
    Validate.notNull(formBackingTypeMetadataDetails, "Unable to obtain metadata for type %s", formBackingType.getFullyQualifiedTypeName());
    formBackingObjectTypesToLocalMids.put(formBackingType, jspMetadataId);
    final SortedMap<JavaType, JavaTypeMetadataDetails> relatedTypeMd = getWebMetadataService().getRelatedApplicationTypeMetadata(formBackingType, memberDetails, jspMetadataId);
    final JavaTypeMetadataDetails formbackingTypeMetadata = relatedTypeMd.get(formBackingType);
    Validate.notNull(formbackingTypeMetadata, "Form backing type metadata required");
    final JavaTypePersistenceMetadataDetails formBackingTypePersistenceMetadata = formbackingTypeMetadata.getPersistenceDetails();
    if (formBackingTypePersistenceMetadata == null) {
        return null;
    }
    final ClassOrInterfaceTypeDetails formBackingTypeDetails = getTypeLocationService().getTypeDetails(formBackingType);
    final LogicalPath formBackingTypePath = PhysicalTypeIdentifier.getPath(formBackingTypeDetails.getDeclaredByMetadataId());
    getMetadataDependencyRegistry().registerDependency(PhysicalTypeIdentifier.createIdentifier(formBackingType, formBackingTypePath), JspMetadata.createIdentifier(formBackingType, formBackingTypePath));
    final LogicalPath path = JspMetadata.getPath(jspMetadataId);
    // Install web artifacts only if Spring MVC config is missing
    // TODO: Remove this call when 'controller' commands are gone
    final PathResolver pathResolver = getProjectOperations().getPathResolver();
    final LogicalPath webappPath = LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, path.getModule());
    if (!getFileManager().exists(pathResolver.getIdentifier(webappPath, WEB_INF_VIEWS))) {
        getJspOperations().installCommonViewArtefacts(path.getModule());
    }
    installImage(webappPath, "images/show.png");
    if (webScaffoldMetadata.getAnnotationValues().isUpdate()) {
        installImage(webappPath, "images/update.png");
    }
    if (webScaffoldMetadata.getAnnotationValues().isDelete()) {
        installImage(webappPath, "images/delete.png");
    }
    final List<FieldMetadata> eligibleFields = getWebMetadataService().getScaffoldEligibleFieldMetadata(formBackingType, memberDetails, jspMetadataId);
    if (eligibleFields.isEmpty() && formBackingTypePersistenceMetadata.getRooIdentifierFields().isEmpty()) {
        return null;
    }
    final JspViewManager viewManager = new JspViewManager(eligibleFields, webScaffoldMetadata.getAnnotationValues(), relatedTypeMd);
    String controllerPath = webScaffoldMetadata.getAnnotationValues().getPath();
    if (controllerPath.startsWith("/")) {
        controllerPath = controllerPath.substring(1);
    }
    // Make the holding directory for this controller
    final String destinationDirectory = pathResolver.getIdentifier(webappPath, WEB_INF_VIEWS + controllerPath);
    if (!getFileManager().exists(destinationDirectory)) {
        getFileManager().createDirectory(destinationDirectory);
    } else {
        final File file = new File(destinationDirectory);
        Validate.isTrue(file.isDirectory(), "%s is a file, when a directory was expected", destinationDirectory);
    }
    // By now we have a directory to put the JSPs inside
    final String listPath1 = destinationDirectory + "/list.jspx";
    getXmlRoundTripFileManager().writeToDiskIfNecessary(listPath1, viewManager.getListDocument());
    getTilesOperations().addViewDefinition(controllerPath, webappPath, controllerPath + "/" + "list", TilesOperations.DEFAULT_TEMPLATE, WEB_INF_VIEWS + controllerPath + "/list.jspx");
    final String showPath = destinationDirectory + "/show.jspx";
    getXmlRoundTripFileManager().writeToDiskIfNecessary(showPath, viewManager.getShowDocument());
    getTilesOperations().addViewDefinition(controllerPath, webappPath, controllerPath + "/" + "show", TilesOperations.DEFAULT_TEMPLATE, WEB_INF_VIEWS + controllerPath + "/show.jspx");
    final Map<String, String> properties = new LinkedHashMap<String, String>();
    final JavaSymbolName categoryName = new JavaSymbolName(formBackingType.getSimpleTypeName());
    properties.put("menu_category_" + categoryName.getSymbolName().toLowerCase() + "_label", categoryName.getReadableSymbolName());
    final JavaSymbolName newMenuItemId = new JavaSymbolName("new");
    properties.put("menu_item_" + categoryName.getSymbolName().toLowerCase() + "_" + newMenuItemId.getSymbolName().toLowerCase() + "_label", new JavaSymbolName(formBackingType.getSimpleTypeName()).getReadableSymbolName());
    if (webScaffoldMetadata.getAnnotationValues().isCreate()) {
        final String listPath = destinationDirectory + "/create.jspx";
        getXmlRoundTripFileManager().writeToDiskIfNecessary(listPath, viewManager.getCreateDocument());
        // Add 'create new' menu item
        getMenuOperations().addMenuItem(categoryName, newMenuItemId, "global_menu_new", "/" + controllerPath + "?form", MenuOperations.DEFAULT_MENU_ITEM_PREFIX, webappPath);
        getTilesOperations().addViewDefinition(controllerPath, webappPath, controllerPath + "/" + "create", TilesOperations.DEFAULT_TEMPLATE, WEB_INF_VIEWS + controllerPath + "/create.jspx");
    } else {
        getMenuOperations().cleanUpMenuItem(categoryName, new JavaSymbolName("new"), MenuOperations.DEFAULT_MENU_ITEM_PREFIX, webappPath);
        getTilesOperations().removeViewDefinition(controllerPath + "/" + "create", controllerPath, webappPath);
    }
    if (webScaffoldMetadata.getAnnotationValues().isUpdate()) {
        final String listPath = destinationDirectory + "/update.jspx";
        getXmlRoundTripFileManager().writeToDiskIfNecessary(listPath, viewManager.getUpdateDocument());
        getTilesOperations().addViewDefinition(controllerPath, webappPath, controllerPath + "/" + "update", TilesOperations.DEFAULT_TEMPLATE, WEB_INF_VIEWS + controllerPath + "/update.jspx");
    } else {
        getTilesOperations().removeViewDefinition(controllerPath + "/" + "update", controllerPath, webappPath);
    }
    // Setup labels for i18n support
    final String resourceId = XmlUtils.convertId("label." + formBackingType.getFullyQualifiedTypeName().toLowerCase());
    properties.put(resourceId, new JavaSymbolName(formBackingType.getSimpleTypeName()).getReadableSymbolName());
    final String pluralResourceId = XmlUtils.convertId(resourceId + ".plural");
    final String plural = formBackingTypeMetadataDetails.getPlural();
    properties.put(pluralResourceId, new JavaSymbolName(plural).getReadableSymbolName());
    final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataDetails = formBackingTypeMetadataDetails.getPersistenceDetails();
    Validate.notNull(javaTypePersistenceMetadataDetails, "Unable to determine persistence metadata for type %s", formBackingType.getFullyQualifiedTypeName());
    if (!javaTypePersistenceMetadataDetails.getRooIdentifierFields().isEmpty()) {
        for (final FieldMetadata idField : javaTypePersistenceMetadataDetails.getRooIdentifierFields()) {
            properties.put(XmlUtils.convertId(resourceId + "." + javaTypePersistenceMetadataDetails.getIdentifierField().getFieldName().getSymbolName() + "." + idField.getFieldName().getSymbolName().toLowerCase()), idField.getFieldName().getReadableSymbolName());
        }
    }
    // If no auto generated value for id, put name in i18n
    if (javaTypePersistenceMetadataDetails.getIdentifierField().getAnnotation(JpaJavaType.GENERATED_VALUE) == null) {
        properties.put(XmlUtils.convertId(resourceId + "." + javaTypePersistenceMetadataDetails.getIdentifierField().getFieldName().getSymbolName().toLowerCase()), javaTypePersistenceMetadataDetails.getIdentifierField().getFieldName().getReadableSymbolName());
    }
    for (final MethodMetadata method : memberDetails.getMethods()) {
        if (!BeanInfoUtils.isAccessorMethod(method)) {
            continue;
        }
        final FieldMetadata field = BeanInfoUtils.getFieldForJavaBeanMethod(memberDetails, method);
        if (field == null) {
            continue;
        }
        final JavaSymbolName fieldName = field.getFieldName();
        final String fieldResourceId = XmlUtils.convertId(resourceId + "." + fieldName.getSymbolName().toLowerCase());
        if (getTypeLocationService().isInProject(method.getReturnType()) && getWebMetadataService().isRooIdentifier(method.getReturnType(), getWebMetadataService().getMemberDetails(method.getReturnType()))) {
            final JavaTypePersistenceMetadataDetails typePersistenceMetadataDetails = getWebMetadataService().getJavaTypePersistenceMetadataDetails(method.getReturnType(), getWebMetadataService().getMemberDetails(method.getReturnType()), jspMetadataId);
            if (typePersistenceMetadataDetails != null) {
                for (final FieldMetadata f : typePersistenceMetadataDetails.getRooIdentifierFields()) {
                    final String sb = f.getFieldName().getReadableSymbolName();
                    properties.put(XmlUtils.convertId(resourceId + "." + javaTypePersistenceMetadataDetails.getIdentifierField().getFieldName().getSymbolName() + "." + f.getFieldName().getSymbolName().toLowerCase()), StringUtils.isNotBlank(sb) ? sb : fieldName.getSymbolName());
                }
            }
        } else if (!method.getMethodName().equals(javaTypePersistenceMetadataDetails.getIdentifierAccessorMethod().getMethodName()) || javaTypePersistenceMetadataDetails.getVersionAccessorMethod() != null && !method.getMethodName().equals(javaTypePersistenceMetadataDetails.getVersionAccessorMethod().getMethodName())) {
            final String sb = fieldName.getReadableSymbolName();
            properties.put(fieldResourceId, StringUtils.isNotBlank(sb) ? sb : fieldName.getSymbolName());
        }
    }
    if (javaTypePersistenceMetadataDetails.getFindAllMethod() != null) {
        // Add 'list all' menu item
        final JavaSymbolName listMenuItemId = new JavaSymbolName("list");
        getMenuOperations().addMenuItem(categoryName, listMenuItemId, "global_menu_list", "/" + controllerPath + "?page=1&size=${empty param.size ? 10 : param.size}", MenuOperations.DEFAULT_MENU_ITEM_PREFIX, webappPath);
        properties.put("menu_item_" + categoryName.getSymbolName().toLowerCase() + "_" + listMenuItemId.getSymbolName().toLowerCase() + "_label", new JavaSymbolName(plural).getReadableSymbolName());
    } else {
        getMenuOperations().cleanUpMenuItem(categoryName, new JavaSymbolName("list"), MenuOperations.DEFAULT_MENU_ITEM_PREFIX, webappPath);
    }
    final String controllerPhysicalTypeId = PhysicalTypeIdentifier.createIdentifier(JspMetadata.getJavaType(jspMetadataId), JspMetadata.getPath(jspMetadataId));
    final PhysicalTypeMetadata controllerPhysicalTypeMd = (PhysicalTypeMetadata) getMetadataService().get(controllerPhysicalTypeId);
    if (controllerPhysicalTypeMd == null) {
        return null;
    }
    final MemberHoldingTypeDetails mhtd = controllerPhysicalTypeMd.getMemberHoldingTypeDetails();
    if (mhtd == null) {
        return null;
    }
    final List<String> allowedMenuItems = new ArrayList<String>();
    if (MemberFindingUtils.getAnnotationOfType(mhtd.getAnnotations(), RooJavaType.ROO_WEB_FINDER) != null) {
        // This controller is annotated with @RooWebFinder
        final Set<FinderMetadataDetails> finderMethodsDetails = getWebMetadataService().getDynamicFinderMethodsAndFields(formBackingType, memberDetails, jspMetadataId);
        if (finderMethodsDetails == null) {
            return null;
        }
        for (final FinderMetadataDetails finderDetails : finderMethodsDetails) {
            final String finderName = finderDetails.getFinderMethodMetadata().getMethodName().getSymbolName();
            final String listPath = destinationDirectory + "/" + finderName + ".jspx";
            // long (see ROO-1027)
            if (listPath.length() > 244) {
                continue;
            }
            getXmlRoundTripFileManager().writeToDiskIfNecessary(listPath, viewManager.getFinderDocument(finderDetails));
            final JavaSymbolName finderLabel = new JavaSymbolName(finderName.replace("find" + plural + "By", ""));
            // Add 'Find by' menu item
            getMenuOperations().addMenuItem(categoryName, finderLabel, "global_menu_find", "/" + controllerPath + "?find=" + finderName.replace("find" + plural, "") + "&form" + "&page=1&size=${empty param.size ? 10 : param.size}", MenuOperations.FINDER_MENU_ITEM_PREFIX, webappPath);
            properties.put("menu_item_" + categoryName.getSymbolName().toLowerCase() + "_" + finderLabel.getSymbolName().toLowerCase() + "_label", finderLabel.getReadableSymbolName());
            allowedMenuItems.add(MenuOperations.FINDER_MENU_ITEM_PREFIX + categoryName.getSymbolName().toLowerCase() + "_" + finderLabel.getSymbolName().toLowerCase());
            for (final JavaSymbolName paramName : finderDetails.getFinderMethodMetadata().getParameterNames()) {
                properties.put(XmlUtils.convertId(resourceId + "." + paramName.getSymbolName().toLowerCase()), paramName.getReadableSymbolName());
            }
            getTilesOperations().addViewDefinition(controllerPath, webappPath, controllerPath + "/" + finderName, TilesOperations.DEFAULT_TEMPLATE, WEB_INF_VIEWS + controllerPath + "/" + finderName + ".jspx");
        }
    }
    getMenuOperations().cleanUpFinderMenuItems(categoryName, allowedMenuItems, webappPath);
    return new JspMetadata(jspMetadataId, webScaffoldMetadata);
}
Also used : JavaTypePersistenceMetadataDetails(org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypePersistenceMetadataDetails) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) WebScaffoldMetadata(org.springframework.roo.addon.web.mvc.controller.addon.scaffold.WebScaffoldMetadata) JavaTypeMetadataDetails(org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypeMetadataDetails) LogicalPath(org.springframework.roo.project.LogicalPath) PathResolver(org.springframework.roo.project.PathResolver) FinderMetadataDetails(org.springframework.roo.addon.web.mvc.controller.addon.details.FinderMetadataDetails) RooJavaType(org.springframework.roo.model.RooJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) PhysicalTypeMetadata(org.springframework.roo.classpath.PhysicalTypeMetadata) MemberHoldingTypeDetails(org.springframework.roo.classpath.details.MemberHoldingTypeDetails) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) File(java.io.File)

Example 82 with JavaType

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

the class ThymeleafViewGeneratorServiceImpl method createDetailEntityItem.

@Override
protected DetailEntityItem createDetailEntityItem(ThymeleafMetadata detailController, MemberDetails entityMembers, JpaEntityMetadata entityMetadata, String entityName, ViewContext<ThymeleafMetadata> ctx, String detailSuffix, EntityItem rootEntity) {
    JavaType detailItemController;
    JavaType detailCollectionController;
    final ControllerType type = detailController.getControllerMetadata().getType();
    if (type == ControllerType.DETAIL) {
        detailCollectionController = detailController.getDestination();
        detailItemController = detailController.getDetailItemController();
    } else {
        detailCollectionController = detailController.getDetailCollectionController();
        detailItemController = detailController.getDestination();
    }
    JavaType itemController = detailController.getItemController();
    JavaType relatedCollectionController = detailController.getRelatedCollectionController();
    JavaType relatedItemController = detailController.getRelatedItemController();
    DetailEntityItem item = super.createDetailEntityItem(detailController, entityMembers, entityMetadata, entityName, ctx, detailSuffix, rootEntity);
    item.addConfigurationElement("mvcDetailControllerName", detailController.getMvcControllerName());
    item.addConfigurationElement("mvcDetailItemControllerName", detailItemController.getSimpleTypeName());
    item.addConfigurationElement("mvcDetailCollectionControllerName", detailCollectionController.getSimpleTypeName());
    if (relatedItemController != null) {
        item.addConfigurationElement("select2MethodName", ThymeleafMetadata.SELECT2_METHOD_NAME);
        item.addConfigurationElement("select2ControllerName", relatedCollectionController.getSimpleTypeName());
    }
    return item;
}
Also used : RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) DetailEntityItem(org.springframework.roo.addon.web.mvc.views.components.DetailEntityItem) ControllerType(org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType)

Example 83 with JavaType

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

the class LinkFactoryMetadata method getToUriMethod.

/**
 * Generates a `toUri` method which generates URI's for the *Collection*
 * controller methods which are called from views.
 *
 * @param finderName
 * @param serviceFinderMethod
 * @return
 */
private MethodMetadata getToUriMethod() {
    // Define methodName
    final JavaSymbolName toUriMethodName = TO_URI_METHOD_NAME;
    // Define method argument types
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(stringArgument);
    parameterTypes.add(objectArrayArgument);
    parameterTypes.add(mapStringObjectArgument);
    // Return method if already exists
    MethodMetadata existingMethod = getGovernorMethod(toUriMethodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Define method argument names
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(METHOD_NAME_ARGUMENT_NAME);
    parameterNames.add(PARAMETERS_ARGUMENT_NAME);
    parameterNames.add(PATH_VARIABLES_ARGUMENT_NAME);
    // Generate body
    final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Include a conditional for every method
    for (MethodMetadata method : this.controllerMethods) {
        // Getting methodName
        String methodName = method.getMethodName().getSymbolName();
        // Getting methodParams
        List<String> methodParamsToNull = new ArrayList<String>();
        for (AnnotatedJavaType paramType : method.getParameterTypes()) {
            JavaType javaType = paramType.getJavaType();
            if (javaType.isPrimitive() && !javaType.isArray()) {
                if (JavaType.BOOLEAN_PRIMITIVE.equals(javaType)) {
                    methodParamsToNull.add("false");
                } else if (JavaType.INT_PRIMITIVE.equals(javaType)) {
                    methodParamsToNull.add("0");
                } else if (JavaType.LONG_PRIMITIVE.equals(javaType)) {
                    methodParamsToNull.add("0l");
                } else if (JavaType.FLOAT_PRIMITIVE.equals(javaType)) {
                    methodParamsToNull.add("0.0f");
                } else if (JavaType.DOUBLE_PRIMITIVE.equals(javaType)) {
                    methodParamsToNull.add("0.0");
                }
            } else {
                // Include a null declaration for every parameter
                methodParamsToNull.add("null");
            }
        }
        // if (METHOD_NAME_ARGUMENT_NAME.equals(methodNameConstant)) {
        bodyBuilder.appendFormalLine("if (%s.equals(%s)) {", METHOD_NAME_ARGUMENT_NAME, getConstantForMethodName(methodName).getFieldName());
        bodyBuilder.indent();
        // return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(getControllerClass()).list(null)).build();
        bodyBuilder.appendFormalLine("return %1$s.fromMethodCall(%1$s.on(%2$s()).%3$s(%4$s)).buildAndExpand(%5$s);", getNameOfJavaType(SpringletsJavaType.SPRINGLETS_MVC_URI_COMPONENTS_BUILDER), this.getControllerClassMethod.getMethodName(), methodName, StringUtils.join(methodParamsToNull, ", "), PATH_VARIABLES_ARGUMENT_NAME);
        bodyBuilder.indentRemove();
        // }
        bodyBuilder.appendFormalLine("}");
    }
    // throw new IllegalArgumentException("Invalid method name: " + METHOD_NAME_ARGUMENT_NAME);
    bodyBuilder.appendFormalLine("throw new IllegalArgumentException(\"Invalid method name: \" + %s);", METHOD_NAME_ARGUMENT_NAME);
    // Build method builder
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, toUriMethodName, SpringJavaType.URI_COMPONENTS, parameterTypes, parameterNames, bodyBuilder);
    return methodBuilder.build();
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JdkJavaType(org.springframework.roo.model.JdkJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)

Example 84 with JavaType

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

the class AbstractViewGenerationService method addMenu.

@Override
public void addMenu(String moduleName, ViewContext<T> ctx) {
    Map<String, MenuEntry> mapMenuEntries = new TreeMap<String, MenuEntry>();
    Set<ClassOrInterfaceTypeDetails> existingControllers = new HashSet<ClassOrInterfaceTypeDetails>();
    existingControllers.addAll(getControllerLocator().getControllers(null, ControllerType.COLLECTION, getType()));
    existingControllers.addAll(getControllerLocator().getControllers(null, ControllerType.SEARCH, getType()));
    Iterator<ClassOrInterfaceTypeDetails> it = existingControllers.iterator();
    while (it.hasNext()) {
        // Getting controller and its information
        ClassOrInterfaceTypeDetails controller = it.next();
        ControllerAnnotationValues controllerValues = new ControllerAnnotationValues(controller);
        JavaType entity = controllerValues.getEntity();
        // Obtain the entityMetadata
        JpaEntityMetadata entityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(getTypeLocationService().getTypeDetails(entity)));
        boolean isReadOnly = false;
        if (entityMetadata != null && entityMetadata.isReadOnly()) {
            isReadOnly = true;
        }
        // Get finders for each controller
        AnnotationMetadata controllerSearchAnnotation = controller.getAnnotation(RooJavaType.ROO_SEARCH);
        Map<String, String> finderNamesAndPaths = new HashMap<String, String>();
        if (controllerSearchAnnotation != null && controllerSearchAnnotation.getAttribute("finders") != null) {
            List<?> finders = (List<?>) controllerSearchAnnotation.getAttribute("finders").getValue();
            Iterator<?> iterator = finders.iterator();
            while (iterator.hasNext()) {
                StringAttributeValue attributeValue = (StringAttributeValue) iterator.next();
                String finderName = attributeValue.getValue();
                // Build URL path to get data
                String finderPath = "";
                if (StringUtils.startsWith(finderName, "count")) {
                    finderPath = StringUtils.removeStart(finderName, "count");
                } else if (StringUtils.startsWith(finderName, "find")) {
                    finderPath = StringUtils.removeStart(finderName, "find");
                } else if (StringUtils.startsWith(finderName, "query")) {
                    finderPath = StringUtils.removeStart(finderName, "query");
                } else if (StringUtils.startsWith(finderName, "read")) {
                    finderPath = StringUtils.removeStart(finderName, "read");
                } else {
                    finderPath = finderName;
                }
                finderPath = String.format("search/%s/search-form", StringUtils.uncapitalize(finderPath));
                finderNamesAndPaths.put(finderName, finderPath);
            }
        }
        // Getting pathPrefix
        String pathPrefix = StringUtils.defaultString(controllerValues.getPathPrefix(), "");
        // Generate path
        String path = getControllerOperations().getBaseUrlForController(controller);
        if (controllerSearchAnnotation != null) {
            // Prevent that /search will be included in every menu entry
            // The /search is already included in the step before only for
            // finder entries
            path = path.replace("/search", "");
        }
        // Create new menuEntry element for controller
        String keyThatRepresentsEntry = pathPrefix.concat(entity.getSimpleTypeName());
        // Add new menu entry to menuEntries list if doesn't exist
        MenuEntry menuEntry = null;
        if (controllerValues.getType() == ControllerType.SEARCH) {
            // Only add finder entry
            menuEntry = createMenuEntry(entity.getSimpleTypeName(), path, pathPrefix, FieldItem.buildLabel(entity.getSimpleTypeName(), ""), FieldItem.buildLabel(entity.getSimpleTypeName(), "plural"), finderNamesAndPaths, false, false, false);
        } else {
            // Add default menu entries
            menuEntry = createMenuEntry(entity.getSimpleTypeName(), path, pathPrefix, FieldItem.buildLabel(entity.getSimpleTypeName(), ""), FieldItem.buildLabel(entity.getSimpleTypeName(), "plural"), finderNamesAndPaths, false, true, isReadOnly);
        }
        if (mapMenuEntries.containsKey(keyThatRepresentsEntry)) {
            MenuEntry menuEntryInserted = mapMenuEntries.get(keyThatRepresentsEntry);
            if (menuEntryInserted.getFinderNamesAndPaths().isEmpty() && !menuEntry.getFinderNamesAndPaths().isEmpty()) {
                menuEntryInserted.setFinderNamesAndPaths(menuEntry.getFinderNamesAndPaths());
            }
            // Check the 'addDefaultEntries' attribute and add it if needed
            if (!menuEntryInserted.isAddDefaultEntries() && menuEntry.isAddDefaultEntries()) {
                menuEntryInserted.setAddDefaultEntries(menuEntry.isAddDefaultEntries());
            }
        } else {
            mapMenuEntries.put(keyThatRepresentsEntry, menuEntry);
        }
    }
    // Also, check web flow views in the views folder
    String viewsFolder = getViewsFolder(moduleName);
    List<String> webFlowViews = getWebFlowViewsFromDir(viewsFolder, null);
    // After obtain the webFlow views, add them to the menu
    for (String webFlowView : webFlowViews) {
        // Creating the menu entry
        MenuEntry menuEntry = createMenuEntry(webFlowView, webFlowView, "", FieldItem.buildLabel(webFlowView, ""), FieldItem.buildLabel(webFlowView, "plural"), null, true, false, false);
        mapMenuEntries.put(webFlowView, menuEntry);
    }
    // First of all, generate a list of MenuEntries based on existing
    // controllers
    List<MenuEntry> menuEntries = new ArrayList<MenuEntry>(mapMenuEntries.values());
    // Generate ids to search when merge new and existing doc
    List<String> requiredIds = new ArrayList<String>();
    for (MenuEntry entry : menuEntries) {
        requiredIds.add(entry.getPathPrefix().concat(entry.getEntityName()).concat("Entry"));
    }
    // Process elements to generate
    DOC newDoc = null;
    // Getting new viewName
    String viewName = getFragmentsFolder(moduleName).concat("/menu").concat(getViewsExtension());
    // Check if new view to generate exists or not
    if (existsFile(viewName)) {
        DOC existingDoc = loadExistingDoc(viewName);
        if (!isUserManagedDocument(existingDoc)) {
            newDoc = mergeMenu("fragments/menu", existingDoc, ctx, menuEntries);
        }
    } else {
        ctx.addExtraParameter("menuEntries", menuEntries);
        newDoc = process("fragments/menu", ctx);
    }
    // Write newDoc on disk
    writeDoc(newDoc, viewName);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) Jsr303JavaType(org.springframework.roo.model.Jsr303JavaType) JdkJavaType(org.springframework.roo.model.JdkJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) MenuEntry(org.springframework.roo.addon.web.mvc.views.components.MenuEntry) ControllerAnnotationValues(org.springframework.roo.addon.web.mvc.controller.addon.ControllerAnnotationValues) List(java.util.List) ArrayList(java.util.ArrayList) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) StringAttributeValue(org.springframework.roo.classpath.details.annotations.StringAttributeValue) HashSet(java.util.HashSet)

Example 85 with JavaType

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

the class AbstractViewGenerationService method addListDeleteModalBatchView.

@Override
public void addListDeleteModalBatchView(String moduleName, JpaEntityMetadata entityMetadata, MemberDetails entity, ViewContext<T> ctx) {
    // Get the repository related with the entity to check the default return type
    RepositoryJpaMetadata repository = getRepositoryJpaLocator().getFirstRepositoryMetadata(entityMetadata.getAnnotatedEntity());
    // All views should have a repository
    Validate.notNull(repository, "ERROR: The provided entity should have an associated repository to be able " + "to generate the list view.");
    // Obtain the defaultReturnType
    JavaType defaultReturnType = repository.getDefaultReturnType();
    // The defaultReturnType must not be null. If it's not an entity projection,
    // it must be an entity
    Validate.notNull(defaultReturnType, "ERROR: The repository associated to the provided entity should define a defaultReturnType");
    // Obtain details of the provided defaultReturnType. If not exists as type, show an error
    ClassOrInterfaceTypeDetails defaultReturnTypeCid = getTypeLocationService().getTypeDetails(defaultReturnType);
    Validate.notNull(defaultReturnTypeCid, "ERROR: The provided defaultReturnType is not a valid type");
    MemberDetails defaultReturnTypeDetails = getMemberDetailsScanner().getMemberDetails(getClass().toString(), defaultReturnTypeCid);
    Validate.notNull(defaultReturnTypeDetails, "ERROR: Is not possible to obtain any detail from the " + "provided defaultReturnType.");
    List<FieldMetadata> defaultReturnTypeFields = defaultReturnTypeDetails.getFields();
    // all the entity fields will be used
    if (defaultReturnTypeFields.isEmpty()) {
        defaultReturnTypeFields = entity.getFields();
    }
    // Getting entity fields that should be included on view
    List<FieldMetadata> entityFields = getPersistentFields(defaultReturnTypeFields);
    List<FieldItem> fields = getFieldViewItems(entityMetadata, entityFields, ctx.getEntityName(), true, ctx, TABLE_SUFFIX);
    // Process elements to generate
    DOC newDoc = null;
    // Getting new viewName
    String viewName = getViewsFolder(moduleName).concat(ctx.getControllerPath()).concat("/").concat("/listDeleteModalBatch").concat(getViewsExtension());
    EntityItem entityItem = createEntityItem(entityMetadata, ctx, TABLE_SUFFIX);
    // Check if new view to generate exists or not
    if (existsFile(viewName)) {
        DOC existingDoc = loadExistingDoc(viewName);
        if (!isUserManagedDocument(existingDoc)) {
            newDoc = mergeListDeleteModalBatchView("listDeleteModalBatch", loadExistingDoc(viewName), ctx, entityItem, fields);
        }
    } else {
        ctx.addExtraParameter("entity", entityItem);
        ctx.addExtraParameter("fields", fields);
        newDoc = process("listDeleteModalBatch", ctx);
    }
    // Write newDoc on disk
    writeDoc(newDoc, viewName);
}
Also used : RepositoryJpaMetadata(org.springframework.roo.addon.layers.repository.jpa.addon.RepositoryJpaMetadata) Jsr303JavaType(org.springframework.roo.model.Jsr303JavaType) JdkJavaType(org.springframework.roo.model.JdkJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) FieldItem(org.springframework.roo.addon.web.mvc.views.components.FieldItem) EntityItem(org.springframework.roo.addon.web.mvc.views.components.EntityItem) DetailEntityItem(org.springframework.roo.addon.web.mvc.views.components.DetailEntityItem)

Aggregations

JavaType (org.springframework.roo.model.JavaType)411 RooJavaType (org.springframework.roo.model.RooJavaType)212 ArrayList (java.util.ArrayList)142 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)133 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)129 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)114 JdkJavaType (org.springframework.roo.model.JdkJavaType)110 SpringJavaType (org.springframework.roo.model.SpringJavaType)101 JpaJavaType (org.springframework.roo.model.JpaJavaType)83 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)78 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)76 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)72 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)70 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)65 LogicalPath (org.springframework.roo.project.LogicalPath)62 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)60 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)59 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)38 MemberDetails (org.springframework.roo.classpath.scanner.MemberDetails)35 ClassOrInterfaceTypeDetailsBuilder (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder)30