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:org.eclipse.swordfish.internal.core.integration.nmr.SwordfishExchangeListener.java

private void processOutgoingRequestHeaders(Exchange exchange) {
    EndpointMetadata<?> metadata = (EndpointMetadata<?>) exchange
            .getProperty(EndpointMetadata.ENDPOINT_METADATA);
    if (metadata == null) {
        return;/*from  w  w w.j a  v a 2 s.c  o  m*/
    }
    DocumentFragment policy = metadata.toXml();

    // create wsa:ReplyTo SOAP header containing traded policy
    Document doc = XmlUtil.getDocumentBuilder().newDocument();
    Element replyTo = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_REPLY_TO_NAME);
    replyTo.setPrefix(JbiConstants.WSA_PREFIX);

    Element addr = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_ADDRESS_NAME);
    addr.setPrefix(JbiConstants.WSA_PREFIX);
    addr.appendChild(doc.createTextNode(JbiConstants.WSA_ANONYMOUS));
    replyTo.appendChild(addr);

    Element refParams = doc.createElementNS(JbiConstants.WSA_NS, JbiConstants.WSA_REFERENCE_PARAMS_NAME);
    refParams.setPrefix(JbiConstants.WSA_PREFIX);
    Node policyNode = doc.importNode(policy, true);
    refParams.appendChild(policyNode);
    replyTo.appendChild(refParams);

    DocumentFragment replyToHeader = doc.createDocumentFragment();
    replyToHeader.appendChild(replyTo);

    Map<QName, DocumentFragment> headers = new HashMap<QName, DocumentFragment>();

    QName policyKey = new QName(policy.getFirstChild().getNamespaceURI(),
            policy.getFirstChild().getLocalName());
    headers.put(policyKey, policy);
    headers.put(JbiConstants.WSA_REPLY_TO_QNAME, replyToHeader);

    exchange.getIn(false).setHeader(JbiConstants.SOAP_HEADERS, headers);
}

From source file:org.eclipse.thym.core.plugin.test.InstallActionsTest.java

@Test
public void testXMLConfigFileActionInstall() throws FileNotFoundException, IOException, CoreException,
        SAXException, ParserConfigurationException, XPathExpressionException {

    final File target = TestUtils.createTempFile("AndroidManifest.xml");
    final String xml = "<config-file target=\"AndroidManifest.xml\" parent=\"/manifest\">"
            + "<uses-permission android:name=\"android.permission.BLUETOOTH\" />"
            + "<uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\" />" + "</config-file >";
    final String parentExpression = "/manifest";

    XMLConfigFileAction action = new XMLConfigFileAction(target, parentExpression, xml);
    action.install();//ww w . ja va 2 s .  c om

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(target);
    Document node = db.parse(new InputSource(new StringReader(xml)));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Node parentNode = (Node) xpath.evaluate(parentExpression, doc, XPathConstants.NODE);
    assertNotNull(parentNode);

    NodeList alienChildren = node.getDocumentElement().getChildNodes();

    Node[] importedNodes = new Node[alienChildren.getLength()];
    for (int i = 0; i < alienChildren.getLength(); i++) {
        importedNodes[i] = doc.importNode(alienChildren.item(i), true);
    }

    NodeList childNodes = parentNode.getChildNodes();
    int found = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node current = childNodes.item(i);
        for (int j = 0; j < importedNodes.length; j++) {
            if (current.isEqualNode(importedNodes[j])) {
                found++;
            }
        }
    }
    assertEquals(importedNodes.length, found); // found all imported nodes
}

From source file:org.eclipse.thym.core.plugin.test.InstallActionsTest.java

@Test
public void testXMLConfigFileActionUnInstall()
        throws IOException, CoreException, ParserConfigurationException, SAXException, XPathException {
    final File target = TestUtils.createTempFile("AndroidManifest.xml");
    final String xml = "<config-file target=\"AndroidManifest.xml\" parent=\"/manifest\">"
            + "<uses-permission android:name=\"android.permission.INTERNET\" />"
            + "<uses-permission android:name=\"android.permission.RECEIVE_SMS\" />" + "</config-file >";
    final String parentExpression = "/manifest";

    XMLConfigFileAction action = new XMLConfigFileAction(target, parentExpression, xml);
    action.unInstall();//from  w  w w .  ja v  a  2s.c  om

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(target);
    Document node = db.parse(new InputSource(new StringReader(xml)));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Node parentNode = (Node) xpath.evaluate(parentExpression, doc, XPathConstants.NODE);
    assertNotNull(parentNode);

    NodeList alienChildren = node.getDocumentElement().getChildNodes();

    Node[] importedNodes = new Node[alienChildren.getLength()];
    for (int i = 0; i < alienChildren.getLength(); i++) {
        importedNodes[i] = doc.importNode(alienChildren.item(i), true);
    }

    NodeList childNodes = parentNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node current = childNodes.item(i);
        for (int j = 0; j < importedNodes.length; j++) {
            assertFalse("Found a node that is not suppposed to be here", current.isEqualNode(importedNodes[j]));
        }
    }
}

From source file:org.etudes.component.app.melete.MeleteSecurityServiceImpl.java

/**
 * {@inheritDoc}/*from   ww  w. j a  v  a2 s  .  com*/
 */
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames,
        Map userIdTrans, Set userListAllowImport) {
    logger.debug("merge of melete" + siteId + "," + fromSiteId + "," + root.toString());
    int count = 0;
    try {
        org.w3c.dom.Document w3doc = Xml.createDocument();
        org.w3c.dom.Element w3root = (org.w3c.dom.Element) w3doc.importNode(root, true);
        w3doc.appendChild(w3root);

        //convert to dom4j doc
        org.dom4j.io.DOMReader domReader = new org.dom4j.io.DOMReader();
        org.dom4j.Document domDoc = domReader.read(w3doc);
        logger.debug("archive str " + archivePath + archivePath.lastIndexOf(File.separator));
        archivePath = archivePath.substring(0, archivePath.lastIndexOf("/"));
        count = getMeleteImportService().mergeAndBuildModules(domDoc, archivePath, siteId);
    } catch (Exception e) {
        e.printStackTrace();
        return "error on merging modules content";
    }
    return "merging modules content: (" + count + ") modules \n";
}

From source file:org.gvnix.flex.FlexOperationsImpl.java

private void fixBrokenFlexPlugin() {
    String pomPath = getPathResolver().getIdentifier(LogicalPath.getInstance(Path.ROOT, ""), "pom.xml");

    Document pomDoc;
    try {/*from w w w  .ja  v  a 2  s . co  m*/
        pomDoc = XmlUtils.getDocumentBuilder().parse(this.fileManager.getInputStream(pomPath));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element pluginDependencyElement = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[artifactId='flexmojos-maven-plugin']/dependencies/dependency",
            pomDoc.getDocumentElement());
    Validate.notNull(pluginDependencyElement,
            "Could not find the flexmojos-maven-plugin's dependency element.");
    Element newTypeNode = pomDoc.createElement("type");
    newTypeNode.setTextContent("pom");
    pluginDependencyElement.appendChild(newTypeNode);

    Element pluginExecutionElement = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[artifactId='flexmojos-maven-plugin']/executions/execution",
            pomDoc.getDocumentElement());
    InputStream templateInputStream = FileUtils.getInputStream(getClass(), "pluginsFix.xml");
    Document configurationTemplate;
    try {
        configurationTemplate = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element configurationElement = XmlUtils.findFirstElement("/configuration",
            configurationTemplate.getDocumentElement());
    Validate.notNull(configurationElement, "flexmojos-maven-plugin configuration did not parse as expected.");

    pluginExecutionElement.appendChild(pomDoc.importNode(configurationElement, true));

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, pomDoc);
    String pomContent = byteArrayOutputStream.toString();

    try {
        this.fileManager.createOrUpdateTextFileIfRequired(pomPath, pomContent, false);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.gvnix.web.theme.roo.addon.ThemeOperationsImpl.java

/**
 * Update pom.xml adding a plugin maven-resources-plugin or, if it exists,
 * just adding executions component//from www.  jav  a2 s  .c o  m
 * <p>
 * TODO
 * <p>
 * This source is so because Roo doesn't support Execution with
 * Configuration. When it support the thing we could change this code with
 * something like:
 * <code>projectOperations.updateBuildPlugin(pluginWithExecutionConfigured)</code>
 * This issue is solved in 1.2.0.M1 as ROO-2658 says
 */
private void updatePomFile() {

    Element configuration = org.springframework.roo.support.util.XmlUtils.getConfiguration(getClass());
    Element pluginElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("/configuration/plugin", configuration);

    Plugin plugin = new Plugin(pluginElement);

    Element executionElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("executions/execution", pluginElement);
    Execution pluginExecution = createExecutionFromElement(executionElement);

    String pom = projectOperations.getPathResolver().getIdentifier(LogicalPath.getInstance(Path.ROOT, ""),
            "pom.xml");
    Document pomDoc = org.springframework.roo.support.util.XmlUtils.readXml(fileManager.getInputStream(pom));
    Element root = pomDoc.getDocumentElement();

    // Plugins section: find or create if not exists
    Element build = org.springframework.roo.support.util.XmlUtils.findFirstElement("/project/build", root);
    Element plugins = null;
    if (build != null) {
        plugins = org.springframework.roo.support.util.XmlUtils.findFirstElement("plugins", build);
        if (plugins != null) {
            String pluginXPath = "plugin[groupId='".concat(plugin.getGroupId()).concat("' and artifactId='")
                    .concat(plugin.getArtifactId()).concat("' and version='").concat(plugin.getVersion())
                    .concat("']");
            Element existingPluginElement = org.springframework.roo.support.util.XmlUtils
                    .findFirstElement(pluginXPath, plugins);
            if (existingPluginElement != null) {
                String pluginExecutionXPath = "executions/execution[id='".concat(pluginExecution.getId())
                        .concat("' and phase='").concat(pluginExecution.getPhase()).concat("' and goals[goal='")
                        .concat(pluginExecution.getGoals().get(0)).concat("']]");
                Element existingPluginExecutionElement = org.springframework.roo.support.util.XmlUtils
                        .findFirstElement(pluginExecutionXPath, existingPluginElement);
                if (existingPluginExecutionElement == null) {
                    Element pluginExecutionsElement = org.springframework.roo.support.util.XmlUtils
                            .findFirstElement("executions", existingPluginElement);
                    if (pluginExecutionsElement == null) {
                        pluginExecutionsElement = new XmlElementBuilder("executions", pomDoc).build();
                    }
                    Node importedExecutionPlugin = pomDoc.importNode(executionElement, true);

                    pluginExecutionsElement.appendChild(importedExecutionPlugin);
                    existingPluginElement.appendChild(pluginExecutionsElement);
                }
            } else {
                // create maven-resources-plugin
                Node importedPlugin = pomDoc.importNode(pluginElement, true);
                plugins.appendChild(importedPlugin);
            }
        } else {
            // create plugins with maven-resources-plugin
            plugins = pomDoc.createElement("plugins");
            Node importedPlugin = pomDoc.importNode(pluginElement, true);
            plugins.appendChild(importedPlugin);
            build.appendChild(plugins);
        }
    } else {
        // create build and plugins with maven-resources-plugin
        build = pomDoc.createElement("build");
        plugins = pomDoc.createElement("plugins");
        Node importedPlugin = pomDoc.importNode(pluginElement, true);
        plugins.appendChild(importedPlugin);
        build.appendChild(plugins);
        root.appendChild(build);
    }

    fileManager.createOrUpdateTextFileIfRequired(pom,
            org.springframework.roo.support.util.XmlUtils.nodeToString(pomDoc), true);

}

From source file:org.infoglue.calendar.controllers.ContentTypeDefinitionController.java

/**
 * This method validates the current content type and updates it to be valid in the future.
 *//*from w w w.  j  a va2s. c o  m*/

public ContentTypeDefinition validateAndUpdateContentType(Long id, ContentTypeDefinition contentTypeDefinition,
        Session session) {
    try {
        boolean isModified = false;

        InputSource xmlSource = new InputSource(new StringReader(contentTypeDefinition.getSchemaValue()));
        DOMParser parser = new DOMParser();
        parser.parse(xmlSource);
        Document document = parser.getDocument();

        //Set the new versionId
        String rootXPath = "/xs:schema";
        NodeList schemaList = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                rootXPath);
        for (int i = 0; i < schemaList.getLength(); i++) {
            Element schemaElement = (Element) schemaList.item(i);
            if (schemaElement.getAttribute("version") == null
                    || schemaElement.getAttribute("version").equalsIgnoreCase("")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.0");

                //First check out if the old/wrong definitions are there and delete them
                String definitionsXPath = "/xs:schema/xs:simpleType";
                NodeList definitionList = org.apache.xpath.XPathAPI
                        .selectNodeList(document.getDocumentElement(), definitionsXPath);
                for (int j = 0; j < definitionList.getLength(); j++) {
                    Element childElement = (Element) definitionList.item(j);
                    if (!childElement.getAttribute("name").equalsIgnoreCase("assetKeys"))
                        childElement.getParentNode().removeChild(childElement);
                }

                //Now we create the new definitions
                Element textFieldDefinition = document.createElement("xs:simpleType");
                textFieldDefinition.setAttribute("name", "textfield");
                Element restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                Element maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                textFieldDefinition.appendChild(restriction);
                schemaElement.insertBefore(textFieldDefinition, schemaElement.getFirstChild());

                Element selectDefinition = document.createElement("xs:simpleType");
                selectDefinition.setAttribute("name", "select");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                selectDefinition.appendChild(restriction);
                schemaElement.insertBefore(selectDefinition, schemaElement.getFirstChild());

                Element checkboxDefinition = document.createElement("xs:simpleType");
                checkboxDefinition.setAttribute("name", "checkbox");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                checkboxDefinition.appendChild(restriction);
                schemaElement.insertBefore(checkboxDefinition, schemaElement.getFirstChild());

                Element radiobuttonDefinition = document.createElement("xs:simpleType");
                radiobuttonDefinition.setAttribute("name", "radiobutton");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                radiobuttonDefinition.appendChild(restriction);
                schemaElement.insertBefore(radiobuttonDefinition, schemaElement.getFirstChild());

                Element textareaDefinition = document.createElement("xs:simpleType");
                textareaDefinition.setAttribute("name", "textarea");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                textareaDefinition.appendChild(restriction);
                schemaElement.insertBefore(textareaDefinition, schemaElement.getFirstChild());

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    if (childElement.getAttribute("type").equals("shortString")) {
                        childElement.setAttribute("type", "textfield");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("shortText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("fullText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("hugeText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    }

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        Element annotationElement = (Element) annotationNodeList.item(0);
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            Element appinfoElement = (Element) appinfoNodeList.item(0);
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);
                                addParameterElement(paramsElement, "title", "0");
                                addParameterElement(paramsElement, "description", "0");
                                addParameterElement(paramsElement, "class", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElement(paramsElement, "values", "1");
                                }

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElement(paramsElement, "width", "0", "700");
                                    addParameterElement(paramsElement, "height", "0", "150");
                                    addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                    addParameterElement(paramsElement, "enableTemplateEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableContentRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                            "false");
                                }
                            } else {
                                Element paramsElement = document.createElement("params");

                                addParameterElement(paramsElement, "title", "0");
                                addParameterElement(paramsElement, "description", "0");
                                addParameterElement(paramsElement, "class", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElement(paramsElement, "values", "1");
                                }

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElement(paramsElement, "width", "0", "700");
                                    addParameterElement(paramsElement, "height", "0", "150");
                                    addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                    addParameterElement(paramsElement, "enableTemplateEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableContentRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                            "false");
                                }

                                appinfoElement.appendChild(paramsElement);
                                isModified = true;
                            }
                        } else {
                            Element appInfo = document.createElement("xs:appinfo");
                            Element paramsElement = document.createElement("params");

                            addParameterElement(paramsElement, "title", "0");
                            addParameterElement(paramsElement, "description", "0");
                            addParameterElement(paramsElement, "class", "0");

                            if (inputTypeId.equalsIgnoreCase("checkbox")
                                    || inputTypeId.equalsIgnoreCase("select")
                                    || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                addParameterElement(paramsElement, "values", "1");
                            }

                            if (inputTypeId.equalsIgnoreCase("textarea")) {
                                addParameterElement(paramsElement, "width", "0", "700");
                                addParameterElement(paramsElement, "height", "0", "150");
                                addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                addParameterElement(paramsElement, "enableTemplateEditor", "0", "false");
                                addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                addParameterElement(paramsElement, "enableContentRelationEditor", "0", "false");
                                addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                        "false");
                                addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                        "false");
                            }

                            annotationElement.appendChild(appInfo);
                            appInfo.appendChild(paramsElement);
                            isModified = true;
                        }
                    } else {
                        Element annotation = document.createElement("xs:annotation");
                        Element appInfo = document.createElement("xs:appinfo");
                        Element paramsElement = document.createElement("params");

                        addParameterElement(paramsElement, "title", "0");
                        addParameterElement(paramsElement, "description", "0");
                        addParameterElement(paramsElement, "class", "0");

                        if (inputTypeId.equalsIgnoreCase("checkbox") || inputTypeId.equalsIgnoreCase("select")
                                || inputTypeId.equalsIgnoreCase("radiobutton")) {
                            addParameterElement(paramsElement, "values", "1");
                        }

                        if (inputTypeId.equalsIgnoreCase("textarea")) {
                            addParameterElement(paramsElement, "width", "0", "700");
                            addParameterElement(paramsElement, "height", "0", "150");
                            addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                            addParameterElement(paramsElement, "enableTemplateEditor", "0", "false");
                            addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                            addParameterElement(paramsElement, "enableContentRelationEditor", "0", "false");
                            addParameterElement(paramsElement, "enableStructureRelationEditor", "0", "false");
                            addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0", "false");
                        }

                        childElement.appendChild(annotation);
                        annotation.appendChild(appInfo);
                        appInfo.appendChild(paramsElement);
                        isModified = true;
                    }

                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.0")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.1");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElementIfNotExists(paramsElement, "width", "0", "700");
                                    addParameterElementIfNotExists(paramsElement, "height", "0", "150");
                                    addParameterElementIfNotExists(paramsElement, "enableWYSIWYG", "0",
                                            "false");
                                    addParameterElementIfNotExists(paramsElement, "enableTemplateEditor", "0",
                                            "false");
                                    addParameterElementIfNotExists(paramsElement, "enableFormEditor", "0",
                                            "false");
                                    addParameterElementIfNotExists(paramsElement, "enableContentRelationEditor",
                                            "0", "false");
                                    addParameterElementIfNotExists(paramsElement,
                                            "enableStructureRelationEditor", "0", "false");
                                    addParameterElementIfNotExists(paramsElement,
                                            "activateExtendedEditorOnLoad", "0", "false");

                                    isModified = true;
                                }
                            }
                        }
                    }
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.1")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.2");

                //Now we deal with adding the validation part if not existent
                String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']";
                Node formNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                        validatorsXPath);
                if (formNode == null) {
                    String schemaXPath = "/xs:schema";
                    Node schemaNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                            schemaXPath);

                    Element element = (Element) schemaNode;

                    String validationXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:complexType name=\"Validation\" xmlns:xi=\"http://www.w3.org/2001/XInclude\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><xs:annotation><xs:appinfo><form-validation><global><validator name=\"required\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRequired\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field\" msg=\"300\"/><validator name=\"requiredif\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRequiredIf\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field,org.apache.commons.validator.Validator\" msg=\"315\"/><validator name=\"matchRegexp\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRegexp\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field\" msg=\"300\"/></global><formset><form name=\"requiredForm\"></form></formset></form-validation></xs:appinfo></xs:annotation></xs:complexType>";

                    InputSource validationXMLSource = new InputSource(new StringReader(validationXML));
                    DOMParser parser2 = new DOMParser();
                    parser2.parse(validationXMLSource);
                    Document document2 = parser2.getDocument();

                    Node node = document.importNode(document2.getDocumentElement(), true);
                    element.appendChild(node);
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.2")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.3");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                addParameterElementIfNotExists(paramsElement, "initialData", "0", "");
                                isModified = true;
                            }
                        }
                    }
                }

            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.3")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.4");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                addParameterElementIfNotExists(paramsElement, "enableComponentPropertiesEditor",
                                        "0", "false");

                                isModified = true;
                            }
                        }
                    }
                }

            }

        }

        if (isModified) {
            StringBuffer sb = new StringBuffer();
            XMLHelper.serializeDom(document.getDocumentElement(), sb);
            contentTypeDefinition.setSchemaValue(sb.toString());

            update(id, contentTypeDefinition, session);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return contentTypeDefinition;
}

From source file:org.infoglue.cms.applications.structuretool.actions.ViewSiteNodePageComponentsAction.java

/**
 * This method adds a component to the page. 
 *//*ww w .j a  va  2  s. c  o m*/

public String doAddOrReplaceComponent() throws Exception {
    logger.info("************************************************************");
    logger.info("* ADDING OR REPLACING COMPONENT                            *");
    logger.info("************************************************************");
    logger.info("siteNodeId:" + this.siteNodeId);
    logger.info("languageId:" + this.languageId);
    logger.info("contentId:" + this.contentId);
    logger.info("queryString:" + this.getRequest().getQueryString());
    logger.info("parentComponentId:" + this.parentComponentId);
    //logger.info("componentId:" + this.componentId);
    logger.info("slotId:" + this.slotId);
    logger.info("specifyBaseTemplate:" + this.specifyBaseTemplate);
    logger.info("pagePartContentId:" + this.pagePartContentId);

    try {
        initialize();

        logger.info("masterLanguageId:" + this.masterLanguageVO.getId());

        Integer newComponentId = new Integer(0);

        String componentXML = getPageComponentsString(siteNodeId, this.masterLanguageVO.getId());

        Document document = XMLHelper.readDocumentFromByteArray(componentXML.getBytes("UTF-8"));
        String componentXPath = "//component[@id=" + this.parentComponentId + "]";

        Node componentNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                componentXPath);
        if (componentNode != null) {
            //Element componentElement = (Element)componentNode;

            String componentsXPath = "//component";
            NodeList nodes = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                    componentsXPath);
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                if (new Integer(element.getAttribute("id")).intValue() > newComponentId.intValue())
                    newComponentId = new Integer(element.getAttribute("id"));
            }
            newComponentId = new Integer(newComponentId.intValue() + 1);

            NodeList childNodes = componentNode.getChildNodes();
            logger.info("childNodes:" + childNodes.getLength());

            Node child = componentNode.getFirstChild();
            while (child != null) {
                logger.info("Removing:" + child);
                componentNode.removeChild(child);
                child = componentNode.getFirstChild();
            }

            logger.info("childNodes:" + childNodes.getLength());
            //StringBuffer sb = new StringBuffer();
            //XMLHelper.serializeDom(componentNode, sb);
            //logger.info("SB:" + sb);

            if (this.pagePartContentId != null) {
                ContentVersionVO pagePartContentVersionVO = ContentVersionController
                        .getContentVersionController()
                        .getLatestActiveContentVersionVO(this.pagePartContentId, this.masterLanguageVO.getId());
                String componentStructure = ContentVersionController.getContentVersionController()
                        .getAttributeValue(pagePartContentVersionVO.getId(), "ComponentStructure", false);

                componentStructure = componentStructure.replaceAll(" isInherited=\"true\"", "");
                componentStructure = componentStructure.replaceAll(" pagePartTemplateContentId=\"-1\"", "");
                componentStructure = componentStructure
                        .replaceAll("<property name=\"pagePartContentId\" path=\".*?\"></property>", "");
                componentStructure = componentStructure
                        .replaceAll("<property name=\"pagePartContentId\" path=\".*?\"/>", "");
                componentStructure = componentStructure.replaceAll("<properties>",
                        "<properties><property name=\"pagePartContentId\" path=\"" + pagePartContentId
                                + "\"/>");
                logger.info("componentStructure:" + componentStructure);

                Document componentStructureDocument = XMLHelper
                        .readDocumentFromByteArray(componentStructure.getBytes("UTF-8"));
                Node rootNode = componentStructureDocument.getDocumentElement();

                componentNode.appendChild(document.importNode(rootNode, true));

                String modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();

                ContentVO contentVO = NodeDeliveryController
                        .getNodeDeliveryController(siteNodeId, this.masterLanguageVO.getId(), contentId)
                        .getBoundContent(this.getInfoGluePrincipal(), siteNodeId, this.masterLanguageVO.getId(),
                                true, "Meta information", DeliveryContext.getDeliveryContext());
                ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController()
                        .getLatestActiveContentVersionVO(contentVO.getId(), this.masterLanguageVO.getId());

                ContentVersionController.getContentVersionController().updateAttributeValue(
                        contentVersionVO.getContentVersionId(), "ComponentStructure", modifiedXML,
                        this.getInfoGluePrincipal());
            }
        }

        logger.info("newComponentId:" + newComponentId);

        this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId=" + this.siteNodeId
                + "&languageId=" + this.languageId + "&contentId=" + this.contentId + "&focusElementId="
                + newComponentId + "&activatedComponentId=" + newComponentId + "&componentContentId="
                + this.componentId + "&showSimple=" + this.showSimple;
        //this.getResponse().sendRedirect(url);      

        this.url = this.getResponse().encodeURL(url);
        this.getResponse().sendRedirect(url);
        return NONE;
    } catch (Exception e) {
        logger.error("Error adding/changing component:" + e.getMessage());
        logger.warn("Error adding/changing component:" + e.getMessage(), e);
        return ERROR;
    }
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController.java

/**
 * This method validates the current content type and updates it to be valid in the future.
 *///w  w w . j  a  v a 2 s  . co  m

public ContentTypeDefinitionVO validateAndUpdateContentType(ContentTypeDefinitionVO contentTypeDefinitionVO) {
    try {
        boolean isModified = false;

        InputSource xmlSource = new InputSource(new StringReader(contentTypeDefinitionVO.getSchemaValue()));
        DOMParser parser = new DOMParser();
        parser.parse(xmlSource);
        Document document = parser.getDocument();

        //Set the new versionId
        String rootXPath = "/xs:schema";
        NodeList schemaList = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                rootXPath);
        for (int i = 0; i < schemaList.getLength(); i++) {
            Element schemaElement = (Element) schemaList.item(i);
            if (schemaElement.getAttribute("version") == null
                    || schemaElement.getAttribute("version").equalsIgnoreCase("")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.0");

                //First check out if the old/wrong definitions are there and delete them
                String definitionsXPath = "/xs:schema/xs:simpleType";
                NodeList definitionList = org.apache.xpath.XPathAPI
                        .selectNodeList(document.getDocumentElement(), definitionsXPath);
                for (int j = 0; j < definitionList.getLength(); j++) {
                    Element childElement = (Element) definitionList.item(j);
                    if (!childElement.getAttribute("name").equalsIgnoreCase("assetKeys"))
                        childElement.getParentNode().removeChild(childElement);
                }

                //Now we create the new definitions
                Element textFieldDefinition = document.createElement("xs:simpleType");
                textFieldDefinition.setAttribute("name", "textfield");
                Element restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                Element maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                textFieldDefinition.appendChild(restriction);
                schemaElement.insertBefore(textFieldDefinition, schemaElement.getFirstChild());

                Element selectDefinition = document.createElement("xs:simpleType");
                selectDefinition.setAttribute("name", "select");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                selectDefinition.appendChild(restriction);
                schemaElement.insertBefore(selectDefinition, schemaElement.getFirstChild());

                Element checkboxDefinition = document.createElement("xs:simpleType");
                checkboxDefinition.setAttribute("name", "checkbox");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                checkboxDefinition.appendChild(restriction);
                schemaElement.insertBefore(checkboxDefinition, schemaElement.getFirstChild());

                Element radiobuttonDefinition = document.createElement("xs:simpleType");
                radiobuttonDefinition.setAttribute("name", "radiobutton");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                radiobuttonDefinition.appendChild(restriction);
                schemaElement.insertBefore(radiobuttonDefinition, schemaElement.getFirstChild());

                Element textareaDefinition = document.createElement("xs:simpleType");
                textareaDefinition.setAttribute("name", "textarea");
                restriction = document.createElement("xs:restriction");
                restriction.setAttribute("base", "xs:string");
                maxLength = document.createElement("xs:maxLength");
                maxLength.setAttribute("value", "100");
                restriction.appendChild(maxLength);
                textareaDefinition.appendChild(restriction);
                schemaElement.insertBefore(textareaDefinition, schemaElement.getFirstChild());

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    if (childElement.getAttribute("type").equals("shortString")) {
                        childElement.setAttribute("type", "textfield");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("shortText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("fullText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    } else if (childElement.getAttribute("type").equals("hugeText")) {
                        childElement.setAttribute("type", "textarea");
                        isModified = true;
                    }

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        Element annotationElement = (Element) annotationNodeList.item(0);
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            Element appinfoElement = (Element) appinfoNodeList.item(0);
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);
                                addParameterElement(paramsElement, "title", "0");
                                addParameterElement(paramsElement, "description", "0");
                                addParameterElement(paramsElement, "class", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElement(paramsElement, "widget", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElement(paramsElement, "dataProviderClass", "");
                                    addParameterElement(paramsElement, "dataProviderParameters", "");
                                    addParameterElement(paramsElement, "values", "1");
                                }

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElement(paramsElement, "width", "0", "700");
                                    addParameterElement(paramsElement, "height", "0", "150");
                                    addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                    addParameterElement(paramsElement, "WYSIWYGToolbar", "0", "Default");
                                    addParameterElement(paramsElement, "WYSIWYGExtraConfig", "0", "");
                                    addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableContentRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                            "false");
                                }
                            } else {
                                Element paramsElement = document.createElement("params");

                                addParameterElement(paramsElement, "title", "0");
                                addParameterElement(paramsElement, "description", "0");
                                addParameterElement(paramsElement, "class", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElement(paramsElement, "widget", "0");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElement(paramsElement, "dataProviderClass", "");
                                    addParameterElement(paramsElement, "dataProviderParameters", "");
                                    addParameterElement(paramsElement, "values", "1");
                                }

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElement(paramsElement, "width", "0", "700");
                                    addParameterElement(paramsElement, "height", "0", "150");
                                    addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                    addParameterElement(paramsElement, "WYSIWYGToolbar", "0", "Default");
                                    addParameterElement(paramsElement, "WYSIWYGExtraConfig", "0", "");
                                    addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                    addParameterElement(paramsElement, "enableContentRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                            "false");
                                    addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                            "false");
                                }

                                appinfoElement.appendChild(paramsElement);
                                isModified = true;
                            }
                        } else {
                            Element appInfo = document.createElement("xs:appinfo");
                            Element paramsElement = document.createElement("params");

                            addParameterElement(paramsElement, "title", "0");
                            addParameterElement(paramsElement, "description", "0");
                            addParameterElement(paramsElement, "class", "0");

                            if (inputTypeId.equalsIgnoreCase("checkbox"))
                                addParameterElement(paramsElement, "widget", "0");

                            if (inputTypeId.equalsIgnoreCase("checkbox")
                                    || inputTypeId.equalsIgnoreCase("select")
                                    || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                addParameterElement(paramsElement, "dataProviderClass", "");
                                addParameterElement(paramsElement, "dataProviderParameters", "");
                                addParameterElement(paramsElement, "values", "1");
                            }

                            if (inputTypeId.equalsIgnoreCase("textarea")) {
                                addParameterElement(paramsElement, "width", "0", "700");
                                addParameterElement(paramsElement, "height", "0", "150");
                                addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                                addParameterElement(paramsElement, "WYSIWYGToolbar", "0", "Default");
                                addParameterElement(paramsElement, "WYSIWYGExtraConfig", "0", "");
                                addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                                addParameterElement(paramsElement, "enableContentRelationEditor", "0", "false");
                                addParameterElement(paramsElement, "enableStructureRelationEditor", "0",
                                        "false");
                                addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0",
                                        "false");
                            }

                            annotationElement.appendChild(appInfo);
                            appInfo.appendChild(paramsElement);
                            isModified = true;
                        }
                    } else {
                        Element annotation = document.createElement("xs:annotation");
                        Element appInfo = document.createElement("xs:appinfo");
                        Element paramsElement = document.createElement("params");

                        addParameterElement(paramsElement, "title", "0");
                        addParameterElement(paramsElement, "description", "0");
                        addParameterElement(paramsElement, "class", "0");

                        if (inputTypeId.equalsIgnoreCase("checkbox"))
                            addParameterElement(paramsElement, "widget", "0");

                        if (inputTypeId.equalsIgnoreCase("checkbox") || inputTypeId.equalsIgnoreCase("select")
                                || inputTypeId.equalsIgnoreCase("radiobutton")) {
                            addParameterElement(paramsElement, "dataProviderClass", "");
                            addParameterElement(paramsElement, "dataProviderParameters", "");
                            addParameterElement(paramsElement, "values", "1");
                        }

                        if (inputTypeId.equalsIgnoreCase("textarea")) {
                            addParameterElement(paramsElement, "width", "0", "700");
                            addParameterElement(paramsElement, "height", "0", "150");
                            addParameterElement(paramsElement, "enableWYSIWYG", "0", "false");
                            addParameterElement(paramsElement, "WYSIWYGToolbar", "0", "Default");
                            addParameterElement(paramsElement, "WYSIWYGExtraConfig", "0", "");
                            addParameterElement(paramsElement, "enableFormEditor", "0", "false");
                            addParameterElement(paramsElement, "enableContentRelationEditor", "0", "false");
                            addParameterElement(paramsElement, "enableStructureRelationEditor", "0", "false");
                            addParameterElement(paramsElement, "activateExtendedEditorOnLoad", "0", "false");
                        }

                        childElement.appendChild(annotation);
                        annotation.appendChild(appInfo);
                        appInfo.appendChild(paramsElement);
                        isModified = true;
                    }

                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.0")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.1");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                if (inputTypeId.equalsIgnoreCase("textarea")) {
                                    addParameterElementIfNotExists(paramsElement, "width", "0", "700");
                                    addParameterElementIfNotExists(paramsElement, "height", "0", "150");
                                    addParameterElementIfNotExists(paramsElement, "enableWYSIWYG", "0",
                                            "false");
                                    addParameterElementIfNotExists(paramsElement, "WYSIWYGToolbar", "0",
                                            "Default");
                                    addParameterElementIfNotExists(paramsElement, "WYSIWYGExtraConfig", "0",
                                            "");
                                    addParameterElementIfNotExists(paramsElement, "enableFormEditor", "0",
                                            "false");
                                    addParameterElementIfNotExists(paramsElement, "enableContentRelationEditor",
                                            "0", "false");
                                    addParameterElementIfNotExists(paramsElement,
                                            "enableStructureRelationEditor", "0", "false");
                                    addParameterElementIfNotExists(paramsElement,
                                            "activateExtendedEditorOnLoad", "0", "false");

                                    isModified = true;
                                }
                            }
                        }
                    }
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.1")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.2");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }
                            }
                        }
                    }
                }

                //Now we deal with adding the validation part if not existent
                String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']";
                Node formNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                        validatorsXPath);
                if (formNode == null) {
                    String schemaXPath = "/xs:schema";
                    Node schemaNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                            schemaXPath);

                    Element element = (Element) schemaNode;

                    String validationXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:complexType name=\"Validation\" xmlns:xi=\"http://www.w3.org/2001/XInclude\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><xs:annotation><xs:appinfo><form-validation><global><validator name=\"required\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRequired\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field\" msg=\"300\"/><validator name=\"requiredif\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRequiredIf\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field,org.apache.commons.validator.Validator\" msg=\"315\"/><validator name=\"matchRegexp\" classname=\"org.infoglue.cms.util.validators.CommonsValidator\" method=\"validateRegexp\" methodParams=\"java.lang.Object,org.apache.commons.validator.Field\" msg=\"300\"/></global><formset><form name=\"requiredForm\"></form></formset></form-validation></xs:appinfo></xs:annotation></xs:complexType>";

                    InputSource validationXMLSource = new InputSource(new StringReader(validationXML));
                    DOMParser parser2 = new DOMParser();
                    parser2.parse(validationXMLSource);
                    Document document2 = parser2.getDocument();

                    Node node = document.importNode(document2.getDocumentElement(), true);
                    element.appendChild(node);
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.2")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.3");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                addParameterElementIfNotExists(paramsElement, "initialData", "0", "");
                                isModified = true;
                            }
                        }
                    }
                }

            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.3")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.4");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                addParameterElementIfNotExists(paramsElement, "enableComponentPropertiesEditor",
                                        "0", "false");

                                isModified = true;
                            }
                        }
                    }
                }

            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.4")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.5");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                addParameterElementIfNotExists(paramsElement, "WYSIWYGToolbar", "0", "Default");
                                addParameterElementIfNotExists(paramsElement, "WYSIWYGExtraConfig", "0", "");

                                isModified = true;
                            }
                        }
                    }
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.5")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.5.1");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                addParameterElementIfNotExists(paramsElement, "WYSIWYGExtraConfig", "0", "");

                                isModified = true;
                            }
                        }
                    }
                }
            } else if (schemaElement.getAttribute("version") != null
                    && schemaElement.getAttribute("version").equalsIgnoreCase("2.5.1")) {
                isModified = true;
                schemaElement.setAttribute("version", "2.5.2");

                //Now we deal with the individual attributes and parameters
                String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
                NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                        attributesXPath);
                for (int k = 0; k < anl.getLength(); k++) {
                    Element childElement = (Element) anl.item(k);

                    String inputTypeId = childElement.getAttribute("type");

                    NodeList annotationNodeList = childElement.getElementsByTagName("xs:annotation");
                    if (annotationNodeList != null && annotationNodeList.getLength() > 0) {
                        NodeList appinfoNodeList = childElement.getElementsByTagName("xs:appinfo");
                        if (appinfoNodeList != null && appinfoNodeList.getLength() > 0) {
                            NodeList paramsNodeList = childElement.getElementsByTagName("params");
                            if (paramsNodeList != null && paramsNodeList.getLength() > 0) {
                                Element paramsElement = (Element) paramsNodeList.item(0);

                                if (inputTypeId.equalsIgnoreCase("checkbox"))
                                    addParameterElementIfNotExists(paramsElement, "widget", "0", "default");

                                if (inputTypeId.equalsIgnoreCase("checkbox")
                                        || inputTypeId.equalsIgnoreCase("select")
                                        || inputTypeId.equalsIgnoreCase("radiobutton")) {
                                    addParameterElementIfNotExists(paramsElement, "dataProviderClass", "", "");
                                    addParameterElementIfNotExists(paramsElement, "dataProviderParameters", "",
                                            "");
                                }

                                isModified = true;
                            }
                        }
                    }
                }

            }

        }

        if (isModified) {
            StringBuffer sb = new StringBuffer();
            org.infoglue.cms.util.XMLHelper.serializeDom(document.getDocumentElement(), sb);
            contentTypeDefinitionVO.setSchemaValue(sb.toString());

            update(contentTypeDefinitionVO);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return contentTypeDefinitionVO;
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController.java

private boolean addElement(Document document, String attributeName, String nodeTemplateAsString,
        String siblingName) throws Exception {
    Document nodeTemplateDocument = createDocumentFromDefinition(nodeTemplateAsString);
    logger.info("modelClassNameNodeDocument:" + nodeTemplateDocument);

    String componentLabelsXPath = "//xs:element[@name='" + siblingName + "']";
    NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
            componentLabelsXPath);/*from  w  ww .  j a v a2 s .c om*/
    logger.info("anl:" + anl);
    if (anl.getLength() > 0) {
        Element childElement = (Element) anl.item(0);
        Element parent = (Element) childElement.getParentNode();
        Node node = document.importNode(
                nodeTemplateDocument.getDocumentElement().getElementsByTagName("xs:element").item(0), true);

        parent.appendChild(node);
        return true;
    }
    return false;
}