Search in sources :

Example 6 with XmlElementBuilder

use of org.springframework.roo.support.util.XmlElementBuilder in project spring-roo by spring-projects.

the class HelpServiceImpl method helpReferenceGuide.

/**
 * {@inheritDoc}
 *
 * TODO: Refactor this method to use the Freemarker template engine. See {@link #obtainHelp(String)}.
 */
public void helpReferenceGuide() {
    synchronized (mutex) {
        // Get all Services implement CommandMarker interface
        try {
            ServiceReference<?>[] references = this.context.getAllServiceReferences(CommandMarker.class.getName(), null);
            for (ServiceReference<?> ref : references) {
                CommandMarker command = (CommandMarker) this.context.getService(ref);
                if (!commands.contains(command)) {
                    add(command);
                }
            }
        } catch (InvalidSyntaxException e) {
            LOGGER.warning("Cannot load CommandMarker on SimpleParser.");
        }
        final File f = new File(".");
        final File[] existing = f.listFiles(new FileFilter() {

            public boolean accept(final File pathname) {
                return pathname.getName().startsWith("appendix_");
            }
        });
        for (final File e : existing) {
            e.delete();
        }
        // Compute the sections we'll be outputting, and get them into a
        // nice order
        final SortedMap<String, Object> sections = new TreeMap<String, Object>(COMPARATOR);
        next_target: for (final Object target : commands) {
            final Method[] methods = target.getClass().getMethods();
            for (final Method m : methods) {
                final CliCommand cmd = m.getAnnotation(CliCommand.class);
                if (cmd != null) {
                    String sectionName = target.getClass().getSimpleName();
                    final Pattern p = Pattern.compile("[A-Z][^A-Z]*");
                    final Matcher matcher = p.matcher(sectionName);
                    final StringBuilder string = new StringBuilder();
                    while (matcher.find()) {
                        string.append(matcher.group()).append(" ");
                    }
                    sectionName = string.toString().trim();
                    if (sections.containsKey(sectionName)) {
                        throw new IllegalStateException("Section name '" + sectionName + "' not unique");
                    }
                    sections.put(sectionName, target);
                    continue next_target;
                }
            }
        }
        // Build each section of the appendix
        final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
        final Document document = builder.newDocument();
        final List<Element> builtSections = new ArrayList<Element>();
        for (final Entry<String, Object> entry : sections.entrySet()) {
            final String section = entry.getKey();
            final Object target = entry.getValue();
            final SortedMap<String, Element> individualCommands = new TreeMap<String, Element>(COMPARATOR);
            final Method[] methods = target.getClass().getMethods();
            for (final Method m : methods) {
                final CliCommand cmd = m.getAnnotation(CliCommand.class);
                if (cmd != null) {
                    final StringBuilder cmdSyntax = new StringBuilder();
                    cmdSyntax.append(cmd.value()[0]);
                    // Build the syntax list
                    // Store the order options appear
                    final List<String> optionKeys = new ArrayList<String>();
                    // key: option key, value: help text
                    final Map<String, String> optionDetails = new HashMap<String, String>();
                    for (final Annotation[] ann : m.getParameterAnnotations()) {
                        for (final Annotation a : ann) {
                            if (a instanceof CliOption) {
                                final CliOption option = (CliOption) a;
                                // Figure out which key we want to use (use
                                // first non-empty string, or make it
                                // "(default)" if needed)
                                String key = option.key()[0];
                                if ("".equals(key)) {
                                    for (final String otherKey : option.key()) {
                                        if (!"".equals(otherKey)) {
                                            key = otherKey;
                                            break;
                                        }
                                    }
                                    if ("".equals(key)) {
                                        key = "[default]";
                                    }
                                }
                                final StringBuilder help = new StringBuilder();
                                if ("".equals(option.help())) {
                                    help.append("No help available");
                                } else {
                                    help.append(option.help());
                                }
                                if (option.specifiedDefaultValue().equals(option.unspecifiedDefaultValue())) {
                                    if (option.specifiedDefaultValue().equals(null)) {
                                        help.append("; no default value");
                                    } else {
                                        help.append("; default: '").append(option.specifiedDefaultValue()).append("'");
                                    }
                                } else {
                                    if (!"".equals(option.specifiedDefaultValue()) && !NULL.equals(option.specifiedDefaultValue())) {
                                        help.append("; default if option present: '").append(option.specifiedDefaultValue()).append("'");
                                    }
                                    if (!"".equals(option.unspecifiedDefaultValue()) && !NULL.equals(option.unspecifiedDefaultValue())) {
                                        help.append("; default if option not present: '").append(option.unspecifiedDefaultValue()).append("'");
                                    }
                                }
                                help.append(option.mandatory() ? " " : "");
                                // Store details for later
                                key = "--" + key;
                                optionKeys.add(key);
                                optionDetails.put(key, help.toString());
                                // Include it in the mandatory syntax
                                if (option.mandatory()) {
                                    cmdSyntax.append(" ").append(key);
                                }
                            }
                        }
                    }
                    // Make a variable list element
                    Element variableListElement = document.createElement("variablelist");
                    boolean anyVars = false;
                    for (final String optionKey : optionKeys) {
                        anyVars = true;
                        final String help = optionDetails.get(optionKey);
                        variableListElement.appendChild(new XmlElementBuilder("varlistentry", document).addChild(new XmlElementBuilder("term", document).setText(optionKey).build()).addChild(new XmlElementBuilder("listitem", document).addChild(new XmlElementBuilder("para", document).setText(help).build()).build()).build());
                    }
                    if (!anyVars) {
                        variableListElement = new XmlElementBuilder("para", document).setText("This command does not accept any options.").build();
                    }
                    // Now we've figured out the options, store this
                    // individual command
                    final CDATASection progList = document.createCDATASection(cmdSyntax.toString());
                    final String safeName = cmd.value()[0].replace("\\", "BCK").replace("/", "FWD").replace("*", "ASX");
                    final Element element = new XmlElementBuilder("section", document).addAttribute("xml:id", "command-index-" + safeName.toLowerCase().replace(' ', '-')).addChild(new XmlElementBuilder("title", document).setText(cmd.value()[0]).build()).addChild(new XmlElementBuilder("para", document).setText(cmd.help()).build()).addChild(new XmlElementBuilder("programlisting", document).addChild(progList).build()).addChild(variableListElement).build();
                    individualCommands.put(cmdSyntax.toString(), element);
                }
            }
            final Element topSection = document.createElement("section");
            topSection.setAttribute("xml:id", "command-index-" + section.toLowerCase().replace(' ', '-'));
            topSection.appendChild(new XmlElementBuilder("title", document).setText(section).build());
            topSection.appendChild(new XmlElementBuilder("para", document).setText(section + " are contained in " + target.getClass().getName() + ".").build());
            for (final Element value : individualCommands.values()) {
                topSection.appendChild(value);
            }
            builtSections.add(topSection);
        }
        final Element appendix = document.createElement("appendix");
        appendix.setAttribute("xmlns", "http://docbook.org/ns/docbook");
        appendix.setAttribute("version", "5.0");
        appendix.setAttribute("xml:id", "command-index");
        appendix.appendChild(new XmlElementBuilder("title", document).setText("Command Index").build());
        appendix.appendChild(new XmlElementBuilder("para", document).setText("This appendix was automatically built from Roo " + AbstractShell.versionInfo() + ".").build());
        appendix.appendChild(new XmlElementBuilder("para", document).setText("Commands are listed in alphabetic order, and are shown in monospaced font with any mandatory options you must specify when using the command. Most commands accept a large number of options, and all of the possible options for each command are presented in this appendix.").build());
        for (final Element section : builtSections) {
            appendix.appendChild(section);
        }
        document.appendChild(appendix);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final Transformer transformer = XmlUtils.createIndentingTransformer();
        // Causes an
        // "Error reported by XML parser: Multiple notations were used which had the name 'linespecific', but which were not determined to be duplicates."
        // when creating the DocBook
        // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
        // "-//OASIS//DTD DocBook XML V4.5//EN");
        // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
        // "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd");
        XmlUtils.writeXml(transformer, byteArrayOutputStream, document);
        try {
            final File output = new File(f, "appendix-command-index.xml");
            FileUtils.writeByteArrayToFile(output, byteArrayOutputStream.toByteArray());
        } catch (final IOException ioe) {
            throw new IllegalStateException(ioe);
        } finally {
            IOUtils.closeQuietly(byteArrayOutputStream);
        }
    }
}
Also used : CommandMarker(org.springframework.roo.shell.CommandMarker) Transformer(javax.xml.transform.Transformer) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) CliOption(org.springframework.roo.shell.CliOption) CDATASection(org.w3c.dom.CDATASection) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) FileFilter(java.io.FileFilter) Pattern(java.util.regex.Pattern) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) TreeMap(java.util.TreeMap) XmlElementBuilder(org.springframework.roo.support.util.XmlElementBuilder) Annotation(java.lang.annotation.Annotation) ServiceReference(org.osgi.framework.ServiceReference) DocumentBuilder(javax.xml.parsers.DocumentBuilder) CliCommand(org.springframework.roo.shell.CliCommand) File(java.io.File)

Example 7 with XmlElementBuilder

use of org.springframework.roo.support.util.XmlElementBuilder in project spring-roo by spring-projects.

the class JspOperationsImpl method registerStaticSpringMvcController.

/**
 * Registers a static Spring MVC controller to handle the given relative
 * URL.
 *
 * @param relativeUrl the relative URL to handle (required); a leading slash
 *            will be added if required
 */
private void registerStaticSpringMvcController(final String relativeUrl, final LogicalPath webappPath) {
    final String mvcConfig = getProjectOperations().getPathResolver().getIdentifier(webappPath, "WEB-INF/spring/webmvc-config.xml");
    if (fileManager.exists(mvcConfig)) {
        final Document document = XmlUtils.readXml(fileManager.getInputStream(mvcConfig));
        final String prefixedUrl = "/" + relativeUrl;
        if (XmlUtils.findFirstElement("/beans/view-controller[@path='" + prefixedUrl + "']", document.getDocumentElement()) == null) {
            final Element sibling = XmlUtils.findFirstElement("/beans/view-controller", document.getDocumentElement());
            final Element view = new XmlElementBuilder("mvc:view-controller", document).addAttribute("path", prefixedUrl).build();
            if (sibling != null) {
                sibling.getParentNode().insertBefore(view, sibling);
            } else {
                document.getDocumentElement().appendChild(view);
            }
            fileManager.createOrUpdateTextFileIfRequired(mvcConfig, XmlUtils.nodeToString(document), false);
        }
    }
}
Also used : Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) XmlElementBuilder(org.springframework.roo.support.util.XmlElementBuilder)

Example 8 with XmlElementBuilder

use of org.springframework.roo.support.util.XmlElementBuilder in project spring-roo by spring-projects.

the class JspViewManager method getFinderDocument.

public Document getFinderDocument(final FinderMetadataDetails finderMetadataDetails) {
    final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
    final Document document = builder.newDocument();
    // Add document namespaces
    final Element div = (Element) document.appendChild(new XmlElementBuilder("div", document).addAttribute("xmlns:form", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:field", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build());
    final Element formFind = new XmlElementBuilder("form:find", document).addAttribute("id", XmlUtils.convertId("ff:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("path", controllerPath).addAttribute("finderName", finderMetadataDetails.getFinderMethodMetadata().getMethodName().getSymbolName().replace("find" + formBackingTypeMetadata.getPlural(), "")).build();
    formFind.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(formFind));
    div.appendChild(formFind);
    for (final FieldMetadata field : finderMetadataDetails.getFinderMethodParamFields()) {
        final JavaType type = field.getFieldType();
        final JavaSymbolName paramName = field.getFieldName();
        JavaSymbolName fieldName = null;
        if (paramName.getSymbolName().startsWith("max") || paramName.getSymbolName().startsWith("min")) {
            fieldName = new JavaSymbolName(Introspector.decapitalize(StringUtils.capitalize(paramName.getSymbolName().substring(3))));
        } else {
            fieldName = paramName;
        }
        // Ignoring java.util.Map field types (see ROO-194)
        if (type.equals(new JavaType(Map.class.getName()))) {
            continue;
        }
        Validate.notNull(paramName, "Could not find field '%s' in '%s'", paramName, type.getFullyQualifiedTypeName());
        Element fieldElement = null;
        final JavaTypeMetadataDetails typeMetadataHolder = relatedDomainTypes.get(getJavaTypeForField(field));
        if (type.isCommonCollectionType() && relatedDomainTypes.containsKey(getJavaTypeForField(field))) {
            final JavaTypeMetadataDetails collectionTypeMetadataHolder = relatedDomainTypes.get(getJavaTypeForField(field));
            final JavaTypePersistenceMetadataDetails typePersistenceMetadataHolder = collectionTypeMetadataHolder.getPersistenceDetails();
            if (typePersistenceMetadataHolder != null) {
                fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + collectionTypeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("itemValue", typePersistenceMetadataHolder.getIdentifierField().getFieldName().getSymbolName()).addAttribute("path", "/" + getPathForType(getJavaTypeForField(field))).build();
                if (field.getCustomData().keySet().contains(CustomDataKeys.MANY_TO_MANY_FIELD)) {
                    fieldElement.setAttribute("multiple", "true");
                }
            }
        } else if (typeMetadataHolder != null && typeMetadataHolder.isEnumType() && field.getCustomData().keySet().contains(CustomDataKeys.ENUMERATED_FIELD)) {
            fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + typeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("path", "/" + getPathForType(type)).build();
        } else if (type.equals(BOOLEAN_OBJECT) || type.equals(BOOLEAN_PRIMITIVE)) {
            fieldElement = document.createElement("field:checkbox");
        } else if (typeMetadataHolder != null && typeMetadataHolder.isApplicationType()) {
            final JavaTypePersistenceMetadataDetails typePersistenceMetadataHolder = typeMetadataHolder.getPersistenceDetails();
            if (typePersistenceMetadataHolder != null) {
                fieldElement = new XmlElementBuilder("field:select", document).addAttribute("required", "true").addAttribute("items", "${" + typeMetadataHolder.getPlural().toLowerCase() + "}").addAttribute("itemValue", typePersistenceMetadataHolder.getIdentifierField().getFieldName().getSymbolName()).addAttribute("path", "/" + getPathForType(type)).build();
            }
        } else if (type.equals(DATE) || type.equals(CALENDAR)) {
            fieldElement = new XmlElementBuilder("field:datetime", document).addAttribute("required", "true").addAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.getSymbolName().toLowerCase() + "_date_format}").build();
        }
        if (fieldElement == null) {
            fieldElement = new XmlElementBuilder("field:input", document).addAttribute("required", "true").build();
        }
        addCommonAttributes(field, fieldElement);
        fieldElement.setAttribute("disableFormBinding", "true");
        fieldElement.setAttribute("field", paramName.getSymbolName());
        fieldElement.setAttribute("id", XmlUtils.convertId("f:" + formBackingType.getFullyQualifiedTypeName() + "." + paramName));
        fieldElement.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldElement));
        formFind.appendChild(fieldElement);
    }
    DomUtils.removeTextNodes(document);
    return document;
}
Also used : JavaTypePersistenceMetadataDetails(org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypePersistenceMetadataDetails) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) JavaTypeMetadataDetails(org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypeMetadataDetails) Document(org.w3c.dom.Document) XmlElementBuilder(org.springframework.roo.support.util.XmlElementBuilder)

Example 9 with XmlElementBuilder

use of org.springframework.roo.support.util.XmlElementBuilder in project spring-roo by spring-projects.

the class JspViewManager method getListDocument.

public Document getListDocument() {
    final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
    final Document document = builder.newDocument();
    // Add document namespaces
    final Element div = new XmlElementBuilder("div", document).addAttribute("xmlns:page", "urn:jsptagdir:/WEB-INF/tags/form").addAttribute("xmlns:table", "urn:jsptagdir:/WEB-INF/tags/form/fields").addAttribute("xmlns:jsp", "http://java.sun.com/JSP/Page").addAttribute("version", "2.0").addChild(new XmlElementBuilder("jsp:directive.page", document).addAttribute("contentType", "text/html;charset=UTF-8").build()).addChild(new XmlElementBuilder("jsp:output", document).addAttribute("omit-xml-declaration", "yes").build()).build();
    document.appendChild(div);
    final Element fieldTable = new XmlElementBuilder("table:table", document).addAttribute("id", XmlUtils.convertId("l:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("data", "${" + formBackingTypeMetadata.getPlural().toLowerCase() + "}").addAttribute("path", controllerPath).build();
    if (!webScaffoldAnnotationValues.isUpdate()) {
        fieldTable.setAttribute("update", "false");
    }
    if (!webScaffoldAnnotationValues.isDelete()) {
        fieldTable.setAttribute("delete", "false");
    }
    if (!formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName().equals("id")) {
        fieldTable.setAttribute("typeIdFieldName", formBackingTypePersistenceMetadata.getIdentifierField().getFieldName().getSymbolName());
    }
    fieldTable.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(fieldTable));
    int fieldCounter = 0;
    for (final FieldMetadata field : fields) {
        if (++fieldCounter < 7) {
            final Element columnElement = new XmlElementBuilder("table:column", document).addAttribute("id", XmlUtils.convertId("c:" + formBackingType.getFullyQualifiedTypeName() + "." + field.getFieldName().getSymbolName())).addAttribute("property", uncapitalize(field.getFieldName().getSymbolName())).build();
            final String fieldName = uncapitalize(field.getFieldName().getSymbolName());
            if (field.getFieldType().equals(DATE)) {
                columnElement.setAttribute("date", "true");
                columnElement.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}");
            } else if (field.getFieldType().equals(CALENDAR)) {
                columnElement.setAttribute("calendar", "true");
                columnElement.setAttribute("dateTimePattern", "${" + entityName + "_" + fieldName.toLowerCase() + "_date_format}");
            } else if (field.getFieldType().isCommonCollectionType() && field.getCustomData().get(CustomDataKeys.ONE_TO_MANY_FIELD) != null) {
                continue;
            }
            columnElement.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(columnElement));
            fieldTable.appendChild(columnElement);
        }
    }
    // Create page:list element
    final Element pageList = new XmlElementBuilder("page:list", document).addAttribute("id", XmlUtils.convertId("pl:" + formBackingType.getFullyQualifiedTypeName())).addAttribute("items", "${" + formBackingTypeMetadata.getPlural().toLowerCase() + "}").addChild(fieldTable).build();
    pageList.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(pageList));
    div.appendChild(pageList);
    return document;
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) XmlElementBuilder(org.springframework.roo.support.util.XmlElementBuilder)

Example 10 with XmlElementBuilder

use of org.springframework.roo.support.util.XmlElementBuilder in project spring-roo by spring-projects.

the class WaveEmbeddedProvider method install.

public boolean install(final String viewName, final Map<String, String> options) {
    if (options == null || options.size() != 2 || !options.containsKey("provider") || !options.get("provider").equalsIgnoreCase("GOOGLE_WAVE") || !options.containsKey("id")) {
        return false;
    }
    final String id = options.get("id");
    installTagx("wave");
    final Element wave = new XmlElementBuilder("embed:wave", XmlUtils.getDocumentBuilder().newDocument()).addAttribute("id", "wave_" + id).addAttribute("waveId", id).build();
    wave.setAttribute("z", XmlRoundTripUtils.calculateUniqueKeyFor(wave));
    installJspx(getViewName(viewName, options.get("provider").toLowerCase()), null, wave);
    return true;
}
Also used : Element(org.w3c.dom.Element) XmlElementBuilder(org.springframework.roo.support.util.XmlElementBuilder)

Aggregations

XmlElementBuilder (org.springframework.roo.support.util.XmlElementBuilder)19 Element (org.w3c.dom.Element)19 Document (org.w3c.dom.Document)11 DocumentBuilder (javax.xml.parsers.DocumentBuilder)6 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)6 ArrayList (java.util.ArrayList)3 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)3 JavaType (org.springframework.roo.model.JavaType)3 JpaJavaType (org.springframework.roo.model.JpaJavaType)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 JavaTypeMetadataDetails (org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypeMetadataDetails)2 JavaTypePersistenceMetadataDetails (org.springframework.roo.addon.web.mvc.controller.addon.details.JavaTypePersistenceMetadataDetails)2 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileFilter (java.io.FileFilter)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Annotation (java.lang.annotation.Annotation)1 Method (java.lang.reflect.Method)1