Example usage for javax.xml XMLConstants DEFAULT_NS_PREFIX

List of usage examples for javax.xml XMLConstants DEFAULT_NS_PREFIX

Introduction

In this page you can find the example usage for javax.xml XMLConstants DEFAULT_NS_PREFIX.

Prototype

String DEFAULT_NS_PREFIX

To view the source code for javax.xml XMLConstants DEFAULT_NS_PREFIX.

Click Source Link

Document

Prefix to use to represent the default XML Namespace.

Usage

From source file:com.jkoolcloud.tnt4j.streams.utils.NamespaceMap.java

@Override
public String getPrefix(String namespaceURI) {
    Set<String> nsList = mapURI.get(namespaceURI);
    return CollectionUtils.isEmpty(nsList) ? XMLConstants.DEFAULT_NS_PREFIX : nsList.iterator().next();
}

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

/**
 * Build an appropriate {@link QName} for a namespaced parameter name.
 * /*from   www . j a v  a  2s.com*/
 * @param parameter namespaced parameter name
 * @param namespaces map of registered namespaces
 * @return QName for the parameter
 */
public static QName decodeParameterName(String parameter, NamespaceMap namespaces) {
    String[] parts = parameter.split("\\.", 2);

    // check if parameter name is for a namespace declaration
    if (OpenIDConstants.MESSAGE_NAMESPACE_PREFIX.equals(parts[0])) {
        String alias;

        if (parts.length == 2) {
            alias = parts[1];
        } else {
            alias = XMLConstants.DEFAULT_NS_PREFIX;
        }

        return new NamespaceQName(namespaces.getURI(alias), alias);
    }

    // otherwise, parameter name is for a message parameter
    String alias;
    String localPart;

    if (parts.length == 2) {
        alias = parts[0];
        localPart = parts[1];
    } else {
        alias = XMLConstants.DEFAULT_NS_PREFIX;
        localPart = parts[0];
    }

    return new QName(namespaces.getURI(alias), localPart, alias);
}

From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

/**
 * Generates a XML response that describe the EC2 instances
 *///from ww  w  .j  av a2 s  .c  o m
private byte[] generateDescribeInstancesResponse() {
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final StringWriter out = new StringWriter();
    XMLStreamWriter sw;
    try {
        sw = xmlOutputFactory.createXMLStreamWriter(out);
        sw.writeStartDocument();

        String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
        sw.setDefaultNamespace(namespace);
        sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
        {
            sw.writeStartElement("requestId");
            sw.writeCharacters(UUID.randomUUID().toString());
            sw.writeEndElement();

            sw.writeStartElement("reservationSet");
            {
                if (Files.exists(nodes)) {
                    for (String address : Files.readAllLines(nodes)) {

                        sw.writeStartElement("item");
                        {
                            sw.writeStartElement("reservationId");
                            sw.writeCharacters(UUID.randomUUID().toString());
                            sw.writeEndElement();

                            sw.writeStartElement("instancesSet");
                            {
                                sw.writeStartElement("item");
                                {
                                    sw.writeStartElement("instanceId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("imageId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceState");
                                    {
                                        sw.writeStartElement("code");
                                        sw.writeCharacters("16");
                                        sw.writeEndElement();

                                        sw.writeStartElement("name");
                                        sw.writeCharacters("running");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateDnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("dnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceType");
                                    sw.writeCharacters("m1.medium");
                                    sw.writeEndElement();

                                    sw.writeStartElement("placement");
                                    {
                                        sw.writeStartElement("availabilityZone");
                                        sw.writeCharacters("use-east-1e");
                                        sw.writeEndElement();

                                        sw.writeEmptyElement("groupName");

                                        sw.writeStartElement("tenancy");
                                        sw.writeCharacters("default");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateIpAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("ipAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                        sw.writeEndElement();
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return out.toString().getBytes(UTF_8);
}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *///from   w ww  .  ja v  a 2  s.  c om
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:eu.esdihumboldt.hale.io.wfs.ui.describefeature.WFSDescribeFeatureSource.java

@Override
public boolean updateConfiguration(ImportProvider provider) {
    boolean success = super.updateConfiguration(provider);
    if (success && provider instanceof XmlSchemaReader) {
        // analyze URI and determine relevant elements

        URI loc = provider.getSource().getLocation();
        if (loc != null) {
            URIBuilder b = new URIBuilder(loc);
            String namespace = null;
            String typename = null;
            for (NameValuePair param : b.getQueryParams()) {
                switch (param.getName().toLowerCase()) {
                case "namespace":
                case "namespaces":
                    namespace = param.getValue();
                    break;
                case "typename":
                case "typenames":
                    typename = param.getValue();
                    break;
                }//  w ww.j a v  a2s. c  om
            }

            if (typename != null && !typename.isEmpty()) {
                // parse namespaces
                Map<String, String> prefixToNamespace = new HashMap<>();
                if (namespace != null && !namespace.isEmpty()) {
                    Pattern ex = Pattern.compile("xmlns\\((([\\w\\d_\\.\\-]+)(=|,))?([^)]+)\\)");
                    Matcher matcher = ex.matcher(namespace);

                    while (matcher.find()) {
                        String prefix = matcher.group(2);
                        if (prefix == null) {
                            prefix = XMLConstants.DEFAULT_NS_PREFIX;
                        }
                        String ns = matcher.group(4);
                        prefixToNamespace.put(prefix, ns);
                    }

                    // previously used implementation below does not support
                    // comma separator inside xmlns(...)
                    //                  for (String xmlns : Splitter.on(',').omitEmptyStrings().trimResults()
                    //                        .split(namespace)) {
                    //                     if (xmlns.startsWith("xmlns(") && xmlns.endsWith(")")) {
                    //                        String mapping = xmlns.substring("xmlns(".length(),
                    //                              xmlns.length() - 1);
                    //                        List<String> mp = Splitter.on('=').limit(2).trimResults()
                    //                              .splitToList(mapping);
                    //                        if (mp.size() == 2) {
                    //                           prefixToNamespace.put(mp.get(0), mp.get(1));
                    //                        }
                    //                        else {
                    //                           // mapping for default namespace
                    //                           prefixToNamespace.put(XMLConstants.DEFAULT_NS_PREFIX, mp.get(0));
                    //                        }
                    //                     }
                    //                  }
                }

                Set<QName> elements = new HashSet<>();
                // parse type names
                for (String type : Splitter.on(',').omitEmptyStrings().trimResults().split(typename)) {
                    List<String> nameParts = Splitter.on(':').limit(2).trimResults().splitToList(type);
                    QName name;
                    if (nameParts.size() == 2) {
                        // prefix and name
                        String prefix = nameParts.get(0);
                        String ns = prefixToNamespace.get(prefix);
                        if (ns != null) {
                            name = new QName(ns, nameParts.get(1), prefix);
                        } else {
                            // namespace unknown - fall back to local name
                            // only
                            name = new QName(nameParts.get(1));
                        }
                    } else {
                        // only local name
                        name = new QName(nameParts.get(0));
                    }

                    elements.add(name);
                }

                ((XmlSchemaReader) provider).setRelevantElements(elements);
            }
        }
    }
    return success;
}

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

/**
 * Build an appropriate namespaced parameter name for a {@link QName}.
 * //from  w  ww  .  java2  s. c o 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:fr.acxio.tools.agia.alfresco.AlfrescoCategoryConverter.java

/**
 * Encode a path according to ISO 9075.</br> Each part of the path is
 * encoded by itself, the path separators are preserved.</br> A part of a
 * path is a {@link fr.acxio.tools.agia.alfresco.domain.QName QName},
 * therefore it can use the short or the long representation.
 * /*from w w  w  .  j a  v  a  2 s  .  c  o  m*/
 * @param sPath
 *            a path to encode
 * @return the encoded path
 */
private String encodePath(String sPath) {
    String aResult = sPath;
    if ((sPath != null) && (sPath.length() > 0)) {
        StringBuilder aBuilder = new StringBuilder();
        Matcher aMatcher = PATH_SPLIT_PATTERN.matcher(sPath);
        QName aQName;
        String aGroup2;
        while (aMatcher.find()) {
            if (aMatcher.group(1) != null) {
                aBuilder.append(aMatcher.group(1));
            }
            aGroup2 = aMatcher.group(2);
            if ((aGroup2 != null) && (aGroup2.length() > 0)) {
                try {
                    aQName = new QName(aGroup2, namespaceContext);
                    if (aQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)
                            && aQName.getNamespaceURI().equals(XMLConstants.NULL_NS_URI)) {
                        aBuilder.append(aGroup2); // Not a qname so just
                                                  // pass it
                    } else {
                        aBuilder.append(aQName.getPrefix()).append(":")
                                .append(ISO9075.encode(aQName.getLocalName()));
                    }
                } catch (IllegalArgumentException e) {
                    aBuilder.append(aGroup2);
                }
            }
        }
        aResult = aBuilder.toString();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The path '" + sPath + "' is encoded as '" + aResult + "'");
        }
    }
    return aResult;
}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

public void run() throws SaxonApiException {
    super.run();/*from  www  . jav  a2  s  .  c  om*/

    XdmNode requestDoc = source.read();
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw new UnsupportedOperationException("Not a c:http-request!");
    }

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException("Unsupported attribute on c:http-request: " + name);
            }
        }
    }

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException("The 'href' attribute must be specified on p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    client = new HttpClient();

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    HttpMethodBase httpResult;

    if (method == null) {
        throw new XProcException("Method must be specified.");
    }

    if ("get".equals(method.toLowerCase())) {
        httpResult = doGet();
    } else if ("post".equals(method.toLowerCase())) {
        httpResult = doPost(body);
    } else if ("put".equals(method.toLowerCase())) {
        httpResult = doPut(body);
    } else if ("head".equals(method.toLowerCase())) {
        httpResult = doHead();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(resultNode);
}

From source file:com.xmlcalabash.library.HttpRequest.java

public void gorun() throws SaxonApiException {
    super.gorun();

    XdmNode requestDoc = source.read(stepContext);
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw XProcException.stepError(40);
    }//from  w  ww.j  a va2  s . c o m

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException(step.getNode(),
                        "Unsupported attribute on c:request for p:http-request: " + name);
            }
        }
    }

    String send = step.getExtensionAttribute(cx_send_binary);
    encodeBinary = !"true".equals(send);

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (method == null) {
        throw XProcException.stepError(6);
    }

    if (statusOnly && !detailed) {
        throw XProcException.stepError(4);
    }

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException(step.getNode(),
                "The 'href' attribute must be specified on c:request for p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    // What about cookies
    String saveCookieKey = step.getExtensionAttribute(cx_save_cookies);
    String useCookieKeys = step.getExtensionAttribute(cx_use_cookies);
    String cookieKey = step.getExtensionAttribute(cx_cookies);

    if (saveCookieKey == null) {
        saveCookieKey = cookieKey;
    }

    if (useCookieKeys == null) {
        useCookieKeys = cookieKey;
    }

    client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    client.getParams().setParameter("http.protocol.single-cookie-header", true);

    HttpState state = client.getState();

    if (useCookieKeys != null) {
        for (String key : useCookieKeys.split("\\s+")) {
            for (Cookie cookie : runtime.getCookies(key)) {
                state.addCookie(cookie);
            }
        }
    }

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);

        if ("basic".equals(meth.toLowerCase())) {
            client.getParams().setAuthenticationPreemptive(true);
        }
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                String name = event.getAttributeValue(_name);
                if (name == null) {
                    continue; // this can't happen, right?
                }
                if (name.toLowerCase().equals("content-type")) {
                    // We'll deal with the content-type header later
                    headerContentType = event.getAttributeValue(_value).toLowerCase();
                } else {
                    headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
                }
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    String lcMethod = method.toLowerCase();

    // You can only have a body on PUT or POST
    if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) {
        throw XProcException.stepError(5);
    }

    HttpMethodBase httpResult;

    if ("get".equals(lcMethod)) {
        httpResult = doGet();
    } else if ("post".equals(lcMethod)) {
        httpResult = doPost(body);
    } else if ("put".equals(lcMethod)) {
        httpResult = doPut(body);
    } else if ("head".equals(lcMethod)) {
        httpResult = doHead();
    } else if ("delete".equals(lcMethod)) {
        httpResult = doDelete();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        // Deal with cookies
        if (saveCookieKey != null) {
            runtime.clearCookies(saveCookieKey);

            state = client.getState();
            Cookie[] cookies = state.getCookies();
            for (Cookie cookie : cookies) {
                runtime.addCookie(saveCookieKey, cookie);
            }
        }

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                }
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                } else {
                    throw XProcException.dynamicError(6);
                }
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(stepContext, resultNode);
}

From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java

/**
 * If the reference is a attribute (e.g. sawsdl:modelreference), we add it here (by creating 
 * the according XMLEvent). The ref//w  ww  .j  ava  2  s .  co m
 * @param w
 * @param ref
 * @param se 
 * @throws XMLStreamException
 */
private StartElement handleAttribute(XMLEventWriter w, Reference ref, StartElement se)
        throws XMLStreamException {
    /* we are having attributes which are in both, the reference and the current element. We only add 
     * a new Attribute event, if it is not already contained in the Start Element
     * 
     * Example: 
     *    reference <element ns:attr1="value" reference="http://example.com">
     *  element   <element ns:attr1="value">
     */
    StringBuilder referenceString = new StringBuilder(ref.getTarget().toString());
    Matcher matcher = findAttributeInReference.matcher(referenceString);
    List<Attribute> attributeList = new ArrayList<Attribute>();

    // copy namespaces
    LocalNamespaceContext lnc = new LocalNamespaceContext((BaseNsContext) se.getNamespaceContext());

    while (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();

        String key = null;
        String prefix = null;
        String value = null;

        // [ns:attr1, "value"]      
        String[] l = referenceString.substring(start, end).split("=");
        if (l.length > 0) {
            // [ns, attr1]
            String[] n = l[0].split(":");
            if (n.length == 2) {
                key = n[1];
                prefix = n[0];
            } else {
                key = n[0];
            }
            if (l.length == 2) {
                value = l[1].substring(1, l[1].length() - 1); // remove ""

            }
        }

        // check if this is a namespace definition
        if ((prefix != null) && ("xmlns".contentEquals(prefix))) {
            lnc.put(key, value);
        } else {
            QName name = null;
            // create QName
            if (prefix != null) {
                name = new QName(null, key, prefix);
            } else {
                String namespaceURI = se.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
                name = new QName(namespaceURI, key);
            }
            if (name != null) {
                Attribute created = getXMLEventFactory().createAttribute(name, value);
                attributeList.add(created);
            }
        }
    }

    // remove redundant attribute from reference list
    Iterator<?> it = se.getAttributes();
    while (it.hasNext()) {
        Attribute ae = (Attribute) it.next();
        for (Attribute ar : attributeList) {
            if ((ar.getName().getLocalPart().contentEquals(ae.getName().getLocalPart()))
                    && (ar.getValue().contentEquals(ae.getValue()))) {
                //System.out.println("Attribute removed! -> " + ar.getName() + "= " + ar.getValue());
                attributeList.remove(ar);
                break;

            }
        }
    }

    // merge everything again
    Iterator<? extends Attribute> it2 = se.getAttributes();
    while (it2.hasNext()) {
        attributeList.add(it2.next());
    }

    // create a new element with the attribute set and return it
    return StartElementEventImpl.construct(se.getLocation(), se.getName(), attributeList.iterator(),
            lnc.getNamespaces().iterator(), lnc);

}