Example usage for org.w3c.dom Element getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the local part of the qualified name of this node.

Usage

From source file:org.apache.xml.security.test.encryption.EncryptContentTest.java

public void testContentRemoved() throws Exception {

    if (!haveISOPadding) {
        log.warn("Test testContentRemoved skipped as necessary algorithms not available");
        return;/* ww  w.  j av a 2  s.c om*/
    }

    Document doc = db.parse(new ByteArrayInputStream(DATA.getBytes("UTF8")));
    NodeList dataToEncrypt = doc.getElementsByTagName("user");

    XMLCipher dataCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
    dataCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);

    for (int i = 0; i < dataToEncrypt.getLength(); i++) {
        dataCipher.doFinal(doc, (Element) dataToEncrypt.item(i), true);
    }

    // Check that user content has been removed
    Element user = (Element) dataToEncrypt.item(0);
    Node child = user.getFirstChild();
    while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
        child = child.getNextSibling();
    }
    // child should be EncryptedData, if not throw exception
    Element childElem = (Element) child;
    if (!childElem.getLocalName().equals("EncryptedData")) {
        // t.transform(new DOMSource(doc), new StreamResult(System.out));
        throw new Exception("Element content not replaced");
    }
    // there shouldn't be any more children elements
    Node sibling = childElem.getNextSibling();
    while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
        sibling = sibling.getNextSibling();
    }
    if (sibling != null) {
        // t.transform(new DOMSource(doc), new StreamResult(System.out));
        throw new Exception("Sibling element content not replaced");
    }

    // t.transform(new DOMSource(doc), new StreamResult(System.out));
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * Returns true if the element is in XML Signature namespace and the local
 * name equals the supplied one.//  w  w  w.  ja  v  a2s . co m
 *
 * @param element
 * @param localName
 * @return true if the element is in XML Signature namespace and the local name equals 
 * the supplied one
 */
public static boolean elementIsInSignatureSpace(Element element, String localName) {
    if (element == null) {
        return false;
    }

    return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
            && element.getLocalName().equals(localName);
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * Returns true if the element is in XML Encryption namespace and the local
 * name equals the supplied one./*from www .  j a v  a2  s . c  om*/
 *
 * @param element
 * @param localName
 * @return true if the element is in XML Encryption namespace and the local name 
 * equals the supplied one
 */
public static boolean elementIsInEncryptionSpace(Element element, String localName) {
    if (element == null) {
        return false;
    }
    return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
            && element.getLocalName().equals(localName);
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

protected String setXFormsId(Element el) {
    //remove the eventuel "id" attribute
    if (el.hasAttributeNS(SchemaFormBuilder.XFORMS_NS, "id")) {
        el.removeAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");
    }/*from   w  w w  . jav a2s  .c om*/

    //long count=this.incIdCounter();
    long count = 0;
    String name = el.getLocalName();
    Long l = (Long) counter.get(name);

    if (l != null) {
        count = l.longValue();
    }

    String id = name + "_" + count;

    //increment the counter
    counter.put(name, new Long(count + 1));
    el.setAttributeNS(SchemaFormBuilder.XFORMS_NS, this.getXFormsNSPrefix() + "id", id);

    return id;
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * Add a repeat section if maxOccurs > 1.
 *//*ww w .ja v a 2  s  . co  m*/
private Element addRepeatIfNecessary(Document xForm, Element modelSection, Element formSection,
        XSTypeDefinition controlType, int minOccurs, int maxOccurs, String pathToRoot) {
    Element repeatSection = formSection;

    // add xforms:repeat section if this element re-occurs
    //
    if (maxOccurs != 1) {

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("DEBUG: AddRepeatIfNecessary for multiple element for type " + controlType.getName()
                    + ", maxOccurs=" + maxOccurs);

        //repeatSection = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix() + "repeat"));
        repeatSection = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "repeat");

        //bind instead of repeat
        //repeatSection.setAttributeNS(XFORMS_NS,getXFormsNSPrefix() + "nodeset",pathToRoot);
        // bind -> last element in the modelSection
        Element bind = DOMUtil.getLastChildElement(modelSection);
        String bindId = null;

        if ((bind != null) && (bind.getLocalName() != null) && bind.getLocalName().equals("bind")) {
            bindId = bind.getAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");
        } else {
            LOGGER.warn("addRepeatIfNecessary: bind not found: " + bind + " (model selection name="
                    + modelSection.getNodeName() + ")");

            //if no bind is found -> modelSection is already a bind, get its parent last child
            bind = DOMUtil.getLastChildElement(modelSection.getParentNode());

            if ((bind != null) && (bind.getLocalName() != null) && bind.getLocalName().equals("bind")) {
                bindId = bind.getAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");
            } else {
                LOGGER.warn("addRepeatIfNecessary: bind really not found");
            }
        }

        repeatSection.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "bind", bindId);
        this.setXFormsId(repeatSection);

        //appearance=full is more user friendly
        repeatSection.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance", "full");

        //triggers
        this.addTriggersForRepeat(xForm, formSection, repeatSection, minOccurs, maxOccurs, bindId);

        Element controlWrapper = _wrapper.createControlsWrapper(repeatSection);
        formSection.appendChild(controlWrapper);

        //add a group inside the repeat?
        Element group = xForm.createElementNS(XFORMS_NS, this.getXFormsNSPrefix() + "group");
        this.setXFormsId(group);
        repeatSection.appendChild(group);
        repeatSection = group;
    }

    return repeatSection;
}

From source file:org.chiba.xml.xforms.connector.serializer.FormDataSerializer.java

protected void serializeElement(PrintWriter writer, Element element, String boundary, String charset)
        throws Exception {
    /* The specs http://www.w3.org/TR/2003/REC-xforms-20031014/slice11.html#serialize-form-data
     *//from   w w w  .  j  a v  a  2  s .co  m
     *     Each element node is visited in document order.
     *
     *     Each element that has exactly one text node child is selected 
     *     for inclusion.
     *
     *     Element nodes selected for inclusion are as encoded as 
     *     Content-Disposition: form-data MIME parts as defined in 
     *     [RFC 2387], with the name parameter being the element local name.
     *
     *     Element nodes of any datatype populated by upload are serialized 
     *     as the specified content and additionally have a 
     *     Content-Disposition filename parameter, if available.
     *
     *     The Content-Type must be text/plain except for xsd:base64Binary, 
     *     xsd:hexBinary, and derived types, in which case the header 
     *     represents the media type of the attachment if known, otherwise 
     *     application/octet-stream. If a character set is applicable, the 
     *     Content-Type may have a charset parameter.
     *
     */
    String nodeValue = null;
    boolean isCDATASection = false;
    boolean includeTextNode = true;

    NodeList list = element.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node n = list.item(i);
        switch (n.getNodeType()) {

        /* CDATA sections are not mentioned ... ignore for now
        case Node.CDATA_SECTION_NODE:
            isCDATASection = true;
         */

        case Node.TEXT_NODE:
            if (includeTextNode == true) {
                if (nodeValue != null) {
                    /* only one text node allowed by specs */
                    includeTextNode = false;
                } else {
                    nodeValue = n.getNodeValue();
                }
            }
            break;

        /* Real ambiguity in specs, what if there's one text node and
         * n elements ? Let's assume if there is an element, ignore the
         * text nodes
         */
        case Node.ELEMENT_NODE:
            includeTextNode = false;
            serializeElement(writer, (Element) n, boundary, charset);
            break;

        default:
            // ignore comments and other nodes...
        }
    }

    if (nodeValue != null && includeTextNode) {

        Object object = ((ElementImpl) element).getUserData();
        if (!(object instanceof ModelItem)) {
            throw new XFormsException("Unknown instance data format.");
        }
        ModelItem item = (ModelItem) object;

        writer.print("\r\n--" + boundary);

        String name = element.getLocalName();
        if (name == null) {
            name = element.getNodeName();
        }

        // mediatype tells about file upload
        if (item.getMediatype() != null) {
            writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";");
            if (item.getFilename() != null) {
                File file = new File(item.getFilename());
                writer.print(" filename=\"" + file.getName() + "\";");
            }
            writer.print("\r\nContent-Type: " + item.getMediatype());

        } else {
            writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";");
            writer.print("\r\nContent-Type: text/plain; charset=\"" + charset + "\";");
        }

        String encoding = "8bit";
        if ("base64Binary".equalsIgnoreCase(item.getDatatype())) {
            encoding = "base64";
        } else if ("hexBinary".equalsIgnoreCase(item.getDatatype())) {
            // recode to base64 because of MIME
            nodeValue = new String(Base64.encodeBase64(Hex.decodeHex(nodeValue.toCharArray()), true));
            encoding = "base64";
        }
        writer.print("\r\nContent-Transfer-Encoding: " + encoding);
        writer.print("\r\n\r\n" + nodeValue);
    }

    writer.flush();
}

From source file:org.chiba.xml.xforms.CustomElementFactory.java

public boolean isCustomActionElement(Element element) throws XFormsException {

    if (this.noCustomElements) {
        //no custom elements configured
        return false;
    }//from   w  w w.  ja v  a2s  . c  o  m

    //key to search the Map for a custom element
    String key = getKeyForElement(element);

    if (ACTIONS_ELEMENTS.containsKey(key)) {
        //a match was found
        return true;
    }

    //if the element is not recognized but it has a
    //mustUnderstand attribute, throw an exception to
    //signal error according to the spec
    if (element.hasAttributeNS(NamespaceConstants.XFORMS_NS, MUST_UNDERSTAND_ATTRIBUTE)) {

        String elementId = element.getPrefix() + ":" + element.getLocalName();

        throw new XFormsException("MustUnderstand Module failure at element " + elementId);
    }

    //no matching configuration was found
    return false;
}

From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java

@Override
public void handleMessage(Message message) throws Fault {
    List authHeader = (List) ((Map) message.getExchange().getOutMessage().get(Message.PROTOCOL_HEADERS))
            .get("Authorization");
    String authorization = null;/*from  w  ww  .  j  a v  a  2s  .  c om*/
    if (authHeader != null && authHeader.size() > 0) {
        authorization = (String) authHeader.get(0);
    }
    InputStream content = message.getContent(InputStream.class);
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null || !contentType.contains(APPLICATION_VND_PAOS_XML)) {
        return;
    }
    try {
        SOAPPart soapMessage = SamlProtocol
                .parseSoapMessage(IOUtils.toString(content, Charset.forName("UTF-8")));
        Iterator iterator = soapMessage.getEnvelope().getHeader().examineAllHeaderElements();
        IDPEntry idpEntry = null;
        String relayState = "";
        String responseConsumerURL = "";
        String messageId = "";
        while (iterator.hasNext()) {
            Element soapHeaderElement = (SOAPHeaderElement) iterator.next();
            if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                relayState = DOM2Writer.nodeToString(soapHeaderElement);
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI()
                    .equals(URN_OASIS_NAMES_TC_SAML_2_0_PROFILES_SSO_ECP)) {
                try {
                    soapHeaderElement = SamlProtocol.convertDomImplementation(soapHeaderElement);
                    Request ecpRequest = (Request) OpenSAMLUtil.fromDom(soapHeaderElement);
                    IDPList idpList = ecpRequest.getIDPList();
                    if (idpList == null) {
                        throw new Fault(new AccessDeniedException(
                                "Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    List<IDPEntry> idpEntrys = idpList.getIDPEntrys();
                    if (idpEntrys == null || idpEntrys.size() == 0) {
                        throw new Fault(new AccessDeniedException(
                                "Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    // choose the right entry, probably need to do something better than select the first
                    // one
                    // but the spec doesn't specify how this is supposed to be done
                    idpEntry = idpEntrys.get(0);
                } catch (WSSecurityException e) {
                    // TODO figure out IdP alternatively
                    LOGGER.info(
                            "Unable to determine IdP appropriately. ECP connection will fail. SP may be incorrectly configured. Contact the administrator for the remote system.");
                }
            } else if (REQUEST.equals(soapHeaderElement.getLocalName())
                    && soapHeaderElement.getNamespaceURI().equals(URN_LIBERTY_PAOS_2003_08)) {
                responseConsumerURL = soapHeaderElement.getAttribute(RESPONSE_CONSUMER_URL);
                messageId = soapHeaderElement.getAttribute(MESSAGE_ID);
            }
        }
        if (idpEntry == null) {
            throw new Fault(new AccessDeniedException(
                    "Unable to complete SAML ECP connection. Unable to determine IdP server."));
        }
        String token = createToken(authorization);
        checkAuthnRequest(soapMessage);
        Element authnRequestElement = SamlProtocol
                .getDomElement(soapMessage.getEnvelope().getBody().getFirstChild());
        String loc = idpEntry.getLoc();
        String soapRequest = buildSoapMessage(token, relayState, authnRequestElement, null);
        HttpResponseWrapper httpResponse = getHttpResponse(loc, soapRequest, null);
        InputStream httpResponseContent = httpResponse.content;
        SOAPPart idpSoapResponse = SamlProtocol
                .parseSoapMessage(IOUtils.toString(httpResponseContent, Charset.forName("UTF-8")));
        Iterator responseHeaderElements = idpSoapResponse.getEnvelope().getHeader().examineAllHeaderElements();
        String newRelayState = "";
        while (responseHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) responseHeaderElements.next();
            if (RESPONSE.equals(soapHeaderElement.getLocalName())) {
                String assertionConsumerServiceURL = soapHeaderElement
                        .getAttribute(ASSERTION_CONSUMER_SERVICE_URL);
                if (!responseConsumerURL.equals(assertionConsumerServiceURL)) {
                    String soapFault = buildSoapFault(ECP_RESPONSE,
                            "The responseConsumerURL does not match the assertionConsumerServiceURL.");
                    httpResponse = getHttpResponse(responseConsumerURL, soapFault, null);
                    message.setContent(InputStream.class, httpResponse.content);
                    return;
                }
            } else if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                newRelayState = DOM2Writer.nodeToString(soapHeaderElement);
                if (StringUtils.isNotEmpty(relayState) && !relayState.equals(newRelayState)) {
                    LOGGER.debug("RelayState does not match between ECP request and response");
                }
                if (StringUtils.isNotEmpty(relayState)) {
                    newRelayState = relayState;
                }
            }
        }
        checkSamlpResponse(idpSoapResponse);
        Element samlpResponseElement = SamlProtocol
                .getDomElement(idpSoapResponse.getEnvelope().getBody().getFirstChild());
        Response paosResponse = null;
        if (StringUtils.isNotEmpty(messageId)) {
            paosResponse = getPaosResponse(messageId);
        }
        String soapResponse = buildSoapMessage(null, newRelayState, samlpResponseElement, paosResponse);
        httpResponse = getHttpResponse(responseConsumerURL, soapResponse,
                message.getExchange().getOutMessage());
        if (httpResponse.statusCode < 400) {
            httpResponseContent = httpResponse.content;
            message.setContent(InputStream.class, httpResponseContent);
            Map<String, List<String>> headers = new HashMap<>();
            message.put(Message.PROTOCOL_HEADERS, headers);
            httpResponse.headers.forEach((entry) -> headers.put(entry.getKey(),
                    // CXF Expects pairs of <String, List<String>>
                    entry.getValue() instanceof List
                            ? ((List<Object>) entry.getValue()).stream().map(String::valueOf)
                                    .collect(Collectors.toList())
                            : Lists.newArrayList(String.valueOf(entry.getValue()))));

        } else {
            throw new Fault(
                    new AccessDeniedException("Unable to complete SAML ECP connection due to an error."));
        }

    } catch (IOException e) {
        LOGGER.debug("Error encountered while performing ECP handshake.", e);
    } catch (XMLStreamException | SOAPException e) {
        throw new Fault(new AccessDeniedException(
                "Unable to complete SAML ECP connection. The server's response was not in the correct format."));
    } catch (WSSecurityException e) {
        throw new Fault(new AccessDeniedException(
                "Unable to complete SAML ECP connection. Unable to send SOAP request messages."));
    }
}

From source file:org.cruxframework.crux.core.declarativeui.template.Templates.java

/**
 * @param template/*ww  w .  jav  a  2  s . c om*/
 * @return
 */
static boolean isWidgetTemplate(Document template) {
    boolean isWidget = false;
    if (template != null) {
        Element templateElement = template.getDocumentElement();

        List<Element> children = extractChildrenElements(templateElement);

        if (children != null && children.size() == 1) {
            Element element = children.get(0);
            String namespaceURI = element.getNamespaceURI();
            if (namespaceURI != null) {
                if (namespaceURI.startsWith("http://www.cruxframework.org/crux/")) {
                    isWidget = true;
                } else if (namespaceURI.startsWith("http://www.cruxframework.org/templates/")) {
                    String library = namespaceURI.substring("http://www.cruxframework.org/templates/".length());
                    Document refTemplate = getTemplate(library, element.getLocalName());
                    isWidget = isWidgetTemplate(refTemplate);
                }
            }
        }
    }

    return isWidget;
}

From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java

/**
 * @param cruxPageInnerTag//from www.  j a  v a2s.com
 * @param cruxArrayMetaData
 * @throws ViewParserException 
 */
private void generateCruxInnerMetaData(Element cruxPageInnerTag, StringBuilder cruxArrayMetaData)
        throws ViewParserException {
    writeIndentationSpaces(cruxArrayMetaData);
    cruxArrayMetaData.append("{");

    String currentWidgetTag = getCurrentWidgetTag();
    if (isWidget(currentWidgetTag)) {
        cruxArrayMetaData.append("\"_type\":\"" + currentWidgetTag + "\"");
    } else {
        cruxArrayMetaData.append("\"_childTag\":\"" + cruxPageInnerTag.getLocalName() + "\"");
    }

    if (isHtmlContainerWidget(cruxPageInnerTag)) {
        Element htmlElement = htmlDocument.createElementNS(XHTML_NAMESPACE, "body");
        translateDocument(cruxPageInnerTag, htmlElement, true);
        generateCruxInnerHTMLMetadata(cruxArrayMetaData, htmlElement);
    } else if (allowInnerHTML(currentWidgetTag)) {
        generateCruxInnerHTMLMetadata(cruxArrayMetaData, cruxPageInnerTag);
    } else {
        String innerText = getTextFromNode(cruxPageInnerTag);
        if (innerText.length() > 0) {
            cruxArrayMetaData.append(",\"_text\":\"" + innerText + "\"");
        }
    }
    generateCruxMetaDataAttributes(cruxPageInnerTag, cruxArrayMetaData);
    NodeList childNodes = cruxPageInnerTag.getChildNodes();
    if (childNodes != null && childNodes.getLength() > 0) {
        cruxArrayMetaData.append(",\"_children\":[");
        indent();
        generateCruxMetaData(cruxPageInnerTag, cruxArrayMetaData);
        outdent();
        cruxArrayMetaData.append("]");
    }

    cruxArrayMetaData.append("}");
}