List of usage examples for org.w3c.dom Element insertBefore
public Node insertBefore(Node newChild, Node refChild) throws DOMException;
newChild
before the existing child node refChild
. From source file:com.icesoft.faces.context.DOMResponseWriter.java
private void enhanceBody(Element body) { //id required for forwarded (server-side) redirects body.setAttribute("id", "document:body"); // TODO This is only meant to be a transitional focus retention(management) solution. String focusId = context.getFocusId(); if (focusId != null && !focusId.equals("null")) { JavascriptContext.focus(context, focusId); }/*w ww . ja v a2 s.c o m*/ ExternalContext externalContext = context.getExternalContext(); ViewHandler handler = context.getApplication().getViewHandler(); String sessionIdentifier = context.getIceFacesId(); String viewIdentifier = context.getViewNumber(); String prefix = sessionIdentifier + ':' + viewIdentifier + ':'; Element script = (Element) body.appendChild(document.createElement("script")); script.setAttribute("id", prefix + "dynamic-code"); script.setAttribute("type", "text/javascript"); String calls = JavascriptContext.getJavascriptCalls(context); script.appendChild(document.createTextNode(calls)); String contextPath = handler.getResourceURL(context, "/"); if (blockingRequestHandlerContext == null) { //ICE-3784 //Only need to strip leading and trailing slashes. Removing all slashes //will cause problems with contexts that actually contain slashes e.g /myapp/mysubapp. String normalizedPath = contextPath; if (normalizedPath.length() > 0) { if (normalizedPath.charAt(0) == '/') { normalizedPath = normalizedPath.substring(1); } if (normalizedPath.length() > 0) { if (normalizedPath.charAt(normalizedPath.length() - 1) == '/') { normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1); } } } blockingRequestHandlerContext = URI.create("/").resolve(normalizedPath + "/").toString(); } String connectionLostRedirectURI; try { String uri = configuration.getAttribute("connectionLostRedirectURI"); connectionLostRedirectURI = "'" + handler.getResourceURL(context, uri.replaceAll("'", "")) + "'"; } catch (ConfigurationException e) { connectionLostRedirectURI = "null"; } String sessionExpiredRedirectURI; try { String uri = configuration.getAttribute("sessionExpiredRedirectURI"); sessionExpiredRedirectURI = "'" + handler.getResourceURL(context, uri.replaceAll("'", "")) + "'"; } catch (ConfigurationException e) { sessionExpiredRedirectURI = "null"; } String configurationID = prefix + "configuration-script"; //add viewIdentifier property to the container element ("body" for servlet env., any element for the portlet env.) ResourceBundle localizedBundle = bridgeMessageResolver.bundleFor(context.getViewRoot().getLocale()); //todo: build startup script only once on aplication startup boolean synchronousMode = configuration.getAttributeAsBoolean("synchronousUpdate", false); String startupScript = "window.disposeViewsURI = '" + blockingRequestHandlerContext + "block/dispose-views';\n" + "var container = '" + configurationID + "'.asElement().parentNode;\n" + "container.bridge = new Ice.Community.Application({" + "blockUI: " + configuration.getAttribute("blockUIOnSubmit", "false") + "," + "session: '" + sessionIdentifier + "'," + "view: " + viewIdentifier + "," + "synchronous: " + synchronousMode + "," + "connectionLostRedirectURI: " + connectionLostRedirectURI + "," + "sessionExpiredRedirectURI: " + sessionExpiredRedirectURI + "," + "serverErrorRetryTimeouts: [" + configuration .getAttribute("serverErrorRetryTimeouts", "1000 2000 4000").trim().replaceAll("\\s+", ",") + "], " + "connection: {" + "context: '" + contextPath + "', " + (synchronousMode ? //encode path for URL rewrite session tracking mode ("sendReceiveUpdatesURI: '" + externalContext.encodeResourceURL(contextPath + "block/send-receive-updates") + "',") : ("sendReceiveUpdatesURI: '" + contextPath + "block/send-receive-updates" + "'," + "pingURI: '" + contextPath + "block/ping" + "'," + "receiveUpdatesURI: '" + contextPath + "block/receive-updates" + "'," + "receiveUpdatedViewsURI: '" + blockingRequestHandlerContext + "block/receive-updated-views" + "',") + "heartbeat: {" + "interval: " + configuration.getAttributeAsLong("heartbeatInterval", 50000) + "," + "timeout: " + configuration.getAttributeAsLong("heartbeatTimeout", 30000) + "," + "retries: " + configuration.getAttributeAsLong("heartbeatRetries", 3) + "},") + "timeout: " + configuration.getAttributeAsLong("connectionTimeout", 60000) + "}," + "messages: {" + "sessionExpired: '" + localizedBundle.getString("session-expired") + "'," + "connectionLost: '" + localizedBundle.getString("connection-lost") + "'," + "serverError: '" + localizedBundle.getString("server-error") + "'," + "description: '" + localizedBundle.getString("description") + "'," + "buttonText: '" + localizedBundle.getString("button-text") + "'" + "}" + "}, container);"; Element configurationElement = (Element) body.appendChild(document.createElement("script")); configurationElement.setAttribute("id", configurationID); configurationElement.setAttribute("type", "text/javascript"); configurationElement.appendChild(document.createTextNode(startupScript)); body.insertBefore(configurationElement, body.getFirstChild()); Element iframe = document.createElement("iframe"); body.insertBefore(iframe, body.getFirstChild()); String iframeID = "history-frame:" + sessionIdentifier + ":" + viewIdentifier; iframe.setAttribute("id", iframeID); iframe.setAttribute("name", iframeID); Object request = externalContext.getRequest(); final String frameURI; //another "workaround" to resolve the iframe URI if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getRequestURI() == null) { frameURI = "about:blank"; } else { frameURI = CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank"); } } else { frameURI = CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank"); // ICE-2553 } iframe.setAttribute("title", "Icefaces Redirect"); iframe.setAttribute("src", frameURI); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("style", "z-index: 10000; visibility: hidden; width: 0; height: 0; position: absolute; opacity: 0.22; filter: alpha(opacity=22);"); if (checkJavaScript) { Element noscript = (Element) body.appendChild(document.createElement("noscript")); Element noscriptMeta = (Element) noscript.appendChild(document.createElement("meta")); noscriptMeta.setAttribute("http-equiv", "refresh"); noscriptMeta.setAttribute("content", "0;url=" + handler.getResourceURL(context, "/xmlhttp/javascript-blocked")); } if (context.isContentIncluded()) { Element element = (Element) body.insertBefore(document.createElement("div"), configurationElement); element.setAttribute("style", "display: none;"); //id added so the conditional rendering of the components under the portlet, //won't send the body level update element.setAttribute("id", "cntIncDiv"); appendContentReferences(element); } }
From source file:org.ajax4jsf.webapp.tidy.TidyParser.java
public Document parseHtmlByTidy(Object input, Writer output) throws IOException { Document document = tidy.parseDOM(input, null); if (null != document) { Element documentElement = document.getDocumentElement(); if (null != documentElement) { NodeVisitor nodeVisitor = new NodeVisitor(); nodeVisitor.traverse(documentElement); // Replace state elements with real stored. List<org.w3c.dom.Node> viewStateSpans = nodeVisitor.viewStateSpans; for (org.w3c.dom.Node node : viewStateSpans) { // State marker - replace with real. org.w3c.dom.Node parentNode = node.getParentNode(); if (null != _viewState) { parentNode.replaceChild(document.createCDATASection(_viewState), node); } else { // Remove marker element, but keep it content. if (node.hasChildNodes()) { org.w3c.dom.Node nextSibling = node.getNextSibling(); NodeList childNodes = node.getChildNodes(); // Copy all nodes by temporary array ( since // moving nodes in iteration // modify NodeList with side effects. org.w3c.dom.Node[] childArray = new org.w3c.dom.Node[childNodes.getLength()]; for (int j = 0; j < childArray.length; j++) { childArray[j] = childNodes.item(j); }/*from w w w. j av a2 s.com*/ for (int j = 0; j < childArray.length; j++) { parentNode.insertBefore(childArray[j], nextSibling); } } parentNode.removeChild(node); } } // Inserts scripts and styles to head. if ((null != headEvents && headEvents.length > 0) || null != _viewState) { // find head org.w3c.dom.Node head = nodeVisitor.head; // Insert empty if not found if (null == head) { head = document.createElement("head"); documentElement.insertBefore(head, documentElement.getFirstChild()); } org.w3c.dom.Node child = head.getFirstChild(); while (child != null) { if (child instanceof Element) { String nodeName = ((Element) child).getNodeName(); if (!("title".equalsIgnoreCase(nodeName) || "base".equalsIgnoreCase(nodeName))) { break; } } child = child.getNextSibling(); } if (headEvents != null) { for (org.w3c.dom.Node node : headEvents) { head.insertBefore(importNode(document, node, true), child); } } } } if (null != output) { tidy.pprint(document, output); } } return document; }
From source file:org.alfresco.repo.template.XSLTProcessor.java
/** * Adds the specified parameters to the xsl template as variables within the alfresco namespace. * /* w w w.j a va2s . co m*/ * @param xsltModel * the variables to place within the xsl template * @param xslTemplate * the xsl template */ protected void addParameters(final XSLTemplateModel xsltModel, final Document xslTemplate) { final Element docEl = xslTemplate.getDocumentElement(); final String XSL_NS = docEl.getNamespaceURI(); final String XSL_NS_PREFIX = docEl.getPrefix(); for (Map.Entry<QName, Object> e : xsltModel.entrySet()) { if (ROOT_NAMESPACE.equals(e.getKey())) { continue; } final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable"); el.setAttribute("name", e.getKey().toPrefixString()); final Object o = e.getValue(); if (o instanceof String || o instanceof Number || o instanceof Boolean) { el.appendChild(xslTemplate.createTextNode(o.toString())); // ALF-15413. Add the variables at the end of the list of children docEl.insertBefore(el, null); } } }
From source file:org.alfresco.web.forms.XSLTRenderingEngine.java
/** * Adds the specified parameters to the xsl template as variables within the * alfresco namespace./*from w w w .j ava 2s . c om*/ * * @param model the variables to place within the xsl template * @param xslTemplate the xsl template */ protected void addParameters(final Map<QName, Object> model, final Document xslTemplate) { final Element docEl = xslTemplate.getDocumentElement(); final String XSL_NS = docEl.getNamespaceURI(); final String XSL_NS_PREFIX = docEl.getPrefix(); for (Map.Entry<QName, Object> e : model.entrySet()) { if (RenderingEngine.ROOT_NAMESPACE.equals(e.getKey())) { continue; } final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable"); el.setAttribute("name", e.getKey().toPrefixString()); final Object o = e.getValue(); if (o instanceof String || o instanceof Number || o instanceof Boolean) { el.appendChild(xslTemplate.createTextNode(o.toString())); docEl.insertBefore(el, docEl.getFirstChild()); } } }
From source file:org.apache.axis.wsdl.fromJava.Types.java
/** * Inserts the type fragment into the given wsdl document and ensures * that definitions from each embedded schema are allowed to reference * schema components from the other sibling schemas. * @param doc/* w w w. j av a 2 s. c o m*/ */ public void insertTypesFragment(Document doc) { updateNamespaces(); if (wsdlTypesElem == null) return; // Make sure that definitions from each embedded schema are allowed // to reference schema components from the other sibling schemas. Element schemaElem = null; String tns = null; NodeList nl = wsdlTypesElem.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { NamedNodeMap attrs = nl.item(i).getAttributes(); if (attrs == null) continue; // Should never happen. for (int n = 0; n < attrs.getLength(); n++) { Attr a = (Attr) attrs.item(n); if (a.getName().equals("targetNamespace")) { tns = a.getValue(); schemaElem = (Element) nl.item(i); break; } } // Ignore what appears to be a not namespace-qualified // schema definition. if (tns != null && !"".equals(tns.trim())) { // By now we know that an import element might be necessary // for some sibling schemas. However, in the absence of // a symbol table proper, the best we can do is add one // for each sibling schema. Iterator it = schemaTypes.keySet().iterator(); String otherTns; Element importElem; while (it.hasNext()) { if (!tns.equals(otherTns = (String) it.next())) { importElem = docHolder.createElement("import"); importElem.setAttribute("namespace", otherTns); schemaElem.insertBefore(importElem, schemaElem.getFirstChild()); } } } schemaElem = null; tns = null; } // Import the wsdlTypesElement into the doc. org.w3c.dom.Node node = doc.importNode(wsdlTypesElem, true); // Insert the imported element at the beginning of the document doc.getDocumentElement().insertBefore(node, doc.getDocumentElement().getFirstChild()); }
From source file:org.apache.camel.maven.DocumentationEnricher.java
private void addDocumentation(Element item, String textContent) { Element annotation = document.createElement(Constants.XS_ANNOTATION_ELEMENT_NAME); Element documentation = document.createElement(Constants.XS_DOCUMENTATION_ELEMENT_NAME); documentation.setAttribute("xml:lang", "en"); CDATASection cdataDocumentationText = document.createCDATASection(formatTextContent(item, textContent)); documentation.appendChild(cdataDocumentationText); annotation.appendChild(documentation); if (item.getFirstChild() != null) { item.insertBefore(annotation, item.getFirstChild()); } else {//from w w w. java 2 s . c om item.appendChild(annotation); } }
From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java
public void rewrite(Gadget gadget, MutableContent mutableContent) throws RewritingException { // Don't touch sanitized gadgets. if (gadget.sanitizeOutput()) { return;//w w w. j a v a2 s. c o m } try { Document document = mutableContent.getDocument(); Element head = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head"); // Insert new content before any of the existing children of the head element Node firstHeadChild = head.getFirstChild(); // Only inject default styles if no doctype was specified. if (document.getDoctype() == null) { Element defaultStyle = document.createElement("style"); defaultStyle.setAttribute("type", "text/css"); head.insertBefore(defaultStyle, firstHeadChild); defaultStyle.appendChild(defaultStyle.getOwnerDocument().createTextNode(DEFAULT_CSS)); } injectBaseTag(gadget, head); injectGadgetBeacon(gadget, head, firstHeadChild); injectFeatureLibraries(gadget, head, firstHeadChild); // This can be one script block. Element mainScriptTag = document.createElement("script"); GadgetContext context = gadget.getContext(); MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), context.getLocale(), context.getIgnoreCache(), context.getContainer()); injectMessageBundles(bundle, mainScriptTag); injectDefaultPrefs(gadget, mainScriptTag); injectPreloads(gadget, mainScriptTag); // We need to inject our script before any developer scripts. head.insertBefore(mainScriptTag, firstHeadChild); Element body = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body"); body.setAttribute("dir", bundle.getLanguageDirection()); injectOnLoadHandlers(body); mutableContent.documentChanged(); } catch (GadgetException e) { throw new RewritingException(e.getLocalizedMessage(), e, e.getHttpStatusCode()); } }
From source file:org.apache.tuscany.sca.implementation.bpel.ode.TuscanyProcessConfImpl.java
/** * Insert an initializer which supplies the value of an SCA property as specified by the * SCA Component using the BPEL process/*from www . j a va 2s . c o m*/ * @param bpelDOM - a DOM model representation of the BPEL process * @param property - an SCA ComponentProperty element for the property * This DOM model is updated, with an initializer being added for the BPEL variable * corresponding to the SCA property */ private void insertSCAPropertyInitializer(Document bpelDOM, ComponentProperty property) { // Only insert a Property initializer where there is a value for the Property if (property.getValue() == null) return; Element insertionElement = findInitializerInsertionPoint(bpelDOM); if (insertionElement == null) return; Element initializer = getInitializerSequence(bpelDOM, property); if (initializer == null) return; // Insert the initializer sequence as the next sibling element of the insertion point Element parent = (Element) insertionElement.getParentNode(); // Get the next sibling element, if there is one Node sibling = insertionElement.getNextSibling(); while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { sibling = sibling.getNextSibling(); } // end while // Either insert at the end or before the next element if (sibling == null) { parent.appendChild(initializer); } else { parent.insertBefore(initializer, sibling); } // end if }
From source file:org.apache.ws.security.util.WSSecurityUtil.java
/** * prepend a child element <p/>/*from w ww . j a v a2 s .com*/ * * @param parent element of this child element * @param child the element to append * @return the child element */ public static Element prependChildElement(Element parent, Element child) { Node firstChild = parent.getFirstChild(); if (firstChild == null) { return (Element) parent.appendChild(child); } else { return (Element) parent.insertBefore(child, firstChild); } }
From source file:org.apache.ws.security.util.WSSecurityUtil.java
/** * prepend a child element <p/>/*from ww w .j a v a 2 s . c om*/ * * @param doc the DOM document (SOAP request) * @param parent element of this child element * @param child the element to append * @param addWhitespace if true prepend a newline before child * @deprecated use {@link WSSecurityUtil#prependChildElement(Element, Element)} * instead * @return the child element */ public static Element prependChildElement(Document doc, Element parent, Element child, boolean addWhitespace) { Node firstChild = parent.getFirstChild(); Node addedChild; if (firstChild == null) { addedChild = parent.appendChild(child); } else { addedChild = parent.insertBefore(child, firstChild); } if (addWhitespace) { Node whitespaceText = doc.createTextNode("\n"); parent.insertBefore(whitespaceText, addedChild); } return (Element) addedChild; }