Example usage for org.w3c.dom Element getParentNode

List of usage examples for org.w3c.dom Element getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Element getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.cloud.hypervisor.vmware.mo.HypervisorHostHelper.java

public static String removeOVFNetwork(final String ovfString) {
    if (ovfString == null || ovfString.isEmpty()) {
        return ovfString;
    }/*  w  w w  .ja  v  a2 s . co m*/
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(ovfString.getBytes()));
        final DocumentTraversal traversal = (DocumentTraversal) doc;
        final NodeIterator iterator = traversal.createNodeIterator(doc.getDocumentElement(),
                NodeFilter.SHOW_ELEMENT, null, true);
        for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
            final Element e = (Element) n;
            if ("NetworkSection".equals(e.getTagName())) {
                if (e.getParentNode() != null) {
                    e.getParentNode().removeChild(e);
                }
            } else if ("rasd:Connection".equals(e.getTagName())) {
                if (e.getParentNode() != null && e.getParentNode().getParentNode() != null) {
                    e.getParentNode().getParentNode().removeChild(e.getParentNode());
                }
            }
        }
        final DOMSource domSource = new DOMSource(doc);
        final StringWriter writer = new StringWriter();
        final StreamResult result = new StreamResult(writer);
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
        s_logger.warn("Unexpected exception caught while removing network elements from OVF:", e);
    }
    return ovfString;
}

From source file:com.wfreitas.camelsoap.SoapClient.java

/**
 * Expand the message to accommodate data collections.
 * <p/>/*  w w w  .  j  a v a2 s. c o m*/
 * It basically just clones the message where appropriate.
 *
 * @param element The element to be processed.
 * @param params  The message params.  Uses the message params to
 *                decide whether or not cloning is required.
 */
private void expandMessage(Element element, Map params) {

    // If this element is not a cloned element, check does it need to be cloned...
    if (!element.hasAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, IS_CLONE_ATTRIB)) {
        String ognl = OGNLUtils.getOGNLExpression(element);
        Element clonePoint = getClonePoint(element);

        if (clonePoint != null) {
            int collectionSize;

            collectionSize = calculateCollectionSize(ognl, params);

            if (collectionSize == -1) {
                // It's a collection, but has no entries that match the OGNL expression for this element...
                if (clonePoint == element) {
                    // If the clonePoint is the element itself, we remove it... we're done with it...
                    clonePoint.getParentNode().removeChild(clonePoint);
                } else {
                    // If the clonePoint is not the element itself (it's a child element), leave it
                    // and check it again when we get to it...
                    resetClonePoint(clonePoint);
                }
            } else if (collectionSize == 0) {
                // It's a collection, but has no entries, remove it...
                clonePoint.getParentNode().removeChild(clonePoint);
            } else if (collectionSize == 1) {
                // It's a collection, but no need to clone coz we
                // already have an entry for it...
                clonePoint.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
                        OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB, ognl + "[0]");
            } else {
                // It's a collection and we need to do some cloning
                if (clonePoint != null) {
                    // We already have one, so decrement by one...
                    cloneCollectionTemplateElement(clonePoint, (collectionSize - 1), ognl);
                } else {
                    LOGGER.warn("Collection/array template element <" + element.getLocalName()
                            + "> would appear to be invalid.  It doesn't contain any child elements.");
                }
            }
        }
    }

    // Now do the same for the child elements...
    List<Node> children = DOMUtil.copyNodeList(element.getChildNodes());
    for (Node node : children) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            expandMessage((Element) node, params);
        }
    }
}

From source file:de.betterform.agent.web.event.EventQueue.java

/** Adding XMLEvents to the EventQueue to be processed on the client
 *  EventTarget is nulled to avoid sending it over the wire, targetName and targetId (received from EventTarget)
 *  are stored instead in the ContextInfo Map
 *
 * @param event XMLEvent received from processor
 *///from w  w w  .  j  a v  a2  s.  c  o  m
public void add(XMLEvent event) {
    try {
        XMLEvent clonedEvent = (XMLEvent) event.clone();

        Element target = (Element) clonedEvent.getTarget();
        clonedEvent.addProperty("targetId", target.getAttributeNS(null, "id"));
        String targetName = target.getLocalName();
        clonedEvent.addProperty("targetName", targetName);

        if ((BetterFormEventNames.ITEM_CHANGED.equals(clonedEvent.getType())
                || BetterFormEventNames.STATE_CHANGED.equals(clonedEvent.getType())
                        && HELPER_ELEMENTS.contains(targetName))
                || BetterFormEventNames.PROTOTYPE_CLONED.equals(clonedEvent.getType())
                || BetterFormEventNames.ITEM_DELETED.equals(clonedEvent.getType())) {
            // parent id is needed for updating all helper elements cause they
            // are identified by '<parentId>-label' etc. rather than their own id
            String parentId = ((Element) target.getParentNode()).getAttributeNS(null, "id");
            clonedEvent.addProperty("parentId", parentId);
        } else if (BetterFormEventNames.STATE_CHANGED.equals(clonedEvent.getType())
                && XFormsConstants.OUTPUT.equals(targetName)
                && XFormsConstants.LABEL.equals(target.getParentNode().getLocalName())
                && XFormsConstants.TRIGGER.equals(target.getParentNode().getParentNode().getLocalName())) {
            // for outputs within labels of triggers add the trigger id as parentId and 'label' as targetName to the event
            String parentId = ((Element) target.getParentNode().getParentNode()).getAttributeNS(null, "id");
            clonedEvent.addProperty("parentId", parentId);
            clonedEvent.addProperty("targetName", XFormsConstants.LABEL);
        }

        ((XercesXMLEvent) clonedEvent).target = null;
        ((XercesXMLEvent) clonedEvent).currentTarget = null;
        if (isLoadEmbedEvent(clonedEvent)) {
            this.loadEmbedEventList.add(clonedEvent);
        } else {
            this.eventList.add(clonedEvent);
        }

    } catch (CloneNotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java

/**
 * This is the command "nwcloud enable-jpa". It will configure the JPA persistence layer in a
 * way that will use the HANA Cloud persistence service.
 */// w ww . j a v  a 2  s.c o m
public void nwcloudEnableJPA() {

    // TODO
    // One could check here if ECLIPSELINK is used as JPA provider in persistence.xml
    // and abort, if something else is used.

    // 1. Copy the "persistence.xml" from the addon resources to the directory
    //    "src\main\resources\META-INF\persistence.xml" of the project.
    //    -> the existing "persistence.xml" will be overwritten, so we will do
    //       a backup before to be able to revert this operation.

    // Get the META-INF dir of the current project ("src\main\resources\META-INF")
    // (Later in the packaged WAR this directory will reside in "WEB-INF\classes\META-INF".) 
    String dirWebMetaInf = this.getPathResolved(Path.SRC_MAIN_RESOURCES, "META-INF");
    // Backup "persistence.xml" which is located in this folder
    this.backup(dirWebMetaInf + File.separatorChar + "persistence.xml", null);
    // Overwrite the existing "persistence.xml" with the one included in the resources of our addon
    copyFileFromAddonToProject(dirWebMetaInf, "persistence.xml",
            "HANA Cloud JPA persistency config (needs EclipseLink)");

    // --------------------------------------------------------------------------------

    // 2. Backup "src\main\webapp\WEB-INF\web.xml" first, and then modify it by inserting
    //    the following to declare the DataSource which the application server should
    //    fetch from the environment and provide to the web app through JNDI.
    //      <resource-ref>
    //         <res-ref-name>jdbc/DefaultDB</res-ref-name>
    //         <res-type>javax.sql.DataSource</res-type>
    //      </resource-ref>

    // Get the WEB-INF dir ("src\main\webapp\WEB-INF"), where the "web.xml" is located.
    String dirWebInf = this.getPathResolved(Path.SRC_MAIN_WEBAPP, "WEB-INF");
    String fileWebXml = dirWebInf + File.separatorChar + "web.xml";

    // Backup "src\main\webapp\META-INF\web.xml"
    this.backup(fileWebXml, null);

    // Insert declaration for app server in "web.xml" to import DataSource from environment to JNDI

    // Read "web.xml" and store reference to root Element
    Document document = XmlUtils.readXml(fileManager.getInputStream(fileWebXml));
    Element root = document.getDocumentElement();

    // Add JNDI ressource definition for JPA data source to use (if it does not yet exist)
    if (XmlUtils.findFirstElement("/web-app/resource-ref/resource-ref-name[text()='jdbc/DefaultDB']",
            root) == null) {

        // Create needed DOM elements
        String elemNamespace = "http://java.sun.com/xml/ns/javaee";
        Element resRefElement = document.createElementNS(elemNamespace, "resource-ref");
        Element resRefNameElement = document.createElementNS(elemNamespace, "res-ref-name");
        Node resRefNameElementText = document.createTextNode("jdbc/DefaultDB");
        Element resRefTypeElement = document.createElementNS(elemNamespace, "res-type");
        Node resRefTypeElementText = document.createTextNode("javax.sql.DataSource");

        // Connect and insert elements in XML document
        resRefNameElement.appendChild(resRefNameElementText);
        resRefTypeElement.appendChild(resRefTypeElementText);
        resRefElement.appendChild(resRefNameElement);
        resRefElement.appendChild(resRefTypeElement);
        root.appendChild(resRefElement);

        // Update "web.xml"
        String descriptionOfChange = "Added JNDI ressource for JPA datasource";
        fileManager.createOrUpdateTextFileIfRequired(fileWebXml, XmlUtils.nodeToString(document),
                descriptionOfChange, true);

    }

    // --------------------------------------------------------------------------------

    // 3. Modify "src\main\resources\META-INF\spring\applicationContext.xml"
    //    - Remove the existing declaration of the "dataSource" bean
    //         <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
    //            [...]
    //         </bean>
    //    - Insert statement to fetch dataSource from JNDI (as created by application server)
    //         <jee:jndi-lookup id="dataSource" jndi-name="jdbc/DefaultDB" />

    // Get the Spring config file of the current project ("src\main\resources\META-INF\spring\applicationContext.xml")
    // and create a backup of it, so we're able to revert the changes.
    String fileSpringConf = this.getPathResolved(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
    this.backup(fileSpringConf, null);

    // Read "applicationContext.xml" and store reference to root Element
    document = XmlUtils.readXml(fileManager.getInputStream(fileSpringConf));
    root = document.getDocumentElement();

    // Loop through all bean elements and remove all beans having id "dataSource"
    String descriptionOfChange = "";
    List<Element> beanElements = XmlUtils.findElements("/beans/bean", root);
    for (Element beanElement : beanElements) {
        // Did we find the bean with the id "dataSource"?
        if (beanElement.getAttribute("id").equalsIgnoreCase("dataSource")) {
            Node parent = beanElement.getParentNode();
            parent.removeChild(beanElement);
            DomUtils.removeTextNodes(parent);
            descriptionOfChange = "Removed bean storing static datasource";
            // We will not break the loop (even though we could theoretically), just in case there is more than one such bean declared            
        }
    }

    // Update "applicationContext.xml" file if something has changed
    fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document),
            descriptionOfChange, true);

    // Add bean for dynamic JNDI lookup of datasource (if it does not yet exist)
    if (XmlUtils.findFirstElement("/beans/jndi-lookup[@id='dataSource']", root) == null) {

        Element newJndiElement = document.createElementNS("http://www.springframework.org/schema/jee",
                "jee:jndi-lookup");
        newJndiElement.setAttribute("id", "dataSource");
        newJndiElement.setAttribute("jndi-name", "jdbc/DefaultDB");
        root.appendChild(newJndiElement);
        descriptionOfChange = "Added bean for dynamic JNDI lookup of datasource";

        // Update "applicationContext.xml"
        fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document),
                descriptionOfChange, true);

    }

}

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

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    try {/* w  ww .j  av  a 2 s .  c o  m*/
        User user = securityService.getLoggedInAdminConsoleUser();
        boolean createPageTemplate;
        boolean updateStyleSheet = formItems.getBoolean("updatestylesheet", true);
        boolean updateCSS = formItems.getBoolean("updatecss", false);
        String xmlData;
        Document doc;
        String cssStylesheetKey = null;

        String datasourcesXML;

        int menuKey = formItems.getInt("menukey");

        ResourceKey stylesheetKey = null;
        ResourceFile stylesheet = null;
        ResourceKey cssKey = null;
        boolean stylesheetValid = false;
        String cssKeyParam = request.getParameter("selectedcsskey");
        if (cssKeyParam != null && !"".equals(cssKeyParam)) {
            cssKey = new ResourceKey(cssKeyParam);
        }
        if (request.getParameter("selstylesheetkey") != null
                && request.getParameter("selstylesheetkey").length() > 0) {
            stylesheetKey = new ResourceKey(request.getParameter("selstylesheetkey"));
            formItems.putString("stylesheetkey", stylesheetKey.toString());
        }

        int key = formItems.getInt("key", -1);

        // If we have not selected a stylesheet yet
        if (stylesheetKey == null && cssKey == null && key == -1) {

            createPageTemplate = true;

            doc = XMLTool.createDocument("pagetemplates");
            Document dsDoc = XMLTool.createDocument("datasources");
            datasourcesXML = XMLTool.documentToString(dsDoc);
        } else {
            createPageTemplate = (key == -1);
            int pageTemplateKey;

            if (stylesheetKey == null && cssKey == null) // createPageTemplate = false
            {
                //   If we are editing an existing template
                pageTemplateKey = Integer.parseInt(request.getParameter("key"));
                xmlData = admin.getPageTemplate(pageTemplateKey);
                doc = XMLTool.domparse(xmlData);
                Element pagetemplateElem = XMLTool.getElement(doc.getDocumentElement(), "pagetemplate");
                Element stylesheetElem = XMLTool.getElement(pagetemplateElem, "stylesheet");
                stylesheetKey = new ResourceKey(stylesheetElem.getAttribute("stylesheetkey"));
            } else {
                // If we are making a new template
                doc = buildPageTemplateXML(formItems, key == -1);
                Element oldRoot = doc.getDocumentElement();
                String keyStr = oldRoot.getAttribute("key");
                if (keyStr != null && keyStr.length() > 0) {
                    pageTemplateKey = Integer.parseInt(keyStr);
                } else {
                    pageTemplateKey = -1;
                }
                Element newRoot = XMLTool.createElement(doc, "pagetemplates");
                doc.replaceChild(newRoot, oldRoot);
                newRoot.appendChild(oldRoot);
                updateStyleSheet = stylesheetKey != null;
                if (!updateStyleSheet) {
                    Element elem = XMLTool.getElement(oldRoot, "stylesheet");
                    String styleSheetKeyStr = elem.getAttribute("stylesheetkey");
                    if (styleSheetKeyStr.length() > 0) {
                        stylesheetKey = new ResourceKey(styleSheetKeyStr);
                    }
                }
            }

            Element cssElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/css");
            if (cssElem != null) {
                if (updateCSS && cssKey == null) {
                    cssElem.getParentNode().removeChild(cssElem);
                } else {
                    cssStylesheetKey = cssElem.getAttribute("stylesheetkey");
                }
            }

            Element ptdElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/pagetemplatedata");
            Element dselem = XMLTool.getElement(ptdElem, "datasources");
            if (dselem != null) {
                Document dsDoc = XMLTool.createDocument();
                dsDoc.appendChild(dsDoc.importNode(dselem, true));
                datasourcesXML = XMLTool.documentToString(dsDoc);
            } else {
                Document dsDoc = XMLTool.createDocument("datasources");
                datasourcesXML = XMLTool.documentToString(dsDoc);
            }

            if (!updateStyleSheet) {
                // Insert valuename attributes all parameters
                Element[] pagetemplateparamElems = XMLTool.getElements(ptdElem, "pagetemplateparameter");
                for (Element pagetemplateparamElem : pagetemplateparamElems) {
                    String keyStr = pagetemplateparamElem.getAttribute("value");
                    if (keyStr != null && keyStr.length() > 0) {
                        String type = pagetemplateparamElem.getAttribute("type");
                        if ("category".equals(type)) {
                            int categoryKey = Integer.parseInt(keyStr);
                            String name = admin.getCategoryName(categoryKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("page".equals(type)) {
                            int menuItemKey = Integer.parseInt(keyStr);
                            String name = admin.getMenuItemName(menuItemKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("resource".equals(type)) {
                            pagetemplateparamElem.setAttribute("valuename", keyStr);
                        }
                    }
                }
            }

            String menuItemsXML = admin.getMenuItemsByPageTemplates(user, new int[] { pageTemplateKey });
            Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
            XMLTool.mergeDocuments(doc, menuItemsDoc, true);
        }

        if (stylesheetKey != null && ((createPageTemplate && cssKey == null) || updateStyleSheet)) {

            Map<String, Element> elemMap = new HashMap<String, Element>();
            Element root = doc.getDocumentElement();
            if (updateStyleSheet) {
                // Remove all parameters from xml
                root = XMLTool.getElement(root, "pagetemplate");
                Element pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplateparameters");
                Element[] pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem : pageTemplateParameterElems) {
                    String name = XMLTool.getElementText(XMLTool.getElement(elem, "name"));
                    elemMap.put(name, elem);
                }
                root.removeChild(pageTemplateParamterRootElement);
                pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplatedata");
                pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem1 : pageTemplateParameterElems) {
                    String name = elem1.getAttribute("name");
                    elemMap.put(name, elem1);
                    pageTemplateParamterRootElement.removeChild(elem1);
                }
            }
            Element stylesheetParams = XMLTool.createElement(doc, root, "pagetemplateparameters");

            Element pagetemplatedataElem = XMLTool.getElement(root, "pagetemplatedata");
            if (pagetemplatedataElem == null) {
                pagetemplatedataElem = XMLTool.createElement(doc, root, "pagetemplatedata");
            }

            stylesheet = resourceService.getResourceFile(stylesheetKey);
            if (stylesheet != null) {
                Document stylesheetDoc = null;
                try {
                    stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                    stylesheetValid = true;
                } catch (XMLException e) {
                }
                if (stylesheetDoc != null) {
                    Element[] paramElems = XMLTool.getElements(stylesheetDoc.getDocumentElement(), "xsl:param");
                    for (Element paramElem : paramElems) {
                        Element typeElem = XMLTool.getElement(paramElem, "type");
                        Element tempElem;
                        String name = paramElem.getAttribute("name");
                        if (typeElem != null) {
                            String type = XMLTool.getElementText(typeElem);
                            if ("object".equals(type) || "region".equals(type)) {
                                Element elem = elemMap.get(name);
                                if (elem != null && elem.getAttribute("type").length() == 0) {
                                    stylesheetParams.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, stylesheetParams,
                                            "pagetemplateparameter");
                                    XMLTool.createElement(doc, tempElem, "name", name);
                                }
                            } else {
                                if (elemMap.containsKey(name)) {
                                    Element elem = elemMap.get(name);
                                    String elemType = elem.getAttribute("type");
                                    if (elemType.length() == 0) {
                                        elem.setAttribute("name", name);
                                        XMLTool.removeChildNodes(elem, true);
                                    }
                                    elem.setAttribute("type", type);
                                    pagetemplatedataElem.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                            "pagetemplateparameter");
                                    tempElem.setAttribute("name", name);
                                    tempElem.setAttribute("type", type);
                                }
                            }
                        } else {
                            // Alle vanlige parametere, spesifisert som as="xs:string", e.l. i XSL'en.
                            if (elemMap.containsKey(name)) {
                                Element elem = elemMap.get(name);
                                String type = elem.getAttribute("type");
                                if (type.length() == 0) {
                                    elem.setAttribute("name", name);
                                    XMLTool.removeChildNodes(elem, true);
                                } else {
                                    elem.removeAttribute("type");
                                    elem.removeAttribute("valuename");
                                }
                                pagetemplatedataElem.appendChild(elem);
                            } else {
                                tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                        "pagetemplateparameter");
                                tempElem.setAttribute("name", name);
                            }
                        }
                    }
                }
            }
        }

        if (stylesheet == null && stylesheetKey != null) {
            stylesheet = resourceService.getResourceFile(stylesheetKey);
        }

        if (stylesheet != null) {
            Document stylesheetDoc = null;
            try {
                stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                stylesheetValid = true;
            } catch (XMLException e) {
            }
            if (stylesheetDoc != null) {
                Element tmpElem = XMLTool.createElement(doc.getDocumentElement(), "resource");
                tmpElem.appendChild(doc.importNode(stylesheetDoc.getDocumentElement(), true));
            }
        }

        // Get content types for this site
        XMLTool.mergeDocuments(doc, admin.getContentTypes(false).getAsDOMDocument(), true);

        DOMSource xmlSource = new DOMSource(doc);

        Source xslSource = AdminStore.getStylesheet(session, "pagetemplate_form.xsl");

        HashMap<String, Object> parameters = new HashMap<String, Object>();
        addCommonParameters(admin, user, request, parameters, -1, menuKey);

        if (cssStylesheetKey != null) {
            parameters.put("cssStylesheetKey", cssStylesheetKey);
            parameters.put("cssStylesheetExist",
                    resourceService.getResourceFile(new ResourceKey(cssStylesheetKey)) == null ? "false"
                            : "true");
        }

        ResourceKey defaultCSSKey = admin.getDefaultCSSByMenu(menuKey);
        if (defaultCSSKey != null) {
            parameters.put("defaultcsskey", defaultCSSKey.toString());
            parameters.put("defaultcssExist",
                    resourceService.getResourceFile(defaultCSSKey) == null ? "false" : "true");
        }

        if (createPageTemplate) {
            parameters.put("create", "1");
        } else {
            parameters.put("create", "0");
        }

        parameters.put("page", String.valueOf(request.getParameter("page")));
        datasourcesXML = StringUtil.formatXML(datasourcesXML, 2);
        parameters.put("datasources", datasourcesXML);

        parameters.put("menukey", formItems.getString("menukey"));
        parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", "none"));

        if (stylesheetKey != null) {
            parameters.put("selstylesheetkey", stylesheetKey.toString());
            parameters.put("selstylesheetExist", stylesheet == null ? "false" : "true");
            parameters.put("selstylesheetValid", stylesheetValid ? "true" : "false");

        }

        addAccessLevelParameters(user, parameters);

        UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        parameters.put("defaultRunAsUser", defaultRunAsUserName);

        transformXML(session, response.getWriter(), xmlSource, xslSource, parameters);
    } catch (TransformerException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 10, "XSLT error: %t", e);
    } catch (IOException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 20, "I/O error: %t", e);
    }
}

From source file:com.opensymphony.xwork3.config.providers.XmlConfigurationProvider.java

/**
 * Build a map of ResultConfig objects from below a given XML element.
 *//*from w w  w . j a  v  a 2  s. c  om*/
protected List<ExceptionMappingConfig> buildExceptionMappings(Element element,
        PackageConfig.Builder packageContext) {
    NodeList exceptionMappingEls = element.getElementsByTagName("exception-mapping");

    List<ExceptionMappingConfig> exceptionMappings = new ArrayList<ExceptionMappingConfig>();

    for (int i = 0; i < exceptionMappingEls.getLength(); i++) {
        Element ehElement = (Element) exceptionMappingEls.item(i);

        if (ehElement.getParentNode().equals(element)
                || ehElement.getParentNode().getNodeName().equals(element.getNodeName())) {
            String emName = ehElement.getAttribute("name");
            String exceptionClassName = ehElement.getAttribute("exception");
            String exceptionResult = ehElement.getAttribute("result");

            Map<String, String> params = XmlHelper.getParams(ehElement);

            if (StringUtils.isEmpty(emName)) {
                emName = exceptionResult;
            }

            ExceptionMappingConfig ehConfig = new ExceptionMappingConfig.Builder(emName, exceptionClassName,
                    exceptionResult).addParams(params)
                            //                        .location(DomHelper.getLocationObject(ehElement))
                            .build();
            exceptionMappings.add(ehConfig);
        }
    }

    return exceptionMappings;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//  w w  w.  j  a  v  a2s . c om

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

protected List<InterceptorMapping> buildInterceptorList(Element element, PackageConfig.Builder context)
        throws ConfigurationException {
    List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>();
    NodeList interceptorRefList = element.getElementsByTagName("interceptor-ref");

    for (int i = 0; i < interceptorRefList.getLength(); i++) {
        Element interceptorRefElement = (Element) interceptorRefList.item(i);

        if (interceptorRefElement.getParentNode().equals(element)
                || interceptorRefElement.getParentNode().getNodeName().equals(element.getNodeName())) {
            List<InterceptorMapping> interceptors = lookupInterceptorReference(context, interceptorRefElement);
            interceptorList.addAll(interceptors);
        }/*from   w  w w  . j  a v a  2 s .co m*/
    }

    return interceptorList;
}

From source file:org.alfresco.web.config.WebConfigRuntime.java

/**
 * @param properties//  w  ww. j  a  va  2 s .c o m
 * @return
 */
public boolean syncActionWizardOptions(HashMap<String, String> properties) {
    boolean status = false;
    Element rootElement = (Element) webConfigDocument.getFirstChild();
    Element actionWizardsConfigElem = XmlUtils.findFirstElement(
            "config[@evaluator='string-compare' and @condition='Action Wizards']", rootElement);
    if (actionWizardsConfigElem == null) {
        actionWizardsConfigElem = webConfigDocument.createElement("config");
        actionWizardsConfigElem.setAttribute("evaluator", "string-compare");
        actionWizardsConfigElem.setAttribute("condition", "Action Wizards");
        appendChild(rootElement, actionWizardsConfigElem);
        status = true;
    }
    Element aspectsElem = XmlUtils.findFirstElement("aspects", actionWizardsConfigElem);
    if (aspectsElem == null) {
        aspectsElem = webConfigDocument.createElement("aspects");
        appendChild(actionWizardsConfigElem, aspectsElem);
        status = true;
    }

    String aspectName = properties.get("aspect");
    String showOption = properties.get("show");

    if (aspectName != null && showOption != null) {
        Element typeElem = XmlUtils.findFirstElement("aspect[@name='" + aspectName + "']", aspectsElem);
        if (typeElem == null && showOption.equals("true")) {
            typeElem = webConfigDocument.createElement("aspect");
            typeElem.setAttribute("name", aspectName);
            appendChild(aspectsElem, typeElem);
            status = true;
        }
        if (typeElem != null && showOption.equals("false")) {
            typeElem.getParentNode().removeChild(typeElem);
            status = true;
        }
    }
    return status;
}