Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:com.enonic.vertical.engine.handlers.SectionHandler.java

public Document getSections(User user, SectionCriteria criteria) {

    Connection con = null;/*from w ww .j ava2 s.  c  o  m*/
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    Document doc = null;
    SectionView sectionView = SectionView.getInstance();

    try {
        con = getConnection();
        StringBuffer sql;
        SiteKey[] siteKeys = criteria.getSiteKeys();
        MenuItemKey[] menuItemKeys = criteria.getMenuItemKeys();
        int sectionKey = criteria.getSectionKey();
        int superSectionKey = criteria.getSuperSectionKey();
        boolean includeSection = criteria.isIncludeSection();
        int level = criteria.getLevel();
        int[] sectionKeys = criteria.getSectionKeys();
        int contentKey = criteria.getContentKey();
        int contentKeyExcludeFilter = criteria.getContentKeyExcludeFilter();
        int contentTypeKeyFilter = criteria.getContentTypeKeyFilter();
        boolean treeStructure = criteria.isTreeStructure();
        boolean markContentFilteredSections = criteria.isMarkContentFilteredSections();
        boolean includeAll = criteria.isIncludeAll();

        // Generate SQL
        if (siteKeys != null) {
            if (siteKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_men_lKey,
                    siteKeys.length);
        } else if (menuItemKeys != null) {
            if (menuItemKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_lKey,
                    menuItemKeys.length);
        } else if (sectionKey != -1) {
            sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
        } else if (sectionKeys != null) {
            if (sectionKeys.length == 0) {
                return XMLTool.createDocument("sections");
            }
            sql = XDG.generateSelectWhereInSQL(sectionView, (Column[]) null, false, sectionView.mei_lKey,
                    sectionKeys.length);
        } else if (superSectionKey != -1) {
            if (includeSection) {
                sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
                if (level > 0) {
                    level += 1;
                }
            } else {
                sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lParent);
            }
        } else if (contentKey != -1) {
            sql = XDG.generateSelectSQL(sectionView);
            sql.append(" WHERE mei_lKey IN (SELECT sco_mei_lKey FROM tSectionContent2 WHERE sco_con_lKey = ?)");
        } else {
            sql = XDG.generateSelectSQL(sectionView);
        }

        if (contentKeyExcludeFilter > -1 && !markContentFilteredSections) {
            if (sql.toString().toLowerCase().indexOf("where") < 0) {
                sql.append(" WHERE");
            } else {
                sql.append(" AND");
            }
            sql.append(" mei_lKey NOT IN (SELECT sco_mei_lKey FROM tSectionContent2 WHERE sco_con_lKey = ?)");
        }

        if (contentTypeKeyFilter > -1) {
            if (sql.toString().toLowerCase().indexOf("where") < 0) {
                sql.append(" WHERE");
            } else {
                sql.append(" AND");
            }
            sql.append(" (");
            sql.append(" mei_lKey IN (SELECT sctf_mei_lKey FROM tSecConTypeFilter2 WHERE sctf_cty_lkey = ?)");
            if (criteria.isIncludeSectionsWithoutContentTypeEvenWhenFilterIsSet()) {
                sql.append(
                        " OR NOT EXISTS (SELECT sctf_mei_lKey FROM tSecConTypeFilter2 WHERE sctf_mei_lkey = mei_lKey)");
            }
            sql.append(" )");
        }

        SecurityHandler securityHandler = getSecurityHandler();
        if (!includeAll) {
            securityHandler.appendSectionSQL(user, sql, criteria);
        }

        sql.append(" ORDER BY mei_sName");

        preparedStmt = con.prepareStatement(sql.toString());

        int index = 1;
        // Set parameters
        if (siteKeys != null) {
            for (SiteKey siteKey : siteKeys) {
                preparedStmt.setInt(index++, siteKey.toInt());
            }
        } else if (menuItemKeys != null) {
            for (MenuItemKey menuItemKey : menuItemKeys) {
                preparedStmt.setInt(index++, menuItemKey.toInt());
            }
        } else if (sectionKey != -1) {
            preparedStmt.setInt(index++, sectionKey);
        } else if (sectionKeys != null) {
            for (int loopSectionKey : sectionKeys) {
                preparedStmt.setInt(index++, loopSectionKey);
            }
        } else if (superSectionKey != -1) {
            preparedStmt.setInt(index++, superSectionKey);
        } else if (contentKey != -1) {
            preparedStmt.setInt(index++, contentKey);
        }

        if (contentKeyExcludeFilter > -1 && !markContentFilteredSections) {
            preparedStmt.setInt(index++, contentKeyExcludeFilter);
        }
        if (contentTypeKeyFilter > -1) {
            preparedStmt.setInt(index, contentTypeKeyFilter);
        }

        resultSet = preparedStmt.executeQuery();

        ElementProcessor childCountProcessor = null;
        if (criteria.getIncludeChildCount()) {
            childCountProcessor = new ChildCountProcessor();
        }

        Map<String, Element> elemMap = new HashMap<String, Element>();
        CollectionProcessor collectionProcessor = new CollectionProcessor(elemMap, null);
        ElementProcessor[] processors;
        ElementProcessor aep = null;
        if (contentKeyExcludeFilter >= 0) {
            if (markContentFilteredSections) {
                int[] keys = getSectionKeysByContent(contentKeyExcludeFilter, -1);
                aep = new FilteredAttributeElementProcessor("filtered", "true", keys);
            }
        }
        if (contentKey >= 0 && markContentFilteredSections) {
            int[] keys = getSectionKeysByContent(contentKey, -1);
            aep = new FilteredAttributeElementProcessor("filtered", "true", keys);
        }

        SectionProcessor sectionProcessorThatIncludesContentTypes = null;

        if (criteria.isIncludeSectionContentTypesInfo()) {
            sectionProcessorThatIncludesContentTypes = new SectionProcessor();
        }

        processors = new ElementProcessor[] { aep,
                // mark content in original query
                new AttributeElementProcessor("marked", "true"), sectionProcessorThatIncludesContentTypes,
                collectionProcessor, childCountProcessor };

        doc = XDG.resultSetToXML(sectionView, resultSet, null, processors, null, -1);
        close(resultSet);
        close(preparedStmt);

        // If treeStructure is true, all parents of the retrieved section
        // are retrieved:
        if (treeStructure) {
            sql = XDG.generateSelectSQL(sectionView, sectionView.mei_lKey);
            preparedStmt = con.prepareStatement(sql.toString());

            Element sectionsRootElement = doc.getDocumentElement();
            List<Element> sectionsElementList = XMLTool.getElementsAsList(sectionsRootElement);
            collectionProcessor.elemList = sectionsElementList;

            // remove marking of sections ("filtered"(0) and "marked"(1) attributes)
            processors[0] = null;
            processors[1] = null;

            for (int i = 0; i < sectionsElementList.size(); i++) {
                Element sectionElement = sectionsElementList.get(i);
                String superKey = sectionElement.getAttribute("supersectionkey");
                if (superKey != null && superKey.length() > 0) {
                    sectionsRootElement.removeChild(sectionElement);

                    // find parent element and append current element
                    Element parentElem = elemMap.get("section_" + superKey);
                    if (parentElem == null) {
                        int key = Integer.parseInt(superKey);
                        preparedStmt.setInt(1, key);
                        resultSet = preparedStmt.executeQuery();
                        XDG.resultSetToXML(sectionView, resultSet, doc.getDocumentElement(), processors, "name",
                                -1);
                        close(resultSet);
                        parentElem = collectionProcessor.lastElem;
                    }
                    Element elem = XMLTool.createElementIfNotPresent(doc, parentElem, "sections");
                    elem.appendChild(sectionElement);
                }
            }
        }

        // If specified, get sections recursivly, i.e. retrieve all sections below the
        // the retrieved sections:
        else if (criteria.getSectionsRecursivly()) {
            if (level > 1 || level == 0) {
                Element sectionsElement = doc.getDocumentElement();
                Element[] sections = XMLTool.getElements(sectionsElement, "section");

                for (Element section : sections) {
                    int currentSectionKey = Integer.parseInt(section.getAttribute("key"));
                    int[] subSectionKeys = getSectionKeysBySuperSection(currentSectionKey, false);

                    if (subSectionKeys.length > 0) {

                        criteria.setSectionKey(-1);
                        criteria.setSectionKeys(subSectionKeys);
                        criteria.setLevel((level > 1 ? level - 1 : 0));

                        Document subSectionsDoc = getSections(user, criteria);
                        section.appendChild(doc.importNode(subSectionsDoc.getDocumentElement(), true));
                    }
                }
            }
        }

        if (criteria.appendAccessRights()) {
            securityHandler.appendAccessRights(user, doc, true, true);
        }
    } catch (SQLException sqle) {
        String message = "Failed to get sections: %t";
        VerticalEngineLogger.error(this.getClass(), 1, message, sqle);
        doc = XMLTool.createDocument("sections");
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }
    return doc;
}

From source file:com.enonic.vertical.adminweb.handlers.xmlbuilders.SimpleContentXMLBuilder.java

private void createGroupBlock(ExtendedMap formItems, Document doc, Element contentdata, NodeList inputElements,
        String groupXPath, int groupCounter) throws ParseException {
    // get number of block instances
    int instances = 1;
    if (AdminHandlerBaseServlet.isArrayFormItem(formItems, "group" + groupCounter + "_counter")) {
        instances = ((String[]) formItems.get("group" + groupCounter + "_counter")).length;
    }// w w w.j a v a  2  s .  c  o  m

    ArrayList<Integer> keepBinaries;
    if (formItems.containsKey("__keepbinaries")) {
        keepBinaries = (ArrayList<Integer>) formItems.get("__keepbinaries");
    } else {
        keepBinaries = new ArrayList<Integer>();
    }

    Element[] blocks = new Element[instances];

    for (int k = 0; k < instances; ++k) {
        // First, create the elements in the xpath:
        blocks[k] = createXPathElements(contentdata, groupXPath, 1);
    }

    for (int i = 0; i < inputElements.getLength(); ++i) {
        Element inputElem = (Element) inputElements.item(i);
        String name = inputElem.getAttribute("name");
        String xpath = XMLTool.getElementText(inputElem, "xpath");
        String type = inputElem.getAttribute("type");

        if (xpath != null) {

            // Then store the data.
            // Some types may need to be treated separatly.

            // date
            if (type.equals("date")) {
                if (instances > 1) {
                    String[] values = (String[]) formItems.get("date" + name);

                    for (int j = 0; j < instances; ++j) {
                        if (values[j] != null && values[j].length() > 0) {
                            Date tempDate = DateUtil.parseDate(values[j]);
                            XMLTool.createTextNode(doc, createXPathElements(blocks[j], xpath, 0),
                                    DateUtil.formatISODate(tempDate));
                        }
                    }
                } else {
                    if (formItems.containsKey("date" + name)) {
                        Date tempDate = DateUtil.parseDate(formItems.getString("date" + name));
                        XMLTool.createTextNode(doc, createXPathElements(blocks[0], xpath, 0),
                                DateUtil.formatISODate(tempDate));
                    }
                }

            }

            // file
            else if (type.equals("file")) {
                if (instances > 1) {
                    String[] values = (String[]) formItems.get(name);

                    for (int j = 0; j < instances; ++j) {
                        if (values[j] != null && values[j].length() > 0) {
                            Element file = XMLTool.createElement(doc, createXPathElements(blocks[j], xpath, 0),
                                    "file");
                            file.setAttribute("key", values[j]);
                        }
                    }
                } else {
                    String filekey = formItems.getString(name, null);
                    Element fileEl = XMLTool.createElement(doc, createXPathElements(blocks[0], xpath, 0),
                            "file");

                    if (filekey != null && filekey.length() > 0) {
                        fileEl.setAttribute("key", filekey);
                    }
                }
            }

            // image
            else if (type.equals("image")) {
                if (instances > 1) {
                    String[] values = (String[]) formItems.get(name, null);
                    //String[] textValues = (String[]) formItems.get(name + "text");

                    if (values == null) {
                        continue;
                    }

                    for (int j = 0; j < instances; ++j) {
                        Element tmpElem = createXPathElements(blocks[j], xpath, 0);

                        if (values[j] != null && values[j].length() > 0) {
                            tmpElem.setAttribute("key", values[j]);
                            /*if ("true".equals(inputElem.getAttribute("imagetext")))
                                    XMLTool.createElement(doc, tmpElem, "text", textValues[j]);*/
                        }
                    }
                } else {
                    String value = formItems.getString(name, null);
                    //String text = formItems.getString(name + "text", null);
                    Element tmpElem = createXPathElements(blocks[0], xpath, 0);

                    if (value != null && value.length() > 0) {
                        tmpElem.setAttribute("key", value);
                        /*if ("true".equals(inputElem.getAttribute("imagetext")))
                               XMLTool.createElement(doc, tmpElem, "text", text);*/
                    }
                }

            }

            // checkbox
            else if (type.equals("checkbox")) {
                if (instances > 1) {
                    String[] values = (String[]) formItems.get(name);

                    for (int j = 0; j < instances; ++j) {
                        Element tmpElem = createXPathElements(blocks[j], xpath, 0);

                        if ("true".equals(values[j])) {
                            XMLTool.createTextNode(doc, tmpElem, "true");
                        } else {
                            XMLTool.createTextNode(doc, tmpElem, "false");
                        }
                    }
                } else {
                    Element tmpElem = createXPathElements(blocks[0], xpath, 0);

                    if ("true".equals(formItems.getString(name, "false"))) {
                        XMLTool.createTextNode(doc, tmpElem, "true");
                    } else {
                        XMLTool.createTextNode(doc, tmpElem, "false");
                    }
                }
            }

            // uploaded binary file
            else if (type.equals("uploadfile")) {
                BinaryData[] binaries = (BinaryData[]) formItems.get("__binaries", null);
                String[] fileNames = formItems.getStringArray("filename_" + name);
                String[] values = formItems.getStringArray(name);

                for (int instance = 0; instance < instances; instance++) {
                    int oldKey = -1;
                    if (values != null && values.length > 0 && values[instance] != null
                            && values[instance].length() > 0) {
                        oldKey = Integer.parseInt(values[instance]);
                    }

                    boolean isReplaced = false;

                    if (instance < fileNames.length) {
                        if (binaries != null && binaries.length > 0) {
                            int index = -1;

                            for (int counter = 0; counter < binaries.length; counter++) {
                                if (fileNames[instance].equals(binaries[counter].fileName)) {
                                    index = counter;
                                    break;
                                }
                            }
                            if (index != -1) {
                                Element tmpElem = createXPathElements(blocks[instance], xpath, 0);
                                Element binaryElement = XMLTool.createElement(doc, tmpElem, "binarydata");
                                binaryElement.setAttribute("key", "%" + index);

                                if (oldKey != -1) {
                                    isReplaced = true;
                                }
                            }
                        }
                    }
                    if (oldKey != -1 && !isReplaced) {
                        Element tmpElem = createXPathElements(blocks[instance], xpath, 0);
                        Element binaryElement = XMLTool.createElement(doc, tmpElem, "binarydata");
                        binaryElement.setAttribute("key", String.valueOf(oldKey));

                        keepBinaries.add(oldKey);
                        formItems.put("__keepbinaries", keepBinaries);
                    }
                }
                formItems.put("__keepbinaries", keepBinaries);
            }

            // relatedcontent
            else if (type.equals("relatedcontent")) {
                if (!"false".equals(inputElem.getAttribute("multiple"))) {
                    String[] keys = formItems.getStringArray(name);
                    String[] counters = formItems.getStringArray(name + "_counter");

                    if (counters != null && counters.length > 0) {
                        int index = 0;
                        for (int j = 0; j < instances; j++) {
                            int keyCount = Integer.parseInt(counters[j]);
                            Element tmpElem = createXPathElements(blocks[j], xpath, 0);
                            for (int k = index; k < index + keyCount; k++) {
                                Element contentElem = XMLTool.createElement(doc, tmpElem, "content");
                                contentElem.setAttribute("key", String.valueOf(keys[k]));
                            }
                            index = index + keyCount;
                        }
                    }
                } else if (formItems.containsKey(name)) {
                    String[] keys = formItems.getStringArray(name);
                    for (int j = 0; j < instances; j++) {
                        if (!"".equals(keys[j])) {
                            Element tmpElem = createXPathElements(blocks[j], xpath, 0);
                            tmpElem.setAttribute("key", String.valueOf(keys[j]));
                        }
                    }
                }
            } else if (type.equals("xml")) {
                if (instances > 1 && formItems.containsKey(name)) {
                    String[] values = formItems.getStringArray(name);

                    for (int j = 0; j < instances && j < values.length; ++j) {
                        if (values[j] != null && values[j].length() > 0) {
                            Element tmpElem = createXPathElements(blocks[j], xpath, 0);
                            Document xmlDoc = XMLTool.domparse(values[j]);
                            tmpElem.appendChild(doc.importNode(xmlDoc.getDocumentElement(), true));
                        }
                    }
                } else {
                    Element tmpElem = createXPathElements(blocks[0], xpath, 0);

                    if (formItems.containsKey(name)) {
                        String value = formItems.getString(name);
                        Document xmlDoc = XMLTool.domparse(value);
                        tmpElem.appendChild(doc.importNode(xmlDoc.getDocumentElement(), true));
                    }
                }
            }
            //JIRA VS-2461 Hack to make radiobuttons work in groups
            // radiobutton
            else if (type.equals("radiobutton")) {
                String[] radiobuttonNames = getFormItemsByRegexp("rb:[0-9].*:" + name, formItems);

                for (int j = 0; j < instances; ++j) {
                    if ((radiobuttonNames.length) > j && radiobuttonNames[j] != null) {
                        if (!formItems.getString(radiobuttonNames[j]).equals(radiobuttonNames[j])) {
                            Element tmpElem = createXPathElements(blocks[j], xpath, 0);
                            XMLTool.createTextNode(doc, tmpElem, formItems.getString(radiobuttonNames[j]));
                        }
                    }
                }
            }

            // normal text
            else {
                if (instances > 1 && formItems.containsKey(name)) {
                    String[] values = formItems.getStringArray(name);

                    for (int j = 0; j < instances && j < values.length; ++j) {
                        if (values[j] != null && values[j].length() > 0) {
                            Element tmpElem = createXPathElements(blocks[j], xpath, 0);

                            if (type.equals("htmlarea") || type.equals("simplehtmlarea")) {
                                XMLTool.createXHTMLNodes(doc, tmpElem, values[j], true);
                            } else {
                                XMLTool.createTextNode(doc, tmpElem, values[j]);
                            }
                        }
                    }
                } else {
                    Element tmpElem = createXPathElements(blocks[0], xpath, 0);

                    if (formItems.containsKey(name)) {
                        String value = formItems.getString(name);

                        if (type.equals("htmlarea") || type.equals("simplehtmlarea")) {
                            XMLTool.createXHTMLNodes(doc, tmpElem, value, true);
                        } else {
                            XMLTool.createTextNode(doc, tmpElem, value);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.enonic.vertical.adminweb.PageTemplateHandlerServlet.java

private Document buildPageTemplateXML(ExtendedMap formItems, boolean createPageTemplate)
        throws VerticalAdminException {

    String key = null;//from ww w  .j  av  a  2s  .  c  om
    Element tempElement;

    Document doc = XMLTool.createDocument("pagetemplate");
    Element pageTemplate = doc.getDocumentElement();

    String type = formItems.getString("type", "page");
    pageTemplate.setAttribute("type", type);

    String runAs = formItems.getString("runAs", RunAsType.INHERIT.toString());
    pageTemplate.setAttribute("runAs", runAs);

    String menuKey = formItems.getString("menukey");
    pageTemplate.setAttribute("menukey", menuKey);

    if (!createPageTemplate) {
        key = formItems.getString("key");
        pageTemplate.setAttribute("key", key);
    }

    // CSS:
    String tmp = formItems.getString("csskey", null);
    if (tmp != null && tmp.length() > 0) {
        tempElement = XMLTool.createElement(doc, pageTemplate, "css");
        tempElement.setAttribute("stylesheetkey", tmp);
    }

    XMLTool.createElement(doc, pageTemplate, "name", formItems.getString("name", ""));

    XMLTool.createElement(doc, pageTemplate, "description", formItems.getString("description", ""));

    tempElement = XMLTool.createElement(doc, pageTemplate, "stylesheet");
    if (formItems.containsKey("stylesheetkey")) {
        tempElement.setAttribute("stylesheetkey", formItems.getString("stylesheetkey"));
    }

    Element templateParams = XMLTool.createElement(doc, pageTemplate, "pagetemplateparameters");

    if (isArrayFormItem(formItems, "paramname") == false) {
        if (formItems.containsKey("paramname")) {
            if (createPageTemplate) {
                createTemplateParamXML(createPageTemplate, doc, templateParams, "", null,
                        formItems.getString("multiple1", null) != null
                                && formItems.getString("multiple1", "").length() > 0
                                        ? formItems.getString("multiple1")
                                        : "0",
                        "0", formItems.getString("paramname", ""), formItems.getString("separator", ""));
            } else {
                createTemplateParamXML(createPageTemplate, doc, templateParams,
                        formItems.getString("paramkey", ""), key,
                        formItems.getString("multiple1", null) != null
                                && (formItems.getString("multiple1")).length() > 0
                                        ? formItems.getString("multiple1")
                                        : "0",
                        "0", formItems.getString("paramname"), formItems.getString("separator", ""));
            }
        }
    } else {
        String[] paramNameArray = (String[]) formItems.get("paramname");
        String[] paramKeyArray = (String[]) formItems.get("paramkey", null);
        String[] separatorArray = (String[]) formItems.get("separator");

        for (int j = 0; j < paramNameArray.length; j++) {
            if (paramNameArray[j] != null && paramNameArray[j].trim().length() != 0) {
                String multiple = formItems.getString("multiple" + (j + 1), "0");
                if (createPageTemplate) {
                    createTemplateParamXML(createPageTemplate, doc, templateParams, "", null, multiple, "0",
                            paramNameArray[j], separatorArray[j]);
                } else {
                    createTemplateParamXML(createPageTemplate, doc, templateParams, paramKeyArray[j], key,
                            multiple, "0", paramNameArray[j], separatorArray[j]);
                }
            }
        }
    }

    // Default contentobjects for the page template:
    if (isArrayFormItem(formItems, "paramname")) {
        String[] paramNameArray = (String[]) formItems.get("paramname");
        String[] paramKeyArray = (String[]) formItems.get("paramkey", null);
        Element contentObjectsElem = XMLTool.createElement(doc, pageTemplate, "contentobjects");

        int newObjectCounter = 0;
        for (int i = 0; i < paramNameArray.length; ++i) {
            if (isArrayFormItem(formItems, paramNameArray[i] + "co")) {
                String[] coArray = (String[]) formItems.get(paramNameArray[i] + "co");
                String[] coNameArray = (String[]) formItems.get("view" + paramNameArray[i] + "co");
                boolean used = false;
                for (int j = 0; j < coArray.length; j++) {
                    Element contentObjectElem = XMLTool.createElement(doc, contentObjectsElem, "contentobject");
                    contentObjectElem.setAttribute("conobjkey", coArray[j]);
                    if (paramKeyArray != null && paramKeyArray[i].length() > 0) {
                        contentObjectElem.setAttribute("parameterkey", paramKeyArray[i]);
                    } else {
                        contentObjectElem.setAttribute("parameterkey", "_" + newObjectCounter);
                        used = true;
                    }
                    XMLTool.createElement(doc, contentObjectElem, "order", String.valueOf(j));
                    XMLTool.createElement(doc, contentObjectElem, "name", coNameArray[j]);

                    if (pageTemplate.getAttribute("key") != null) {
                        contentObjectElem.setAttribute("pagetemplatekey", pageTemplate.getAttribute("key"));
                    }
                }
                if (used) {
                    newObjectCounter++;
                }
            } else if (formItems.containsKey(paramNameArray[i] + "co")) {
                String coName = formItems.getString("view" + paramNameArray[i] + "co");
                Element contentObjectElem = XMLTool.createElement(doc, contentObjectsElem, "contentobject");
                contentObjectElem.setAttribute("conobjkey", formItems.getString(paramNameArray[i] + "co"));
                if (paramKeyArray != null && paramKeyArray[i].length() > 0) {
                    contentObjectElem.setAttribute("parameterkey", paramKeyArray[i]);
                } else {
                    contentObjectElem.setAttribute("parameterkey", "_" + newObjectCounter++);
                }
                XMLTool.createElement(doc, contentObjectElem, "order", "0");
                XMLTool.createElement(doc, contentObjectElem, "name", coName);

                if (pageTemplate.getAttribute("key") != null) {
                    contentObjectElem.setAttribute("pagetemplatekey", pageTemplate.getAttribute("key"));
                }
            } else {
                // This fixes a bug when inserting objects in a new page template. If the object was inserted at pos 3 with no
                // object at pos 1, it would be placed in pos 1.
                if (createPageTemplate) {
                    newObjectCounter++;
                }
            }
        }
    } else if (formItems.containsKey("paramname")) {
        String paramName = formItems.getString("paramname");
        String paramKey = formItems.getString("paramkey", "_0");

        Element contentObjectsElem = XMLTool.createElement(doc, pageTemplate, "contentobjects");
        if (isArrayFormItem(formItems, paramName + "co")) {
            String[] coArray = (String[]) formItems.get(paramName + "co");
            for (int j = 0; j < coArray.length; j++) {
                Element contentObjectElem = XMLTool.createElement(doc, contentObjectsElem, "contentobject");
                contentObjectElem.setAttribute("conobjkey", coArray[j]);
                if (paramKey != null && paramKey.length() > 0) {
                    contentObjectElem.setAttribute("parameterkey", paramKey);
                }
                XMLTool.createElement(doc, contentObjectElem, "order", String.valueOf(j));

                if (pageTemplate.getAttribute("key") != null) {
                    contentObjectElem.setAttribute("pagetemplatekey", pageTemplate.getAttribute("key"));
                }
            }
        } else if (formItems.containsKey(paramName + "co")) {
            Element contentObjectElem = XMLTool.createElement(doc, contentObjectsElem, "contentobject");
            contentObjectElem.setAttribute("conobjkey", formItems.getString(paramName + "co"));
            if (paramKey != null && paramKey.length() > 0) {
                contentObjectElem.setAttribute("parameterkey", paramKey);
            }
            XMLTool.createElement(doc, contentObjectElem, "order", "0");

            if (pageTemplate.getAttribute("key") != null) {
                contentObjectElem.setAttribute("pagetemplatekey", pageTemplate.getAttribute("key"));
            }
        }

    }

    // page template parameters other than parameters of type "object"
    Element ptdElem = XMLTool.createElement(doc, pageTemplate, "pagetemplatedata");
    if (isArrayFormItem(formItems, "parameter_name")) {

        String[] paramNames = (String[]) formItems.get("parameter_name");
        String[] paramValues = (String[]) formItems.get("parameter_value");
        String[] paramValueNames = (String[]) formItems.get("viewparameter_value");
        String[] paramTypes = (String[]) formItems.get("parameter_type");

        for (int i = 0; i < paramNames.length; ++i) {
            Element ptpElem = XMLTool.createElement(doc, ptdElem, "pagetemplateparameter");
            ptpElem.setAttribute("name", paramNames[i]);
            ptpElem.setAttribute("value", paramValues[i]);
            ptpElem.setAttribute("type", paramTypes[i]);
            if (paramValueNames[i] != null && paramValueNames[i].length() > 0) {
                ptpElem.setAttribute("valuename", paramValueNames[i]);
            }
        }
    } else if (formItems.containsKey("parameter_name")) {
        String paramName = formItems.getString("parameter_name", null);
        if (paramName != null && paramName.length() > 0) {
            String paramValue = formItems.getString("parameter_value", "");
            String paramValueName = formItems.getString("viewparameter_value", null);
            String paramType = formItems.getString("parameter_type", "");

            Element ptpElem = XMLTool.createElement(doc, ptdElem, "pagetemplateparameter");
            ptpElem.setAttribute("name", paramName);
            ptpElem.setAttribute("value", paramValue);
            ptpElem.setAttribute("type", paramType);
            if (paramValueName != null) {
                ptpElem.setAttribute("valuename", paramValueName);
            }
        }
    }

    // Datasources
    String datasources = formItems.getString("datasources", null);
    if (StringUtils.isNotBlank(datasources)) {
        Document dsDoc = XMLTool.domparse(datasources);
        ptdElem.appendChild(doc.importNode(dsDoc.getDocumentElement(), true));
    }

    // default document
    Element documentElem = XMLTool.createElement(doc, ptdElem, "document");
    if (verticalProperties.isStoreXHTMLOn()) {
        documentElem.setAttribute("mode", "xhtml");
        XMLTool.createXHTMLNodes(doc, documentElem, formItems.getString("contentdata_body", ""), true);
    } else {
        XMLTool.createCDATASection(doc, documentElem, formItems.getString("contentdata_body", ""));
    }

    // Content types
    Element ctyElem = XMLTool.createElement(doc, pageTemplate, "contenttypes");
    String[] contentTypeKeys = formItems.getStringArray("contenttypekey");
    for (String contentTypeKey : contentTypeKeys) {
        XMLTool.createElement(doc, ctyElem, "contenttype").setAttribute("key", contentTypeKey);
    }

    return doc;
}

From source file:nl.nn.adapterframework.extensions.bis.BisWrapperPipe.java

private String prepareReply(String rawReply, String messageHeader, String result, boolean resultInPayload)
        throws DomBuilderException, IOException, TransformerException {
    ArrayList messages = new ArrayList();
    if (messageHeader != null) {
        messages.add(messageHeader);/*w  w  w .  j av  a  2  s  . c  o m*/
    }
    messages.add(rawReply);

    String payload = null;
    if (result == null) {
        payload = Misc.listToString(messages);
    } else {
        if (resultInPayload) {
            String message = Misc.listToString(messages);
            Document messageDoc = XmlUtils.buildDomDocument(message);
            Node messageRootNode = messageDoc.getFirstChild();
            Node resultNode = messageDoc.importNode(XmlUtils.buildNode(result), true);
            messageRootNode.appendChild(resultNode);
            payload = XmlUtils.nodeToString(messageDoc);
        } else {
            messages.add(result);
            payload = Misc.listToString(messages);
        }
    }
    return payload;
}

From source file:org.alfresco.repo.rendition.executer.XSLTRenderingEngine.java

@SuppressWarnings({ "serial", "unchecked" })
protected Object buildModel(RenderingContext context) {
    Map<String, Serializable> suppliedParams = context.getCheckedParam(PARAM_MODEL, Map.class);
    final NodeRef sourceNode = context.getSourceNode();
    final NodeRef parentNode = nodeService.getPrimaryParent(context.getSourceNode()).getParentRef();
    final String sourcePath = getPath(sourceNode);
    final String parentPath = getPath(parentNode);

    XSLTemplateModel model = new XSLTemplateModel();

    // add simple scalar parameters
    model.put(QName.createQName(NamespaceService.ALFRESCO_URI, "date"), new Date());

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "source_file_name", namespacePrefixResolver),
            nodeService.getProperty(context.getSourceNode(), ContentModel.PROP_NAME));
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "source_path", namespacePrefixResolver),
            sourcePath);// ww w.ja va  2 s  .c  o m
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver),
            parentPath);

    // add methods
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to encodeQuotes.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String text = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath);
                    }

                    final String result = xsltFunctions.encodeQuotes(text);
                    return result;
                }
            });

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to parseXMLDocument.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String path = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("parseXMLDocument('" + path + "'), parentPath = " + parentPath);
                    }

                    Document d = null;
                    try {
                        d = xsltFunctions.parseXMLDocument(parentNode, path);
                    } catch (Exception ex) {
                        log.warn("Received an exception from parseXMLDocument()", ex);
                    }
                    return d == null ? null : d.getDocumentElement();
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver),
            new TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length > 2) {
                        throw new IllegalArgumentException("expected one or two arguments to "
                                + "parseXMLDocuments.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    if (arguments.length == 2 && !(arguments[1] instanceof String)) {
                        throw new ClassCastException("expected arguments[1] to be a " + String.class.getName()
                                + ".  got a " + arguments[1].getClass().getName() + ".");
                    }

                    String path = arguments.length == 2 ? (String) arguments[1] : "";
                    final String typeName = (String) arguments[0];

                    if (log.isDebugEnabled()) {
                        log.debug("tpm_parseXMLDocuments('" + typeName + "','" + path + "'), parentPath = "
                                + parentPath);
                    }

                    final Map<String, Document> resultMap = xsltFunctions.parseXMLDocuments(typeName,
                            parentNode, path);

                    if (log.isDebugEnabled()) {
                        log.debug("received " + resultMap.size() + " documents in " + path + " with form name "
                                + typeName);
                    }

                    // create a root document for rooting all the results. we do this
                    // so that each document root element has a common parent node
                    // and so that xpath axes work properly
                    final Document rootNodeDocument = XMLUtil.newDocument();
                    final Element rootNodeDocumentEl = rootNodeDocument.createElementNS(
                            NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list");
                    rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                            NamespaceService.ALFRESCO_URI);
                    rootNodeDocument.appendChild(rootNodeDocumentEl);

                    final List<Node> result = new ArrayList<Node>(resultMap.size());
                    for (Map.Entry<String, Document> e : resultMap.entrySet()) {
                        final Element documentEl = e.getValue().getDocumentElement();
                        documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                                NamespaceService.ALFRESCO_URI);
                        documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI,
                                NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey());
                        final Node n = rootNodeDocument.importNode(documentEl, true);
                        rootNodeDocumentEl.appendChild(n);
                        result.add(n);
                    }
                    return result.toArray(new Node[result.size()]);
                }
            });

    if (suppliedParams != null) {
        for (Map.Entry<String, Serializable> suppliedParam : suppliedParams.entrySet()) {
            model.put(QName.createQName(suppliedParam.getKey()), suppliedParam.getValue());
        }
    }

    // add the xml document
    try {
        model.put(XSLTProcessor.ROOT_NAMESPACE, XMLUtil.parse(sourceNode, contentService));
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RenditionServiceException("Failed to parse XML from source node.", ex);
    }
    return model;
}

From source file:org.alfresco.repo.web.scripts.bean.ADMRemoteStore.java

/**
 * Creates multiple XML documents encapsulated in a single one. 
 * //from   www  .  j  av a 2s  .co  m
 * @param res       WebScriptResponse
 * @param store       String
 * @param in       XML document containing multiple document contents to write
 */
@Override
protected void createDocuments(WebScriptResponse res, String store, InputStream in) {
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document;
        document = documentBuilder.parse(in);
        Element docEl = document.getDocumentElement();
        Transformer transformer = ADMRemoteStore.this.transformer.get();
        for (Node n = docEl.getFirstChild(); n != null; n = n.getNextSibling()) {
            if (!(n instanceof Element)) {
                continue;
            }
            final String path = ((Element) n).getAttribute("path");

            // Turn the first element child into a document
            Document doc = documentBuilder.newDocument();
            Node child;
            for (child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
                if (child instanceof Element) {
                    doc.appendChild(doc.importNode(child, true));
                    break;
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream(512);
            transformer.transform(new DOMSource(doc), new StreamResult(out));
            out.close();

            writeDocument(path, new ByteArrayInputStream(out.toByteArray()));
        }
    } catch (AccessDeniedException ae) {
        res.setStatus(Status.STATUS_UNAUTHORIZED);
        throw ae;
    } catch (FileExistsException feeErr) {
        res.setStatus(Status.STATUS_CONFLICT);
        throw feeErr;
    } catch (Exception e) {
        // various annoying checked SAX/IO exceptions related to XML processing can be thrown
        // none of them should occur if the XML document is well formed
        logger.error(e);
        res.setStatus(Status.STATUS_INTERNAL_SERVER_ERROR);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    }
}

From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java

/**
  * Builds the model to pass to the rendering engine.
  *///  www  . j a  va 2 s .com
protected Map<QName, Object> buildModel(final FormInstanceData formInstanceData, final Rendition rendition)
        throws IOException, SAXException {
    final String formInstanceDataAvmPath = formInstanceData.getPath();
    final String renditionAvmPath = rendition.getPath();
    final String parentPath = AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[0];
    final String sandboxUrl = AVMUtil.getPreviewURI(AVMUtil.getStoreName(formInstanceDataAvmPath));
    final String webappUrl = AVMUtil.buildWebappUrl(formInstanceDataAvmPath);
    final HashMap<QName, Object> model = new HashMap<QName, Object>();
    // add simple scalar parameters
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "date", namespacePrefixResolver), new Date());
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "avm_sandbox_url", namespacePrefixResolver),
            sandboxUrl);
    model.put(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER,
            new RenderingEngine.TemplateResourceResolver() {
                public InputStream resolve(final String name) {
                    final NodeService nodeService = RenderingEngineTemplateImpl.this.getServiceRegistry()
                            .getNodeService();
                    final NodeRef parentNodeRef = nodeService
                            .getPrimaryParent(RenderingEngineTemplateImpl.this.getNodeRef()).getParentRef();

                    if (logger.isDebugEnabled()) {
                        logger.debug("request to resolve resource " + name + " webapp url is " + webappUrl
                                + " and data dictionary workspace is " + parentNodeRef);
                    }

                    final NodeRef result = nodeService.getChildByName(parentNodeRef,
                            ContentModel.ASSOC_CONTAINS, name);
                    if (result != null) {
                        final ContentService contentService = RenderingEngineTemplateImpl.this
                                .getServiceRegistry().getContentService();
                        try {
                            if (logger.isDebugEnabled()) {
                                logger.debug("found " + name + " in data dictonary: " + result);
                            }

                            return contentService.getReader(result, ContentModel.PROP_CONTENT)
                                    .getContentInputStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    if (name.startsWith(WEBSCRIPT_PREFIX)) {
                        try {
                            final FacesContext facesContext = FacesContext.getCurrentInstance();
                            final ExternalContext externalContext = facesContext.getExternalContext();
                            final HttpServletRequest request = (HttpServletRequest) externalContext
                                    .getRequest();

                            String decodedName = URLDecoder.decode(name.substring(WEBSCRIPT_PREFIX.length()));
                            String rewrittenName = decodedName;

                            if (decodedName.contains("${storeid}")) {
                                rewrittenName = rewrittenName.replace("${storeid}",
                                        AVMUtil.getStoreName(formInstanceDataAvmPath));
                            } else {
                                if (decodedName.contains("{storeid}")) {
                                    rewrittenName = rewrittenName.replace("{storeid}",
                                            AVMUtil.getStoreName(formInstanceDataAvmPath));
                                }
                            }

                            if (decodedName.contains("${ticket}")) {
                                AuthenticationService authenticationService = Repository
                                        .getServiceRegistry(facesContext).getAuthenticationService();
                                final String ticket = authenticationService.getCurrentTicket();
                                rewrittenName = rewrittenName.replace("${ticket}", ticket);
                            } else {
                                if (decodedName.contains("{ticket}")) {
                                    AuthenticationService authenticationService = Repository
                                            .getServiceRegistry(facesContext).getAuthenticationService();
                                    final String ticket = authenticationService.getCurrentTicket();
                                    rewrittenName = rewrittenName.replace("{ticket}", ticket);
                                }
                            }

                            final String webscriptURI = (request.getScheme() + "://" + request.getServerName()
                                    + ':' + request.getServerPort() + request.getContextPath() + "/wcservice/"
                                    + rewrittenName);

                            if (logger.isDebugEnabled()) {
                                logger.debug("loading webscript: " + webscriptURI);
                            }

                            final URI uri = new URI(webscriptURI);
                            return uri.toURL().openStream();
                        } catch (Exception e) {
                            logger.warn(e);
                        }
                    }

                    try {
                        final String[] path = (name.startsWith("/") ? name.substring(1) : name).split("/");
                        for (int i = 0; i < path.length; i++) {
                            path[i] = URLEncoder.encode(path[i]);
                        }

                        final URI uri = new URI(webappUrl + '/' + StringUtils.join(path, '/'));

                        if (logger.isDebugEnabled()) {
                            logger.debug("loading " + uri);
                        }

                        return uri.toURL().openStream();
                    } catch (Exception e) {
                        logger.warn(e);
                        return null;
                    }
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "form_instance_data_file_name",
            namespacePrefixResolver), AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[1]);
    model.put(
            QName.createQName(NamespaceService.ALFRESCO_PREFIX, "rendition_file_name", namespacePrefixResolver),
            AVMNodeConverter.SplitBase(renditionAvmPath)[1]);
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver),
            parentPath);
    final FacesContext fc = FacesContext.getCurrentInstance();
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "request_context_path",
            namespacePrefixResolver), fc.getExternalContext().getRequestContextPath());

    // add methods
    final FormDataFunctions fdf = this.getFormDataFunctions();

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to encodeQuotes.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String text = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath);
                    }

                    final String result = fdf.encodeQuotes(text);
                    return result;
                }
            });

    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected 1 argument to parseXMLDocument.  got " + arguments.length);

                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }
                    String path = (String) arguments[0];
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocument('" + path + "'), parentPath = " + parentPath);
                    }

                    final Document d = fdf.parseXMLDocument(path);
                    return d != null ? d.getDocumentElement() : null;
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) throws IOException, SAXException {
                    if (arguments.length > 2) {
                        throw new IllegalArgumentException("expected exactly one or two arguments to "
                                + "parseXMLDocuments.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    if (arguments.length == 2 && !(arguments[1] instanceof String)) {
                        throw new ClassCastException("expected arguments[1] to be a " + String.class.getName()
                                + ".  got a " + arguments[1].getClass().getName() + ".");
                    }

                    String path = arguments.length == 2 ? (String) arguments[1] : "";
                    path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                    final String formName = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_parseXMLDocuments('" + formName + "','" + path + "'), parentPath = "
                                + parentPath);
                    }

                    final Map<String, Document> resultMap = fdf.parseXMLDocuments(formName, path);

                    if (logger.isDebugEnabled()) {
                        logger.debug("received " + resultMap.size() + " documents in " + path
                                + " with form name " + formName);
                    }

                    // create a root document for rooting all the results.  we do this
                    // so that each document root element has a common parent node
                    // and so that xpath axes work properly
                    final Document rootNodeDocument = XMLUtil.newDocument();
                    final Element rootNodeDocumentEl = rootNodeDocument.createElementNS(
                            NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list");
                    rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                            NamespaceService.ALFRESCO_URI);
                    rootNodeDocument.appendChild(rootNodeDocumentEl);

                    final List<Node> result = new ArrayList<Node>(resultMap.size());
                    for (Map.Entry<String, Document> e : resultMap.entrySet()) {
                        final Element documentEl = e.getValue().getDocumentElement();
                        documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX,
                                NamespaceService.ALFRESCO_URI);
                        documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI,
                                NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey());
                        final Node n = rootNodeDocument.importNode(documentEl, true);
                        rootNodeDocumentEl.appendChild(n);
                        result.add(n);
                    }
                    return result.toArray(new Node[result.size()]);
                }
            });
    model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "_getAVMPath", namespacePrefixResolver),
            new RenderingEngine.TemplateProcessorMethod() {
                public Object exec(final Object[] arguments) {
                    if (arguments.length != 1) {
                        throw new IllegalArgumentException(
                                "expected one argument to _getAVMPath.  got " + arguments.length);
                    }
                    if (!(arguments[0] instanceof String)) {
                        throw new ClassCastException("expected arguments[0] to be a " + String.class.getName()
                                + ".  got a " + arguments[0].getClass().getName() + ".");
                    }

                    final String path = (String) arguments[0];

                    if (logger.isDebugEnabled()) {
                        logger.debug("tpm_getAVMPAth('" + path + "'), parentPath = " + parentPath);
                    }

                    return AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE);
                }
            });

    // add the xml document
    model.put(RenderingEngine.ROOT_NAMESPACE, formInstanceData.getDocument());
    return model;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * Generate the XForm based on a user supplied XML Schema.
 *
 * @param instanceDocument The document source for the XML Schema.
 * @param schemaDocument Schema document
 * @param rootElementName Name of the root element
 * @param resourceBundle Strings to use//from w w w.  j  a v a  2s  .  com
 * @return The Document containing the XForm.
 * @throws org.chiba.tools.schemabuilder.FormBuilderException
 *          If an error occurs building the XForm.
 */
public Pair<Document, XSModel> buildXForm(final Document instanceDocument, final Document schemaDocument,
        String rootElementName, final ResourceBundle resourceBundle) throws FormBuilderException {
    final XSModel schema = SchemaUtil.parseSchema(schemaDocument, true);
    this.typeTree = SchemaUtil.buildTypeTree(schema);

    //refCounter = 0;
    this.counter.clear();

    final Document xformsDocument = this.createFormTemplate(rootElementName);

    //find form element: last element created
    final Element formSection = (Element) xformsDocument.getDocumentElement().getLastChild();
    final Element modelSection = (Element) xformsDocument.getDocumentElement()
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "model").item(0);

    //add XMLSchema if we use schema types      
    final Element importedSchemaDocumentElement = (Element) xformsDocument
            .importNode(schemaDocument.getDocumentElement(), true);
    importedSchemaDocumentElement.setAttributeNS(null, "id", "schema-1");

    NodeList nl = importedSchemaDocumentElement.getChildNodes();
    boolean hasExternalSchema = false;

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);
        if (current.getNamespaceURI() != null
                && current.getNamespaceURI().equals(NamespaceConstants.XMLSCHEMA_NS)) {
            String localName = current.getLocalName();
            if (localName.equals("include") || localName.equals("import")) {
                hasExternalSchema = true;
                break;
            }
        }
    }

    // ALF-8105 / ETWOTWO-1384: Only embed the schema if it does not reference externals
    if (!hasExternalSchema) {
        modelSection.appendChild(importedSchemaDocumentElement);
    }

    //check if target namespace
    final StringList schemaNamespaces = schema.getNamespaces();
    final HashMap<String, String> schemaNamespacesMap = new HashMap<String, String>();
    if (schemaNamespaces.getLength() != 0) {
        // will return null if no target namespace was specified
        this.targetNamespace = schemaNamespaces.item(0);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] using targetNamespace " + this.targetNamespace);

        for (int i = 0; i < schemaNamespaces.getLength(); i++) {
            if (schemaNamespaces.item(i) == null) {
                continue;
            }
            final String prefix = addNamespace(xformsDocument.getDocumentElement(),
                    schemaDocument.lookupPrefix(schemaNamespaces.item(i)), schemaNamespaces.item(i));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[buildXForm] adding namespace " + schemaNamespaces.item(i) + " with prefix "
                        + prefix + " to xform and default instance element");
            }
            schemaNamespacesMap.put(prefix, schemaNamespaces.item(i));
        }
    }

    //if target namespace & we use the schema types: add it to form ns declarations
    //   if (this.targetNamespace != null && this.targetNamespace.length() != 0)
    //       envelopeElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    //                  "xmlns:schema",
    //                  this.targetNamespace);

    final XSElementDeclaration rootElementDecl = schema.getElementDeclaration(rootElementName,
            this.targetNamespace);
    if (rootElementDecl == null) {
        throw new FormBuilderException("Invalid root element tag name [" + rootElementName
                + ", targetNamespace = " + this.targetNamespace + "]");
    }

    rootElementName = this.getElementName(rootElementDecl, xformsDocument);
    final Element instanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":instance");
    modelSection.appendChild(instanceElement);
    this.setXFormsId(instanceElement);

    final Element defaultInstanceDocumentElement = xformsDocument.createElement(rootElementName);
    addNamespace(defaultInstanceDocumentElement, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
    if (this.targetNamespace != null) {
        final String targetNamespacePrefix = schemaDocument.lookupPrefix(this.targetNamespace);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[buildXForm] adding target namespace " + this.targetNamespace + " with prefix "
                    + targetNamespacePrefix + " to xform and default instance element");
        }

        addNamespace(defaultInstanceDocumentElement, targetNamespacePrefix, this.targetNamespace);
        addNamespace(xformsDocument.getDocumentElement(), targetNamespacePrefix, this.targetNamespace);
    }

    Element prototypeInstanceElement = null;
    if (instanceDocument == null || instanceDocument.getDocumentElement() == null) {
        instanceElement.appendChild(defaultInstanceDocumentElement);
    } else {
        Element instanceDocumentElement = instanceDocument.getDocumentElement();
        if (!instanceDocumentElement.getNodeName().equals(rootElementName)) {
            throw new IllegalArgumentException("instance document root tag name invalid.  " + "expected "
                    + rootElementName + ", got " + instanceDocumentElement.getNodeName());
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] importing rootElement from other document");

        prototypeInstanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":instance");
        modelSection.appendChild(prototypeInstanceElement);
        this.setXFormsId(prototypeInstanceElement, "instance_prototype");
        prototypeInstanceElement.appendChild(defaultInstanceDocumentElement);
    }

    final Element rootGroup = this.addElement(xformsDocument, modelSection, defaultInstanceDocumentElement,
            formSection, schema, rootElementDecl, "/" + this.getElementName(rootElementDecl, xformsDocument),
            new SchemaUtil.Occurrence(1, 1), resourceBundle);
    if (rootGroup.getNodeName() != NamespaceConstants.XFORMS_PREFIX + ":group") {
        throw new FormBuilderException("Expected root form element to be a " + NamespaceConstants.XFORMS_PREFIX
                + ":group, not a " + rootGroup.getNodeName() + ".  Ensure that "
                + this.getElementName(rootElementDecl, xformsDocument)
                + " is a concrete type that has no extensions.  "
                + "Types with extensions are not supported for " + "the root element of a form.");
    }
    this.setXFormsId(rootGroup, "alfresco-xforms-root-group");

    if (prototypeInstanceElement != null) {
        Schema2XForms.rebuildInstance(prototypeInstanceElement, instanceDocument, instanceElement,
                schemaNamespacesMap);
    }

    this.createSubmitElements(xformsDocument, modelSection, rootGroup);
    this.createTriggersForRepeats(xformsDocument, rootGroup);

    final Comment comment = xformsDocument.createComment(
            "This XForm was generated by " + this.getClass().getName() + " on " + (new Date()) + " from the '"
                    + rootElementName + "' element of the '" + this.targetNamespace + "' XML Schema.");
    xformsDocument.getDocumentElement().insertBefore(comment,
            xformsDocument.getDocumentElement().getFirstChild());
    xformsDocument.normalizeDocument();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[buildXForm] Returning XForm =\n" + XMLUtil.toString(xformsDocument));

    return new Pair<Document, XSModel>(xformsDocument, schema);
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }//from  w  w  w  . java2  s. c  o m

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.alfresco.web.forms.xforms.XFormsBean.java

public void handleSubmit(Node result) {
    final Document instanceData = this.getXformsSession().getFormInstanceData();
    Element documentElement = instanceData.getDocumentElement();
    if (documentElement != null) {
        instanceData.removeChild(documentElement);
    }// w w  w.  j  a  va2 s  . c o m
    if (result instanceof Document) {
        result = ((Document) result).getDocumentElement();
    }
    documentElement = (Element) instanceData.importNode(result.cloneNode(true), true);
    Schema2XForms.removePrototypeNodes(documentElement);
    instanceData.appendChild(documentElement);
    instanceData.normalizeDocument();
}