Example usage for javax.xml.namespace QName getNamespaceURI

List of usage examples for javax.xml.namespace QName getNamespaceURI

Introduction

In this page you can find the example usage for javax.xml.namespace QName getNamespaceURI.

Prototype

public String getNamespaceURI() 

Source Link

Document

Get the Namespace URI of this QName.

Usage

From source file:XMLUtils.java

public static Element createElementNS(Document root, QName name) {
    return createElementNS(root, name.getNamespaceURI(), name.getLocalPart());
}

From source file:XMLUtils.java

public static Element createElementNS(Node node, QName name) {
    return createElementNS(node.getOwnerDocument(), name.getNamespaceURI(), name.getLocalPart());
}

From source file:com.evolveum.midpoint.prism.xml.XsdTypeMapper.java

private static <T> Class<T> toJavaType(QName xsdType, boolean errorIfNoMapping) {
    Class<T> javaType = xsdToJavaTypeMap.get(xsdType);
    if (javaType == null) {
        if (errorIfNoMapping && xsdType.getNamespaceURI().equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
            throw new IllegalArgumentException("No type mapping for XSD type " + xsdType);
        } else {//from w  w  w.  j  a  v  a 2 s.  com
            return null;
        }
    }
    return javaType;
}

From source file:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java

/**
 * Checks, if the response contains an XML doc with NS {@link Constants#HTTP_NS}.
 * If it does, the HTTP data (uri, method, status, headers, body) is extracted from the doc
 * and set as the response.//from  w  w  w. ja  va  2s .  c  o m
 *
 * Reverse of {@link com.predic8.membrane.core.http.xml.Request#write(XMLStreamWriter)} and
 * {@link com.predic8.membrane.core.http.xml.Response#write(XMLStreamWriter)}.
 */
public static void unwrapMessageIfNecessary(Message message) {
    if (MimeType.TEXT_XML_UTF8.equals(message.getHeader().getContentType())) {
        try {
            if (message.getBody().getLength() == 0)
                return;

            XMLEventReader parser;
            synchronized (xmlInputFactory) {
                parser = xmlInputFactory.createXMLEventReader(message.getBodyAsStreamDecoded(),
                        message.getCharset());
            }

            /* States:
             * 0 = before root element,
             * 1 = root element has HTTP_NS namespace
             */
            int state = 0;

            boolean keepSourceHeaders = false, foundHeaders = false, foundBody = false;

            while (parser.hasNext()) {
                XMLEvent event = parser.nextEvent();
                switch (state) {
                case 0:
                    if (event.isStartElement()) {
                        QName name = event.asStartElement().getName();
                        if (Constants.HTTP_NS.equals(name.getNamespaceURI())) {
                            state = 1;
                            if ("request".equals(name.getLocalPart())) {
                                Request req = (Request) message;
                                req.setMethod(requireAttribute(event.asStartElement(), "method"));
                                String httpVersion = getAttribute(event.asStartElement(), "http-version");
                                if (httpVersion == null)
                                    httpVersion = "1.1";
                                req.setVersion(httpVersion);
                            }
                        } else {
                            return;
                        }
                    }
                    break;
                case 1:
                    if (event.isStartElement()) {
                        String localName = event.asStartElement().getName().getLocalPart();
                        if ("status".equals(localName)) {
                            Response res = (Response) message;
                            res.setStatusCode(
                                    Integer.parseInt(requireAttribute(event.asStartElement(), "code")));
                            res.setStatusMessage(slurpCharacterData(parser, event.asStartElement()));
                        }
                        if ("uri".equals(localName)) {
                            Request req = (Request) message;
                            req.setUri(requireAttribute(event.asStartElement(), "value"));
                            // uri/... (port,host,path,query) structure is ignored, as value already contains everything
                            slurpXMLData(parser, event.asStartElement());
                        }
                        if ("headers".equals(localName)) {
                            foundHeaders = true;
                            keepSourceHeaders = "true"
                                    .equals(getAttribute(event.asStartElement(), "keepSourceHeaders"));
                        }
                        if ("header".equals(localName)) {
                            String key = requireAttribute(event.asStartElement(), "name");
                            boolean remove = getAttribute(event.asStartElement(), "remove") != null;
                            if (remove && !keepSourceHeaders)
                                throw new XML2HTTPException(
                                        "<headers keepSourceHeaders=\"false\"><header name=\"...\" remove=\"true\"> does not make sense.");
                            message.getHeader().removeFields(key);
                            if (!remove)
                                message.getHeader().add(key,
                                        slurpCharacterData(parser, event.asStartElement()));
                        }
                        if ("body".equals(localName)) {
                            foundBody = true;
                            String type = requireAttribute(event.asStartElement(), "type");
                            if ("plain".equals(type)) {
                                message.setBodyContent(slurpCharacterData(parser, event.asStartElement())
                                        .getBytes(Constants.UTF_8_CHARSET));
                            } else if ("xml".equals(type)) {
                                message.setBodyContent(slurpXMLData(parser, event.asStartElement())
                                        .getBytes(Constants.UTF_8_CHARSET));
                            } else {
                                throw new XML2HTTPException("XML-HTTP doc body type '" + type
                                        + "' is not supported (only 'plain' or 'xml').");
                            }
                        }
                    }
                    break;
                }
            }

            if (!foundHeaders && !keepSourceHeaders)
                message.getHeader().clear();
            if (!foundBody)
                message.setBodyContent(new byte[0]);
        } catch (XMLStreamException e) {
            log.error("", e);
        } catch (XML2HTTPException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Build the Key-Value Form encoded string of parameters used to calculate a signature. The result of this method is
 * suitable for passing to {@link #calculateSignature(Association, String)}.
 * //from  w w  w. j av a  2  s  .  co m
 * @param parameters message parameter map
 * @param signedFields list of fields to include in the signature data
 * @return Key-Value Form encoded string of parameters
 * @throws SecurityException if unable to build the signature data
 */
public static String buildSignatureData(ParameterMap parameters, List<QName> signedFields)
        throws SecurityException {
    log.debug("building signature data with parameters: {}", signedFields);
    Map<String, String> signedParameters = new LinkedHashMap<String, String>();

    for (QName field : signedFields) {
        String parameterName = EncodingUtils.encodeParameterName(field, parameters.getNamespaces());
        if (field instanceof NamespaceQName) {
            signedParameters.put(parameterName, field.getNamespaceURI());
        } else {
            signedParameters.put(parameterName, parameters.get(field));
        }
    }

    try {
        return KeyValueFormCodec.getInstance().encode(signedParameters);
    } catch (EncodingException e) {
        log.error("Unable to sign data - " + e.getMessage());
        throw new SecurityException("Unable to sign data", e);
    }
}

From source file:eu.eidas.auth.commons.attribute.AttributeSetPropertiesConverter.java

/**
 * Converts the given Iterable of <code>AttributeDefinition</code>s to an immutable sorted Map of Strings.
 *
 * @param properties the Iterable of <code>AttributeDefinition</code>s
 * @return an immutable sorted Map of Strings.
 *//*w  w w  .jav  a 2 s.c om*/
@Nonnull
public static ImmutableSortedMap<String, String> toMap(@Nonnull Iterable<AttributeDefinition<?>> attributes) {
    ImmutableSortedMap.Builder<String, String> builder = new ImmutableSortedMap.Builder<String, String>(
            Ordering.natural());
    int i = 0;
    for (AttributeDefinition<?> attributeDefinition : attributes) {
        String id = String.valueOf(++i);
        builder.put(Suffix.NAME_URI.computeEntry(id), attributeDefinition.getNameUri().toASCIIString());
        builder.put(Suffix.FRIENDLY_NAME.computeEntry(id), attributeDefinition.getFriendlyName());
        builder.put(Suffix.PERSON_TYPE.computeEntry(id), attributeDefinition.getPersonType().getValue());
        builder.put(Suffix.REQUIRED.computeEntry(id), String.valueOf(attributeDefinition.isRequired()));
        if (attributeDefinition.isTransliterationMandatory()) {
            builder.put(Suffix.TRANSLITERATION_MANDATORY.computeEntry(id), Boolean.TRUE.toString());
        }
        if (attributeDefinition.isUniqueIdentifier()) {
            builder.put(Suffix.UNIQUE_IDENTIFIER.computeEntry(id), Boolean.TRUE.toString());
        }
        QName xmlType = attributeDefinition.getXmlType();
        builder.put(Suffix.XML_TYPE_NAMESPACE_URI.computeEntry(id), String.valueOf(xmlType.getNamespaceURI()));
        builder.put(Suffix.XML_TYPE_LOCAL_PART.computeEntry(id), String.valueOf(xmlType.getLocalPart()));
        builder.put(Suffix.XML_TYPE_NAMESPACE_PREFIX.computeEntry(id), String.valueOf(xmlType.getPrefix()));
        builder.put(Suffix.ATTRIBUTE_VALUE_MARSHALLER.computeEntry(id),
                attributeDefinition.getAttributeValueMarshaller().getClass().getName());
    }
    return builder.build();
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.XmlUtils.java

public static String getPath(Stack<QName> stack, NamespaceContext ctx) {
    if (ctx == null)
        logger.fatal("NamespaceContext is null");
    StringBuilder ret = new StringBuilder();
    for (QName q : stack) {
        if (q == null)
            throw new IllegalStateException("q is null");
        ret.append("/");
        String prefix = ctx.getPrefix(q.getNamespaceURI());
        if (prefix != null && prefix.length() > 0)
            ret.append(prefix).append(":");
        ret.append(q.getLocalPart());//from   www.  ja v a2  s .  c  om
    }
    return ret.toString();
}

From source file:edu.internet2.middleware.openid.message.encoding.EncodingUtils.java

/**
 * Build an appropriate namespaced parameter name for a {@link QName}.
 * // w  w w  . j ava2s  . co m
 * @param qname QName to convert into parameter name
 * @param namespaces map of registered namespaces
 * @return namespaced parameter name
 */
public static String encodeParameterName(QName qname, NamespaceMap namespaces) {
    String parameter;
    String namespaceAlias = namespaces.getAlias(qname.getNamespaceURI());

    if (qname instanceof NamespaceQName) {
        // parameter name is for a namespace declaration
        parameter = "ns";

        if (namespaceAlias != XMLConstants.DEFAULT_NS_PREFIX) {
            parameter += "." + namespaceAlias;
        }
    } else {
        // otherwise, parameter name is for a message parameter
        parameter = qname.getLocalPart();

        if (namespaceAlias != XMLConstants.DEFAULT_NS_PREFIX) {
            parameter = namespaceAlias + "." + parameter;
        }
    }

    return parameter;
}

From source file:com.evolveum.midpoint.util.QNameUtil.java

public static boolean match(QName a, QName b, boolean caseInsensitive) {
    if (a == null && b == null) {
        return true;
    }/*from   www .  j  a  v a2 s.  co  m*/
    if (a == null || b == null) {
        return false;
    }
    if (!caseInsensitive) {
        // traditional comparison
        if (StringUtils.isBlank(a.getNamespaceURI()) || StringUtils.isBlank(b.getNamespaceURI())) {
            return a.getLocalPart().equals(b.getLocalPart());
        } else {
            return a.equals(b);
        }
    } else {
        // relaxed (case-insensitive) one
        if (!a.getLocalPart().equalsIgnoreCase(b.getLocalPart())) {
            return false;
        }
        if (StringUtils.isBlank(a.getNamespaceURI()) || StringUtils.isBlank(b.getNamespaceURI())) {
            return true;
        } else {
            return a.getNamespaceURI().equals(b.getNamespaceURI());
        }
    }

}

From source file:ee.ria.xroad.common.message.SoapUtils.java

/**
 * Converts a SOAP request to SOAP response, by adding "Response" suffix
 * to the service name in the body./*from w w  w .j a  va2 s . co  m*/
 * @param request SOAP request message to be converted
 * @param callback function to call when the response SOAP object has been created
 * @return the response SoapMessageImpl
 * @throws Exception if errors occur during response message creation
 */
public static SoapMessageImpl toResponse(SoapMessageImpl request, SOAPCallback callback) throws Exception {
    String charset = request.getCharset();

    SOAPMessage soap = createSOAPMessage(new ByteArrayInputStream(request.getBytes()), charset);

    List<SOAPElement> bodyChildren = getChildElements(soap.getSOAPBody());
    if (bodyChildren.size() == 0) {
        return null;
    }

    QName requestElementQName = bodyChildren.get(0).getElementQName();
    String serviceCode = getServiceCode(soap, requestElementQName);

    QName newName = new QName(requestElementQName.getNamespaceURI(), serviceCode + SOAP_SUFFIX_RESPONSE,
            requestElementQName.getPrefix());
    bodyChildren.get(0).setElementQName(newName);

    if (callback != null) {
        callback.call(soap);
    }

    byte[] xml = getBytes(soap);
    return (SoapMessageImpl) new SoapParserImpl().parseMessage(xml, soap, charset, request.getContentType());
}