Example usage for javax.xml.soap SOAPElement addAttribute

List of usage examples for javax.xml.soap SOAPElement addAttribute

Introduction

In this page you can find the example usage for javax.xml.soap SOAPElement addAttribute.

Prototype

public SOAPElement addAttribute(QName qname, String value) throws SOAPException;

Source Link

Document

Adds an attribute with the specified name and value to this SOAPElement object.

Usage

From source file:com.googlecode.ddom.frontend.saaj.SOAPElementTest.java

@Validated
@Test//from w w  w.j av  a2  s .  c om
public void testAddAttributeFromNameWithoutNamespace() throws Exception {
    SOAPEnvelope envelope = saajUtil.createSOAP11Envelope();
    SOAPBody body = envelope.addBody();
    SOAPElement element = body.addChildElement(new QName("urn:test", "test"));
    SOAPElement retValue = element.addAttribute(envelope.createName("attr"), "value");
    assertSame(element, retValue);
    Attr attr = element.getAttributeNodeNS(null, "attr");
    assertNull(attr.getNamespaceURI());
    String localName = attr.getLocalName();
    if (localName != null) {
        assertEquals("attr", attr.getLocalName());
    }
    assertNull(attr.getPrefix());
    assertEquals("value", attr.getValue());
}

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

public Object __buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = (Document) convertigoResponse;

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        String targetNamespace = context.project.getTargetNamespace();
        String prefix = getPrefix(context.projectName, targetNamespace);

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();//from w  ww.jav a 2 s .c o  m

        // Add the method response element
        SOAPElement soapMethodResponseElement = null;
        String soapElementName = context.sequenceName != null ? context.sequenceName
                : context.connectorName + "__" + context.transactionName;
        soapElementName += "Response";

        soapMethodResponseElement = sb.addChildElement(se.createName(soapElementName, prefix, targetNamespace));

        if (XsdForm.qualified == context.project.getSchemaElementForm()) {
            soapMethodResponseElement.addAttribute(se.createName("xmlns"), targetNamespace);
        }

        // Add a 'response' root child element or not
        SOAPElement soapResponseElement;
        if (context.sequenceName != null) {
            Sequence sequence = (Sequence) context.requestedObject;
            if (sequence.isIncludeResponseElement()) {
                soapResponseElement = soapMethodResponseElement.addChildElement("response");
            } else {
                soapResponseElement = soapMethodResponseElement;
            }
        } else {
            soapResponseElement = soapMethodResponseElement.addChildElement("response");
        }

        if (soapResponseElement.getLocalName().equals("response")) {
            if (document.getDocumentElement().hasAttributes()) {
                addAttributes(responseMessage, se, context, document.getDocumentElement().getAttributes(),
                        soapResponseElement);
            }
        }

        NodeList childNodes = document.getDocumentElement().getChildNodes();
        int len = childNodes.getLength();
        org.w3c.dom.Node node;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            if (node instanceof Element) {
                addElement(responseMessage, se, context, (Element) node, soapResponseElement);
            }
        }

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

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

private void addAttributes(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        NamedNodeMap attributes, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    int len = attributes.getLength();
    Attr attribute;/* w  w w.  j  av  a 2 s . c  o  m*/
    for (int i = 0; i < len; i++) {
        attribute = (Attr) attributes.item(i);
        String attributeName = attribute.getName();
        String attributeValue = attribute.getNodeValue();
        String attributeNsUri = attribute.getNamespaceURI();
        String attributePrefix = getPrefix(context.projectName, attributeNsUri);

        XmlSchemaAttribute xmlSchemaAttribute = getXmlSchemaAttributeByName(context.projectName, attributeName);
        boolean isGlobal = xmlSchemaAttribute != null;
        if (isGlobal) {
            attributeNsUri = xmlSchemaAttribute.getQName().getNamespaceURI();
            attributePrefix = getPrefix(context.projectName, attributeNsUri);
        }

        if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
            if (attributePrefix == null) {
                soapElement.addAttribute(soapEnvelope.createName(attributeName, prefix, targetNamespace),
                        attributeValue);
            } else {
                soapElement.addAttribute(
                        soapEnvelope.createName(attributeName, attributePrefix, attributeNsUri),
                        attributeValue);
            }
        } else {
            soapElement.addAttribute(soapEnvelope.createName(attributeName), attributeValue);
        }
    }
}

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

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

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//from   w ww  .  ja  va  2  s.c  o m

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

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

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

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

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

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

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

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

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of field values of the given document
* @param fieldNames//  ww w .  j a v a  2s . c  om
* @param site
* @param docId
* @return set of the field values
*/
public Map<String, String> getFieldValues(String[] fieldNames, String site, String docLibrary, String docId,
        boolean dspStsWorks) throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        HashMap<String, String> result = new HashMap<String, String>();

        if (site.compareTo("/") == 0)
            site = ""; // root case

        if (dspStsWorks) {
            StsAdapterWS listService = new StsAdapterWS(baseUrl + site, userName, password, configuration,
                    httpClient);
            StsAdapterSoapStub stub = (StsAdapterSoapStub) listService.getStsAdapterSoapHandler();

            String[] vArray = new String[1];
            vArray[0] = "1.0";
            VersionsHeader myVersion = new VersionsHeader();
            myVersion.setVersion(vArray);

            stub.setHeader("http://schemas.microsoft.com/sharepoint/dsp", "versions", myVersion);

            RequestHeader reqHeader = new RequestHeader();
            reqHeader.setDocument(DocumentType.content);
            reqHeader.setMethod(MethodType.query);

            stub.setHeader("http://schemas.microsoft.com/sharepoint/dsp", "request", reqHeader);

            QueryRequest myRequest = new QueryRequest();

            DSQuery sQuery = new DSQuery();
            sQuery.setSelect("/list[@id='" + docLibrary + "']");
            sQuery.setResultContent(ResultContentType.dataOnly);
            myRequest.setDsQuery(sQuery);

            DspQuery spQuery = new DspQuery();
            spQuery.setRowLimit(1);
            // For the Requested Fields
            if (fieldNames.length > 0) {
                Fields spFields = new Fields();
                Field[] fieldArray = new Field[0];
                ArrayList fields = new ArrayList();

                Field spField = new Field();
                //                      spField.setName( "ID" );
                //                      spField.setAlias( "ID" );
                //                      fields.add( spField );

                for (String fieldName : fieldNames) {
                    spField = new Field();
                    spField.setName(fieldName);
                    spField.setAlias(fieldName);
                    fields.add(spField);
                }
                spFields.setField((Field[]) fields.toArray(fieldArray));
                spQuery.setFields(spFields);
            }
            // Of this document
            DspQueryWhere spWhere = new DspQueryWhere();

            org.apache.axis.message.MessageElement criterion = new org.apache.axis.message.MessageElement(
                    (String) null, "Contains");
            SOAPElement seFieldRef = criterion.addChildElement("FieldRef");
            seFieldRef.addAttribute(SOAPFactory.newInstance().createName("Name"), "FileRef");
            SOAPElement seValue = criterion.addChildElement("Value");
            seValue.addAttribute(SOAPFactory.newInstance().createName("Type"), "String");
            seValue.setValue(docId);

            org.apache.axis.message.MessageElement[] criteria = { criterion };
            spWhere.set_any(criteria);
            spQuery.setWhere((DspQueryWhere) spWhere);

            // Set Criteria
            myRequest.getDsQuery().setQuery(spQuery);

            StsAdapterSoap call = stub;

            // Make Request
            QueryResponse resp = call.query(myRequest);
            org.apache.axis.message.MessageElement[] list = resp.get_any();

            if (Logging.connectors.isDebugEnabled()) {
                Logging.connectors.debug("SharePoint: list xml: '" + list[0].toString() + "'");
            }

            XMLDoc doc = new XMLDoc(list[0].toString());
            ArrayList nodeList = new ArrayList();

            doc.processPath(nodeList, "*", null);
            if (nodeList.size() != 1) {
                throw new ManifoldCFException("Bad xml - missing outer 'ns1:dsQueryResponse' node - there are "
                        + Integer.toString(nodeList.size()) + " nodes");
            }

            Object parent = nodeList.get(0);
            //System.out.println( "Outer NodeName = " + doc.getNodeName(parent) );
            if (!doc.getNodeName(parent).equals("ns1:dsQueryResponse"))
                throw new ManifoldCFException("Bad xml - outer node is not 'ns1:dsQueryResponse'");

            nodeList.clear();
            doc.processPath(nodeList, "*", parent);

            parent = nodeList.get(0); // <Shared_X0020_Documents />

            nodeList.clear();
            doc.processPath(nodeList, "*", parent);

            // Process each result (Should only be one )
            // Get each childs Value and add to return array
            for (int i = 0; i < nodeList.size(); i++) {
                Object documentNode = nodeList.get(i);
                ArrayList fieldList = new ArrayList();

                doc.processPath(fieldList, "*", documentNode);
                for (int j = 0; j < fieldList.size(); j++) {
                    Object field = fieldList.get(j);
                    String fieldData = doc.getData(field);
                    String fieldName = doc.getNodeName(field);
                    // Right now this really only works right for single-valued fields.  For multi-valued
                    // fields, we'd need to know in advance that they were multivalued
                    // so that we could interpret commas as value separators.
                    result.put(fieldName, fieldData);
                }
            }
        } else {
            // SharePoint 2010: Get field values some other way
            // Sharepoint 2010; use Lists service instead
            ListsWS lservice = new ListsWS(baseUrl + site, userName, password, configuration, httpClient);
            ListsSoapStub stub1 = (ListsSoapStub) lservice.getListsSoapHandler();

            String sitePlusDocId = serverLocation + site + docId;
            if (sitePlusDocId.startsWith("/"))
                sitePlusDocId = sitePlusDocId.substring(1);

            GetListItemsQuery q = buildMatchQuery("FileRef", "Text", sitePlusDocId);
            GetListItemsViewFields viewFields = buildViewFields(fieldNames);

            GetListItemsResponseGetListItemsResult items = stub1.getListItems(docLibrary, "", q, viewFields,
                    "1", buildNonPagingQueryOptions(), null);
            if (items == null)
                return result;

            MessageElement[] list = items.get_any();

            if (Logging.connectors.isDebugEnabled()) {
                Logging.connectors.debug("SharePoint: getListItems for '" + docId + "' using FileRef value '"
                        + sitePlusDocId + "' xml response: '" + list[0].toString() + "'");
            }

            ArrayList nodeList = new ArrayList();
            XMLDoc doc = new XMLDoc(list[0].toString());

            doc.processPath(nodeList, "*", null);
            if (nodeList.size() != 1)
                throw new ManifoldCFException("Bad xml - expecting one outer 'ns1:listitems' node - there are "
                        + Integer.toString(nodeList.size()) + " nodes");

            Object parent = nodeList.get(0);
            if (!"ns1:listitems".equals(doc.getNodeName(parent)))
                throw new ManifoldCFException("Bad xml - outer node is not 'ns1:listitems'");

            nodeList.clear();
            doc.processPath(nodeList, "*", parent);

            if (nodeList.size() != 1)
                throw new ManifoldCFException("Expected rsdata result but no results found.");

            Object rsData = nodeList.get(0);

            int itemCount = Integer.parseInt(doc.getValue(rsData, "ItemCount"));
            if (itemCount == 0)
                return result;

            // Now, extract the files from the response document
            ArrayList nodeDocs = new ArrayList();

            doc.processPath(nodeDocs, "*", rsData);

            if (nodeDocs.size() != itemCount)
                throw new ManifoldCFException("itemCount does not match with nodeDocs.size()");

            if (itemCount != 1)
                throw new ManifoldCFException("Expecting only one item, instead saw '" + itemCount + "'");

            Object o = nodeDocs.get(0);

            // Look for all the specified attributes in the record
            for (Object attrName : fieldNames) {
                String attrValue = doc.getValue(o, "ows_" + (String) attrName);
                if (attrValue != null) {
                    result.put(attrName.toString(), valueMunge(attrValue));
                }
            }
        }

        return result;
    } catch (javax.xml.soap.SOAPException e) {
        throw new ManifoldCFException("Soap exception: " + e.getMessage(), e);
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting field values for site " + site
                    + " library " + docLibrary + " document '" + docId + "' - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to get field values for site "
                                        + site + " library " + docLibrary + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + site + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        // I don't know if this is what you get when the library is missing, but here's hoping.
        if (e.getMessage().indexOf("List does not exist") != -1)
            return null;

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception getting field values for site " + site
                    + " library " + docLibrary + " document [" + docId + "] - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }
}

From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java

/**
 * add attributes//from  www.  j  av  a  2s.c  o m
 *
 * @param NameCreator nc
 * @param element     SOAPElement which is the target of the new attributes
 * @param reader      XMLStreamReader whose cursor is at START_ELEMENT
 * @throws SOAPException
 */
protected void addAttributes(NameCreator nc, SOAPElement element, XMLStreamReader reader) throws SOAPException {
    if (log.isDebugEnabled()) {
        log.debug("addAttributes: Entry");
    }

    // Add the attributes from the reader
    int size = reader.getAttributeCount();
    for (int i = 0; i < size; i++) {
        QName qName = reader.getAttributeName(i);
        String prefix = reader.getAttributePrefix(i);
        String value = reader.getAttributeValue(i);
        Name name = nc.createName(qName.getLocalPart(), prefix, qName.getNamespaceURI());
        element.addAttribute(name, value);

        try {
            if (log.isDebugEnabled()) {
                log.debug("Setting attrType");
            }
            String namespace = qName.getNamespaceURI();
            Attr attr = null; // This is an org.w3c.dom.Attr
            if (namespace == null || namespace.length() == 0) {
                attr = element.getAttributeNode(qName.getLocalPart());
            } else {
                attr = element.getAttributeNodeNS(namespace, qName.getLocalPart());
            }
            if (attr != null) {
                String attrType = reader.getAttributeType(i);
                attr.setUserData(SAAJConverter.OM_ATTRIBUTE_KEY, attrType, null);
                if (log.isDebugEnabled()) {
                    log.debug("Storing attrType in UserData: " + attrType);
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("An error occured while processing attrType: " + e.getMessage());
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("addAttributes: Exit");
    }
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

private void appendAttributes(SOAPElement bodyElement, NamedNodeMap nnm, SOAPFactory factory)
        throws SOAPException {
    int len = nnm != null ? nnm.getLength() : 0;
    for (int i = 0; i < len; i++) {
        Node n = nnm.item(i);//w  ww .j a  va2s . c o m
        String nodename = n.getNodeName();
        String nodevalue = n.getNodeValue();
        if ("xmlns".equals(nodename))
            continue;
        if (nodename.startsWith("xmlns:"))
            continue;
        //Special case:  xml:lang
        if ("xml:lang".equals(nodename)) {
            Name xmlLang = factory.createName("lang", "xml", "");
            bodyElement.addAttribute(xmlLang, nodevalue);
        } else
            bodyElement.addAttribute(factory.createName(nodename), nodevalue);
    }
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

@Override
public void handleMessage(SoapMessage message) throws Fault {

    if (anonymousAccessDenied) {
        LOGGER.debug("AnonymousAccess not enabled - no message checking performed.");
        return;//from w  ww.  j a  va  2s .c om
    }

    if (message != null) {
        SoapVersion version = message.getVersion();
        SOAPMessage soapMessage = getSOAPMessage(message);
        SOAPFactory soapFactory = null;
        SOAPElement securityHeader = null;

        //Check if security header exists; if not, execute AnonymousInterceptor logic
        String actor = (String) getOption(WSHandlerConstants.ACTOR);
        if (actor == null) {
            actor = (String) message.getContextualProperty(SecurityConstants.ACTOR);
        }

        Element existingSecurityHeader = null;
        try {
            LOGGER.debug("Checking for security header.");
            existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor);
        } catch (WSSecurityException e1) {
            LOGGER.debug("Issue with getting security header", e1);
        }
        if (existingSecurityHeader == null) {
            LOGGER.debug("Current request has no security header, continuing with AnonymousInterceptor");

            AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class);

            // if there is a policy we need to follow or we are ignoring policies, prepare the SOAP message
            if ((assertionInfoMap != null) || overrideEndpointPolicies) {
                RequestData reqData = new CXFRequestData();

                WSSConfig config = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
                WSSecurityEngine engine = null;
                if (config != null) {
                    engine = new WSSecurityEngine();
                    engine.setWssConfig(config);
                }
                if (engine == null) {
                    engine = new WSSecurityEngine();
                    config = engine.getWssConfig();
                }

                reqData.setWssConfig(config);

                try {
                    soapFactory = SOAPFactory.newInstance();
                } catch (SOAPException e) {
                    LOGGER.error("Could not create a SOAPFactory.", e);
                    return; // can't add anything if we can't create it
                }
                if (soapFactory != null) {
                    //Create security header
                    try {
                        securityHeader = soapFactory.createElement(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX,
                                WSConstants.WSSE_NS);
                        securityHeader.addAttribute(
                                new QName(WSConstants.URI_SOAP11_ENV, WSConstants.ATTR_MUST_UNDERSTAND), "1");
                    } catch (SOAPException e) {
                        LOGGER.error("Unable to create security header for anonymous user.", e);
                        return; // can't create the security - just return
                    }
                }
            }

            EffectivePolicy effectivePolicy = message.get(EffectivePolicy.class);
            Exchange exchange = message.getExchange();
            BindingOperationInfo bindingOperationInfo = exchange.getBindingOperationInfo();
            Endpoint endpoint = exchange.get(Endpoint.class);
            if (null == endpoint) {
                return;
            }
            EndpointInfo endpointInfo = endpoint.getEndpointInfo();

            Bus bus = exchange.get(Bus.class);
            PolicyEngine policyEngine = bus.getExtension(PolicyEngine.class);

            if (effectivePolicy == null) {
                if (policyEngine != null) {
                    if (MessageUtils.isRequestor(message)) {
                        effectivePolicy = policyEngine.getEffectiveClientResponsePolicy(endpointInfo,
                                bindingOperationInfo, message);
                    } else {
                        effectivePolicy = policyEngine.getEffectiveServerRequestPolicy(endpointInfo,
                                bindingOperationInfo, message);
                    }
                }
            }

            //Auto analyze endpoint policies

            //Token Assertions
            String tokenAssertion = null;
            String tokenType = null;

            //Security Binding Assertions
            boolean layoutLax = false;
            boolean layoutStrict = false;
            boolean layoutLaxTimestampFirst = false;
            boolean layoutLaxTimestampLast = false;
            boolean requireClientCert = false;
            QName secBindingAssertion = null;

            //Supporting Token Assertions
            QName supportingTokenAssertion = null;
            boolean policyRequirementsSupported = false;

            // if there is a policy, try to follow it as closely as possible
            if (effectivePolicy != null) {
                Policy policy = effectivePolicy.getPolicy();
                if (policy != null) {
                    AssertionInfoMap infoMap = new AssertionInfoMap(policy);
                    Set<Map.Entry<QName, Collection<AssertionInfo>>> entries = infoMap.entrySet();
                    for (Map.Entry<QName, Collection<AssertionInfo>> entry : entries) {
                        Collection<AssertionInfo> assetInfoList = entry.getValue();
                        for (AssertionInfo info : assetInfoList) {
                            LOGGER.debug("Assertion Name: {}", info.getAssertion().getName().getLocalPart());
                            QName qName = info.getAssertion().getName();
                            StringWriter out = new StringWriter();
                            XMLStreamWriter writer = null;
                            try {
                                writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStreamWriter", e);
                            } catch (FactoryConfigurationError e) {
                                LOGGER.debug("Error with FactoryConfiguration", e);
                            }
                            try {
                                if (writer != null) {
                                    info.getAssertion().serialize(writer);
                                    writer.flush();
                                }
                            } catch (XMLStreamException e) {
                                LOGGER.debug("Error with XMLStream", e);
                            } finally {
                                if (writer != null) {
                                    try {
                                        writer.close();
                                    } catch (XMLStreamException ignore) {
                                        //ignore
                                    }
                                }
                            }
                            LOGGER.trace("Assertion XML: {}", out.toString());
                            String xml = out.toString();

                            // TODO DDF-1205 complete support for dynamic policy handling
                            if (qName.equals(SP12Constants.TRANSPORT_BINDING)) {
                                secBindingAssertion = qName;
                            } else if (qName.equals(SP12Constants.INCLUDE_TIMESTAMP)) {
                                createIncludeTimestamp(soapFactory, securityHeader);
                            } else if (qName.equals(SP12Constants.LAYOUT)) {
                                String xpathLax = "/Layout/Policy/Lax";
                                String xpathStrict = "/Layout/Policy/Strict";
                                String xpathLaxTimestampFirst = "/Layout/Policy/LaxTimestampFirst";
                                String xpathLaxTimestampLast = "/Layout/Policy/LaxTimestampLast";

                            } else if (qName.equals(SP12Constants.TRANSPORT_TOKEN)) {

                            } else if (qName.equals(SP12Constants.HTTPS_TOKEN)) {
                                String xpath = "/HttpsToken/Policy/RequireClientCertificate";

                            } else if (qName.equals(SP12Constants.SIGNED_SUPPORTING_TOKENS)) {
                                String xpath = "/SignedSupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(SP12Constants.SUPPORTING_TOKENS)) {
                                String xpath = "/SupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
                                tokenType = retrieveXmlValue(xml, xpath);
                                supportingTokenAssertion = qName;

                            } else if (qName.equals(
                                    org.apache.cxf.ws.addressing.policy.MetadataConstants.ADDRESSING_ASSERTION_QNAME)) {
                                createAddressing(message, soapMessage, soapFactory);

                            } else if (qName.equals(SP12Constants.TRUST_13)) {

                            } else if (qName.equals(SP12Constants.ISSUED_TOKEN)) {
                                //Check Token Assertion
                                String xpath = "/IssuedToken/@IncludeToken";
                                tokenAssertion = retrieveXmlValue(xml, xpath);

                            } else if (qName.equals(SP12Constants.WSS11)) {

                            }
                        }
                    }

                    //Check security and token policies
                    if (tokenAssertion != null && tokenType != null
                            && tokenAssertion.trim().equals(SP12Constants.INCLUDE_ALWAYS_TO_RECIPIENT)
                            && tokenType.trim().equals(TOKEN_SAML20)) {
                        policyRequirementsSupported = true;
                    } else {
                        LOGGER.warn(
                                "AnonymousInterceptor does not support the policies presented by the endpoint.");
                    }

                } else {
                    if (overrideEndpointPolicies) {
                        LOGGER.debug(
                                "WS Policy is null, override is true - an anonymous assertion will be generated");
                    } else {
                        LOGGER.warn(
                                "WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                    }
                }
            } else {
                if (overrideEndpointPolicies) {
                    LOGGER.debug(
                            "Effective WS Policy is null, override is true - an anonymous assertion will be generated");
                } else {
                    LOGGER.warn(
                            "Effective WS Policy is null, override flag is false - no anonymous assertion will be generated.");
                }
            }

            if (policyRequirementsSupported || overrideEndpointPolicies) {
                LOGGER.debug("Creating anonymous security token.");
                if (soapFactory != null) {
                    HttpServletRequest request = (HttpServletRequest) message
                            .get(AbstractHTTPDestination.HTTP_REQUEST);
                    createSecurityToken(version, soapFactory, securityHeader, request.getRemoteAddr());
                    try {
                        // Add security header to SOAP message
                        soapMessage.getSOAPHeader().addChildElement(securityHeader);
                    } catch (SOAPException e) {
                        LOGGER.error("Issue when adding security header to SOAP message:" + e.getMessage());
                    }
                } else {
                    LOGGER.debug("Security Header was null so not creating a SAML Assertion");
                }
            }
        } else {
            LOGGER.debug("SOAP message contains security header, no action taken by the AnonymousInterceptor.");
        }
        if (LOGGER.isTraceEnabled()) {
            try {
                LOGGER.trace("SOAP request after anonymous interceptor: {}",
                        SecurityLogger.getFormattedXml(soapMessage.getSOAPHeader().getParentNode()));
            } catch (SOAPException e) {
                //ignore
            }
        }
    } else {
        LOGGER.error("Incoming SOAP message is null - anonymous interceptor makes no sense.");
    }
}

From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java

private void appendAttributes(SOAPElement bodyElement, NamedNodeMap nnm, SOAPFactory factory)
        throws SOAPException {
    int len = nnm != null ? nnm.getLength() : 0;
    for (int i = 0; i < len; i++) {
        Node n = nnm.item(i);/* www. j av  a  2  s.  c  o  m*/
        String nodename = n.getNodeName();
        String nodevalue = n.getNodeValue();
        if ("xmlns".equals(nodename))
            continue;
        //Special case:  xml:lang
        if ("xml:lang".equals(nodename)) {
            Name xmlLang = factory.createName("lang", "xml", "http://www.w3.org/TR/REC-xml/");
            bodyElement.addAttribute(xmlLang, nodevalue);
        } else
            bodyElement.addAttribute(factory.createName(nodename), nodevalue);
    }
}

From source file:org.jboss.jaxr.juddi.transport.WS4EESaajTransport.java

private SOAPElement getSOAPElement(SOAPBody soapBody, Element elem) {
    String xmlns = IRegistry.UDDI_V2_NAMESPACE;
    SOAPElement soapElement = null;
    SOAPFactory factory = null;/*w w w  .ja  v a2s .  c o  m*/
    try {
        factory = SOAPFactory.newInstance();
        //Go through the element
        String name = elem.getNodeName();
        String nsuri = elem.getNamespaceURI();
        if (nsuri == null)
            nsuri = xmlns;
        soapElement = factory.createElement(name, "ns1", nsuri);
        //Get Attributes
        if (elem.hasAttributes()) {
            NamedNodeMap nnm = elem.getAttributes();
            int len = nnm != null ? nnm.getLength() : 0;
            for (int i = 0; i < len; i++) {
                Node n = nnm.item(i);
                String nodename = n.getNodeName();
                String nodevalue = n.getNodeValue();
                soapElement.addAttribute(factory.createName(nodename), nodevalue);
            }
        } else {
            soapElement.addAttribute(factory.createName("xmlns:ns1"), nsuri);
        }

        NodeList nlist = elem.getChildNodes();
        int len = nlist != null ? nlist.getLength() : 0;

        for (int i = 0; i < len; i++) {
            Node node = nlist.item(i);
            short nodeType = node != null ? node.getNodeType() : -100;
            if (Node.ELEMENT_NODE == nodeType) {
                soapElement.addChildElement(getSOAPElement(soapBody, (Element) node));
            } else if (nodeType == Node.TEXT_NODE) {
                soapElement.addTextNode(node.getNodeValue());
            }

        }
    } catch (SOAPException e) {
        e.printStackTrace();
    }
    return soapElement;
}