Example usage for javax.xml.soap MimeHeaders MimeHeaders

List of usage examples for javax.xml.soap MimeHeaders MimeHeaders

Introduction

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

Prototype

public MimeHeaders() 

Source Link

Document

Constructs a default MimeHeaders object initialized with an empty Vector object.

Usage

From source file:hk.hku.cecid.corvus.ws.EBMSMessageHistoryQuerySenderTest.java

private EBMSMessageHistoryRequestData getHttpRequestData() throws Exception {
    // Check content Type
    String contentType = monitor.getContentType();

    if (contentType == null) {
        System.out.println((monitor == null ? "Null Monitor" : "Monitor not null"));
        System.out.println("Lengeth " + monitor.getContentLength());
        Assert.fail("Null Content");
    }//  ww w. j a v a  2 s. c  om

    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "text/xml", mediaType);

    // Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.    
    RequestContext rc = new RequestContext() {
        public String getCharacterEncoding() {
            return "charset=utf-8";
        }

        public int getContentLength() {
            return monitor.getContentLength();
        }

        public String getContentType() {
            return monitor.getContentType();
        }

        public InputStream getInputStream() {
            return monitor.getInputStream();
        }
    };

    BufferedReader bReader = new BufferedReader(new InputStreamReader(monitor.getInputStream()));

    String strLine = "";
    do {
        strLine = bReader.readLine();
    } while (!strLine.contains("SOAP-ENV"));

    MimeHeaders header = new MimeHeaders();
    header.addHeader("Content-Type", "text/xml");

    SOAPMessage msg = MessageFactory.newInstance().createMessage(header,
            new ByteArrayInputStream(strLine.getBytes()));

    EBMSMessageHistoryRequestData data = new EBMSMessageHistoryRequestData();
    data.setMessageId(getElementValue(msg.getSOAPBody(), "tns:messageId"));
    data.setMessageBox(getElementValue(msg.getSOAPBody(), "tns:messageBox"));
    data.setStatus(getElementValue(msg.getSOAPBody(), "tns:status"));
    data.setService(getElementValue(msg.getSOAPBody(), "tns:service"));
    data.setAction(getElementValue(msg.getSOAPBody(), "tns:action"));
    data.setConversationId(getElementValue(msg.getSOAPBody(), "tns:conversationId"));
    data.setCpaId(getElementValue(msg.getSOAPBody(), "tns:cpaId"));
    return data;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext/*  w  w  w  . j a  va  2  s  .c  om*/
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

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

/**
 * Creates a new SOAPMessage object./* w w w  . ja v  a 2s.co m*/
 * @param is input stream containing the SOAP object data
 * @param charset the expected charset of the input stream
 * @return SOAPMessage that's been read from the input stream
 * @throws SOAPException may be thrown if the message is invalid
 * @throws IOException if there is a problem in reading data from the input stream
 */
public static SOAPMessage createSOAPMessage(InputStream is, String charset) throws SOAPException, IOException {
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-type", contentTypeWithCharset(TEXT_XML, charset));

    return MESSAGE_FACTORY.createMessage(mimeHeaders, is);
}

From source file:io.hummer.util.ws.WebServiceClient.java

private SOAPMessage createSOAPMessage(Element request, List<Element> headers, String protocol)
        throws Exception {
    MessageFactory mf = MessageFactory.newInstance(protocol);
    SOAPMessage message = mf.createMessage();
    SOAPBody body = message.getSOAPBody();

    // check if we have a complete soap:Envelope as request..
    String ns = request.getNamespaceURI();
    if (request.getTagName().contains("Envelope")) {
        if (ns.equals("http://schemas.xmlsoap.org/soap/envelope/"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));
        if (ns.equals("http://www.w3.org/2003/05/soap-envelope"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));

    } else {//from   ww  w . j av  a 2s.com
        xmlUtil.appendChild(body, request);
    }
    for (Element h : headers) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    for (Element h : eprParamsAndProps) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    xmlUtil.appendChild(message.getSOAPHeader(), xmlUtil.toElement(
            "<wsa:To xmlns:wsa=\"" + EndpointReference.NS_WS_ADDRESSING + "\">" + endpointURL + "</wsa:To>"));
    message.saveChanges();
    return message;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private Map<String, String> parseResponseXml(String expectedTagName, byte[] data) {
    try {/*  ww w  .  j  a va  2s.  c  o  m*/
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(data));

        if (soapMessage.getSOAPBody().hasFault()) {
            StringWriter writer = new StringWriter();
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(writer));
            } catch (IllegalArgumentException | TransformerException | TransformerFactoryConfigurationError e) {
                writer.append("Failed to dump fault: " + e);
            }

            throw new ResponseException(writer.toString());
        }

        Iterator<SOAPBodyElement> responseBlockIt = soapMessage.getSOAPBody()
                .getChildElements(new QName(serviceType, expectedTagName));
        if (!responseBlockIt.hasNext()) {
            throw new ResponseException(expectedTagName + " tag missing");
        }

        Map<String, String> ret = new HashMap<>();

        SOAPBodyElement responseNode = responseBlockIt.next();
        Iterator<SOAPBodyElement> responseChildrenIt = responseNode.getChildElements();
        while (responseChildrenIt.hasNext()) {
            SOAPBodyElement param = responseChildrenIt.next();
            String name = StringUtils.trim(param.getLocalName().trim());
            String value = StringUtils.trim(param.getValue().trim());

            ret.put(name, value);
        }

        return ret;
    } catch (IllegalArgumentException | IOException | SOAPException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:com.ibm.soatf.component.soap.SOAPComponent.java

private void checkSOAPMessage(boolean ok) throws SoapComponentException {
    ProgressMonitor.init(2, "Loading message from file...");
    String filename = new StringBuilder(serviceName).append(NAME_DELIMITER).append(operationName)
            .append(NAME_DELIMITER).append(RESPONSE_FILE_SUFFIX).toString();
    final File file = new File(workingDir, filename);
    InputStream is = null;/* w ww  . j a  v  a2 s .c om*/
    try {
        final byte[] xmlMessage = FileUtils.readFileToByteArray(file);
        is = new ByteArrayInputStream(xmlMessage);
        SOAPMessage response = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL)
                .createMessage(new MimeHeaders(), is);
        ProgressMonitor.increment("Checking for fault...");
        response.removeAllAttachments();
        SOAPEnvelope envp = response.getSOAPPart().getEnvelope();
        SOAPBody someBody = envp.getBody();
        if (ok) {
            if (someBody.getFault() == null) {
                cor.addMsg("soap body is OK");
                cor.markSuccessful();
            } else {
                final String msg = "found soap fault in response body:\n" + new String(xmlMessage);
                cor.addMsg(msg);
                throw new SoapComponentException(msg);
            }
        } else {
            if (someBody.getFault() != null) {
                cor.addMsg("found soap fault in response body");
                cor.markSuccessful();
            } else {
                final String msg = "response body doesn't contain soap fault:\n" + new String(xmlMessage);
                cor.addMsg(msg);
                throw new SoapComponentException(msg);
            }
        }
    } catch (IOException | SOAPException ex) {
        throw new SoapComponentException("error while trying to parse response", ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                logger.debug("Not able to close input stream. ", ex);
            }
        }
    }
}

From source file:org.apache.axis.transport.http.SimpleAxisWorker.java

/**
 * The main workhorse method./*from  w  ww.j a v a2 s . com*/
 */
public void execute() {
    byte buf[] = new byte[BUFSIZ];
    // create an Axis server
    AxisServer engine = server.getAxisServer();

    // create and initialize a message context
    MessageContext msgContext = new MessageContext(engine);
    Message requestMsg = null;

    // Reusuable, buffered, content length controlled, InputStream
    NonBlockingBufferedInputStream is = new NonBlockingBufferedInputStream();

    // buffers for the headers we care about
    StringBuffer soapAction = new StringBuffer();
    StringBuffer httpRequest = new StringBuffer();
    StringBuffer fileName = new StringBuffer();
    StringBuffer cookie = new StringBuffer();
    StringBuffer cookie2 = new StringBuffer();
    StringBuffer authInfo = new StringBuffer();
    StringBuffer contentType = new StringBuffer();
    StringBuffer contentLocation = new StringBuffer();

    Message responseMsg = null;

    // prepare request (do as much as possible while waiting for the
    // next connection).  Note the next two statements are commented
    // out.  Uncomment them if you experience any problems with not
    // resetting state between requests:
    //   msgContext = new MessageContext();
    //   requestMsg = new Message("", "String");
    //msgContext.setProperty("transport", "HTTPTransport");
    msgContext.setTransportName(transportName);

    responseMsg = null;

    try {
        // assume the best
        byte[] status = OK;

        // assume we're not getting WSDL
        boolean doWsdl = false;

        // cookie for this session, if any
        String cooky = null;

        String methodName = null;

        try {
            // wipe cookies if we're doing sessions
            if (server.isSessionUsed()) {
                cookie.delete(0, cookie.length());
                cookie2.delete(0, cookie2.length());
            }
            authInfo.delete(0, authInfo.length());

            // read headers
            is.setInputStream(socket.getInputStream());
            // parse all headers into hashtable
            MimeHeaders requestHeaders = new MimeHeaders();
            int contentLength = parseHeaders(is, buf, contentType, contentLocation, soapAction, httpRequest,
                    fileName, cookie, cookie2, authInfo, requestHeaders);
            is.setContentLength(contentLength);

            int paramIdx = fileName.toString().indexOf('?');
            if (paramIdx != -1) {
                // Got params
                String params = fileName.substring(paramIdx + 1);
                fileName.setLength(paramIdx);

                log.debug(Messages.getMessage("filename00", fileName.toString()));
                log.debug(Messages.getMessage("params00", params));

                if ("wsdl".equalsIgnoreCase(params))
                    doWsdl = true;

                if (params.startsWith("method=")) {
                    methodName = params.substring(7);
                }
            }

            // Real and relative paths are the same for the
            // SimpleAxisServer
            msgContext.setProperty(Constants.MC_REALPATH, fileName.toString());
            msgContext.setProperty(Constants.MC_RELATIVE_PATH, fileName.toString());
            msgContext.setProperty(Constants.MC_JWS_CLASSDIR, "jwsClasses");
            msgContext.setProperty(Constants.MC_HOME_DIR, ".");

            // !!! Fix string concatenation
            String url = "http://" + getLocalHost() + ":" + server.getServerSocket().getLocalPort() + "/"
                    + fileName.toString();
            msgContext.setProperty(MessageContext.TRANS_URL, url);

            String filePart = fileName.toString();
            if (filePart.startsWith("axis/services/")) {
                String servicePart = filePart.substring(14);
                int separator = servicePart.indexOf('/');
                if (separator > -1) {
                    msgContext.setProperty("objectID", servicePart.substring(separator + 1));
                    servicePart = servicePart.substring(0, separator);
                }
                msgContext.setTargetService(servicePart);
            }

            if (authInfo.length() > 0) {
                // Process authentication info
                //authInfo = new StringBuffer("dXNlcjE6cGFzczE=");
                byte[] decoded = Base64.decode(authInfo.toString());
                StringBuffer userBuf = new StringBuffer();
                StringBuffer pwBuf = new StringBuffer();
                StringBuffer authBuf = userBuf;
                for (int i = 0; i < decoded.length; i++) {
                    if ((char) (decoded[i] & 0x7f) == ':') {
                        authBuf = pwBuf;
                        continue;
                    }
                    authBuf.append((char) (decoded[i] & 0x7f));
                }

                if (log.isDebugEnabled()) {
                    log.debug(Messages.getMessage("user00", userBuf.toString()));
                }

                msgContext.setUsername(userBuf.toString());
                msgContext.setPassword(pwBuf.toString());
            }

            // if get, then return simpleton document as response
            if (httpRequest.toString().equals("GET")) {

                OutputStream out = socket.getOutputStream();
                out.write(HTTP);
                if (fileName.length() == 0) {
                    out.write("301 Redirect\nLocation: /axis/\n\n".getBytes());
                    out.flush();
                    return;
                }
                out.write(status);

                if (methodName != null) {
                    String body = "<" + methodName + ">" +
                    //                               args +
                            "</" + methodName + ">";
                    String msgtxt = "<SOAP-ENV:Envelope" + " xmlns:SOAP-ENV=\"" + Constants.URI_SOAP12_ENV
                            + "\">" + "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";

                    ByteArrayInputStream istream = new ByteArrayInputStream(msgtxt.getBytes());
                    requestMsg = new Message(istream);
                } else if (doWsdl) {
                    engine.generateWSDL(msgContext);

                    Document doc = (Document) msgContext.getProperty("WSDL");
                    if (doc != null) {
                        XMLUtils.normalize(doc.getDocumentElement());
                        String response = XMLUtils.PrettyDocumentToString(doc);
                        byte[] respBytes = response.getBytes();

                        out.write(XML_MIME_STUFF);
                        putInt(buf, out, respBytes.length);
                        out.write(SEPARATOR);
                        out.write(respBytes);
                        out.flush();
                        return;
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append("<h2>And now... Some Services</h2>\n");
                    Iterator i = engine.getConfig().getDeployedServices();
                    sb.append("<ul>\n");
                    while (i.hasNext()) {
                        ServiceDesc sd = (ServiceDesc) i.next();
                        sb.append("<li>\n");
                        sb.append(sd.getName());
                        sb.append(" <a href=\"services/");
                        sb.append(sd.getName());
                        sb.append("?wsdl\"><i>(wsdl)</i></a></li>\n");
                        ArrayList operations = sd.getOperations();
                        if (!operations.isEmpty()) {
                            sb.append("<ul>\n");
                            for (Iterator it = operations.iterator(); it.hasNext();) {
                                OperationDesc desc = (OperationDesc) it.next();
                                sb.append("<li>" + desc.getName());
                            }
                            sb.append("</ul>\n");
                        }
                    }
                    sb.append("</ul>\n");

                    byte[] bytes = sb.toString().getBytes();

                    out.write(HTML_MIME_STUFF);
                    putInt(buf, out, bytes.length);
                    out.write(SEPARATOR);
                    out.write(bytes);
                    out.flush();
                    return;
                }
            } else {

                // this may be "" if either SOAPAction: "" or if no SOAPAction at all.
                // for now, do not complain if no SOAPAction at all
                String soapActionString = soapAction.toString();
                if (soapActionString != null) {
                    msgContext.setUseSOAPAction(true);
                    msgContext.setSOAPActionURI(soapActionString);
                }
                requestMsg = new Message(is, false, contentType.toString(), contentLocation.toString());
            }

            // Transfer HTTP headers to MIME headers for request message.
            MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
            for (Iterator i = requestHeaders.getAllHeaders(); i.hasNext();) {
                MimeHeader requestHeader = (MimeHeader) i.next();
                requestMimeHeaders.addHeader(requestHeader.getName(), requestHeader.getValue());
            }
            msgContext.setRequestMessage(requestMsg);
            // put character encoding of request to message context
            // in order to reuse it during the whole process.   
            String requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }

            // set up session, if any
            if (server.isSessionUsed()) {
                // did we get a cookie?
                if (cookie.length() > 0) {
                    cooky = cookie.toString().trim();
                } else if (cookie2.length() > 0) {
                    cooky = cookie2.toString().trim();
                }

                // if cooky is null, cook up a cooky
                if (cooky == null) {
                    // fake one up!
                    // make it be an arbitrarily increasing number
                    // (no this is not thread safe because ++ isn't atomic)
                    int i = SimpleAxisServer.sessionIndex++;
                    cooky = "" + i;
                }

                msgContext.setSession(server.createSession(cooky));
            }

            // invoke the Axis engine
            engine.invoke(msgContext);

            // Retrieve the response from Axis
            responseMsg = msgContext.getResponseMessage();

            if (responseMsg == null) {
                status = NOCONTENT;
            }
        } catch (Exception e) {
            AxisFault af;
            if (e instanceof AxisFault) {
                af = (AxisFault) e;
                log.debug(Messages.getMessage("serverFault00"), af);
                QName faultCode = af.getFaultCode();
                if (Constants.FAULT_SOAP12_SENDER.equals(faultCode)) {
                    status = SENDER;
                } else if ("Server.Unauthorized".equals(af.getFaultCode().getLocalPart())) {
                    status = UNAUTH; // SC_UNAUTHORIZED
                } else {
                    status = ISE; // SC_INTERNAL_SERVER_ERROR
                }
            } else {
                status = ISE; // SC_INTERNAL_SERVER_ERROR
                af = AxisFault.makeFault(e);
            }

            // There may be headers we want to preserve in the
            // response message - so if it's there, just add the
            // FaultElement to it.  Otherwise, make a new one.
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(af);
                responseMsg.setMessageContext(msgContext);
            } else {
                try {
                    SOAPEnvelope env = responseMsg.getSOAPEnvelope();
                    env.clearBody();
                    env.addBodyElement(new SOAPFault((AxisFault) e));
                } catch (AxisFault fault) {
                    // Should never reach here!
                }
            }
        }

        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null && responseMsg != null) {
            responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
        }
        // Send it on its way...
        OutputStream out = socket.getOutputStream();
        out.write(HTTP);
        out.write(status);

        if (responseMsg != null) {
            if (server.isSessionUsed() && null != cooky && 0 != cooky.trim().length()) {
                // write cookie headers, if any
                // don't sweat efficiency *too* badly
                // optimize at will
                StringBuffer cookieOut = new StringBuffer();
                cookieOut.append("\r\nSet-Cookie: ").append(cooky).append("\r\nSet-Cookie2: ").append(cooky);
                // OH, THE HUMILITY!  yes this is inefficient.
                out.write(cookieOut.toString().getBytes());
            }

            //out.write(XML_MIME_STUFF);
            out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_TYPE + ": "
                    + responseMsg.getContentType(msgContext.getSOAPConstants())).getBytes());
            // Writing the length causes the entire message to be decoded twice.
            //out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_LENGTH + ": " + responseMsg.getContentLength()).getBytes());
            // putInt(out, response.length);

            // Transfer MIME headers to HTTP headers for response message.
            for (Iterator i = responseMsg.getMimeHeaders().getAllHeaders(); i.hasNext();) {
                MimeHeader responseHeader = (MimeHeader) i.next();
                out.write('\r');
                out.write('\n');
                out.write(responseHeader.getName().getBytes());
                out.write(headerEnder);
                out.write(responseHeader.getValue().getBytes());
            }

            out.write(SEPARATOR);
            responseMsg.writeTo(out);
        }

        // out.write(response);
        out.flush();
    } catch (Exception e) {
        log.info(Messages.getMessage("exception00"), e);
    } finally {
        try {
            if (socket != null)
                socket.close();
        } catch (Exception e) {
        }
    }
    if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
        // why then, quit!
        try {
            server.stop();
        } catch (Exception e) {
        }
    }

}

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

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

    // TODO: /*ww w  .j  a va 2 s.  co m*/
    // This is a non performant way to create SOAPMessage. I will serialize
    // the xmlpart content and then create an InputStream of byte.
    // Finally create SOAPMessage using this InputStream.
    // The real solution may involve using non-spec, implementation
    // constructors to create a Message from an Envelope
    try {
        if (log.isDebugEnabled()) {
            log.debug("start getAsSOAPMessage");
        }
        // Get OMElement from XMLPart.
        OMElement element = xmlPart.getAsOMElement();

        // Get the namespace so that we can determine SOAP11 or SOAP12
        OMNamespace ns = element.getNamespace();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        element.serialize(outStream);

        // In some cases (usually inbound) the builder will not be closed after
        // serialization.  In that case it should be closed manually.
        if (element.getBuilder() != null && !element.getBuilder().isCompleted()) {
            element.close(false);
        }

        byte[] bytes = outStream.toByteArray();

        if (log.isDebugEnabled()) {
            String text = new String(bytes);
            log.debug("  inputstream = " + text);
        }

        // Create InputStream
        ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);

        // Create MessageFactory that supports the version of SOAP in the om element
        MessageFactory mf = getSAAJConverter().createMessageFactory(ns.getNamespaceURI());

        // Create soapMessage object from Message Factory using the input
        // stream created from OM.

        // Get the MimeHeaders from the transportHeaders map
        MimeHeaders defaultHeaders = new MimeHeaders();
        if (transportHeaders != null) {
            Iterator it = transportHeaders.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                if (entry.getValue() == null) {
                    // This is not necessarily a problem; log it and make sure not to NPE
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "  Not added to transport header. header =" + key + " because value is null;");
                    }
                } else if (entry.getValue() instanceof String) {
                    // Normally there is one value per key
                    if (log.isDebugEnabled()) {
                        log.debug("  add transport header. header =" + key + " value = " + entry.getValue());
                    }
                    defaultHeaders.addHeader(key, (String) entry.getValue());
                } else {
                    // There may be multiple values for each key.  This code
                    // assumes the value is an array of String.
                    String values[] = (String[]) entry.getValue();
                    for (int i = 0; i < values.length; i++) {
                        if (log.isDebugEnabled()) {
                            log.debug("  add transport header. header =" + key + " value = " + values[i]);
                        }
                        defaultHeaders.addHeader(key, values[i]);
                    }
                }
            }
        }

        // Toggle based on SOAP 1.1 or SOAP 1.2
        String contentType = null;
        if (ns.getNamespaceURI().equals(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE)) {
            contentType = SOAPConstants.SOAP_1_1_CONTENT_TYPE;
        } else {
            contentType = SOAPConstants.SOAP_1_2_CONTENT_TYPE;
        }

        // Override the content-type
        String ctValue = contentType + "; charset=UTF-8";
        defaultHeaders.setHeader("Content-type", ctValue);
        if (log.isDebugEnabled()) {
            log.debug("  setContentType =" + ctValue);
        }
        SOAPMessage soapMessage = mf.createMessage(defaultHeaders, inStream);

        // At this point the XMLPart is still an OMElement.  
        // We need to change it to the new SOAPEnvelope.
        createXMLPart(soapMessage.getSOAPPart().getEnvelope());

        // If axiom read the message from the input stream, 
        // then one of the attachments is a SOAPPart.  Ignore this attachment
        String soapPartContentID = getSOAPPartContentID(); // This may be null

        if (log.isDebugEnabled()) {
            log.debug("  soapPartContentID =" + soapPartContentID);
        }

        List<String> dontCopy = new ArrayList<String>();
        if (soapPartContentID != null) {
            dontCopy.add(soapPartContentID);
        }

        // Add any new attachments from the SOAPMessage to this Message
        Iterator it = soapMessage.getAttachments();
        while (it.hasNext()) {

            AttachmentPart ap = (AttachmentPart) it.next();
            String cid = ap.getContentId();
            if (log.isDebugEnabled()) {
                log.debug("  add SOAPMessage attachment to Message.  cid = " + cid);
            }
            addDataHandler(ap.getDataHandler(), cid);
            dontCopy.add(cid);
        }

        // Add the attachments from this Message to the SOAPMessage
        for (String cid : getAttachmentIDs()) {
            DataHandler dh = attachments.getDataHandler(cid);
            if (!dontCopy.contains(cid)) {
                if (log.isDebugEnabled()) {
                    log.debug("  add Message attachment to SoapMessage.  cid = " + cid);
                }
                AttachmentPart ap = MessageUtils.createAttachmentPart(cid, dh, soapMessage);
                soapMessage.addAttachmentPart(ap);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("  The SOAPMessage has the following attachments");
            Iterator it2 = soapMessage.getAttachments();
            while (it2.hasNext()) {
                AttachmentPart ap = (AttachmentPart) it2.next();
                log.debug("    AttachmentPart cid=" + ap.getContentId());
                log.debug("        contentType =" + ap.getContentType());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("end getAsSOAPMessage");
        }
        return soapMessage;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }

}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//from   ww  w  .  ja va2s.  c  om
public void testMultipleAttachments() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();

    AttachmentPart a1 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a1.setContentType("text/xml");
    msg.addAttachmentPart(a1);
    AttachmentPart a2 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a2.setContentType("text/xml");
    msg.addAttachmentPart(a2);
    AttachmentPart a3 = msg.createAttachmentPart(new DataHandler("text", "text/plain"));
    a3.setContentType("text/plain");
    msg.addAttachmentPart(a3);

    assertTrue(msg.countAttachments() == 3);

    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");

    int nAttachments = 0;
    Iterator iterator = msg.getAttachments(mimeHeaders);
    while (iterator.hasNext()) {
        nAttachments++;
        AttachmentPart ap = (AttachmentPart) iterator.next();
        assertTrue(ap.equals(a1) || ap.equals(a2));
    }
    assertTrue(nAttachments == 2);
}

From source file:org.apache.axis2.saaj.SOAPPartImpl.java

/**
 * Construct a SOAP part from the given input stream.
 * The content type (as provided by the MIME headers) must be SOAP 1.1, SOAP 1.2
 * or XOP (MTOM). MIME packages (multipart/related) are not supported and should be
 * parsed using {@link SOAPMessageImpl#SOAPMessageImpl(InputStream, MimeHeaders).
 * <p>//from   w  w  w.j  av  a2 s .  c  o m
 * If the content type is XOP, xop:Include elements will only be replaced if
 * the <code>attachments</code> parameter is not null.
 *
 * @see MessageFactoryImpl#setProcessMTOM(boolean)
 * 
 * @param parentSoapMsg the parent SOAP message
 * @param inputStream the input stream with the content of the SOAP part
 * @param mimeHeaders the MIME headers
 * @param attachments the set of attachments to be used to substitute xop:Include elements
 * @throws SOAPException
 */
public SOAPPartImpl(SOAPMessageImpl parentSoapMsg, InputStream inputStream, MimeHeaders mimeHeaders,
        Attachments attachments) throws SOAPException {
    ContentType contentType = null;
    if (mimeHeaders == null) {
        //TODO : read string from constants
        this.mimeHeaders = new MimeHeaders();
        this.mimeHeaders.addHeader("Content-ID", IDGenerator.generateID());
        this.mimeHeaders.addHeader("content-type", HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
    } else {
        String contentTypes[] = mimeHeaders.getHeader(HTTPConstants.CONTENT_TYPE);
        if (contentTypes != null && contentTypes.length > 0) {
            try {
                contentType = new ContentType(contentTypes[0]);
            } catch (ParseException ex) {
                throw new SOAPException("Invalid content type '" + contentTypes[0] + "'");
            }
        }
        this.mimeHeaders = SAAJUtil.copyMimeHeaders(mimeHeaders);
    }

    soapMessage = parentSoapMsg;

    String charset;
    boolean isMTOM;
    String soapEnvelopeNamespaceURI;
    SOAPFactory soapFactory;
    if (contentType == null) {
        charset = null;
        isMTOM = false;
        soapFactory = new SOAP11Factory();
        soapEnvelopeNamespaceURI = null;
    } else {
        String baseType = contentType.getBaseType().toLowerCase();
        String soapContentType;
        if (baseType.equals(MTOMConstants.MTOM_TYPE)) {
            isMTOM = true;
            String typeParam = contentType.getParameter("type");
            if (typeParam == null) {
                throw new SOAPException("Missing 'type' parameter in XOP content type");
            } else {
                soapContentType = typeParam.toLowerCase();
            }
        } else {
            isMTOM = false;
            soapContentType = baseType;
        }

        if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_TEXT_XML)) {
            soapEnvelopeNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP11Factory();
        } else if (soapContentType.equals(HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML)) {
            soapEnvelopeNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            soapFactory = new SOAP12Factory();
        } else {
            throw new SOAPException("Unrecognized content type '" + soapContentType + "'");
        }

        charset = contentType.getParameter("charset");
    }

    XMLStreamReader streamReader;
    try {
        if (charset != null) {
            streamReader = StAXUtils.createXMLStreamReader(inputStream, charset);
        } else {
            streamReader = StAXUtils.createXMLStreamReader(inputStream);
        }
    } catch (XMLStreamException e) {
        throw new SOAPException(e);
    }

    StAXSOAPModelBuilder builder;
    if (isMTOM && attachments != null) {
        builder = new MTOMStAXSOAPModelBuilder(streamReader, soapFactory, attachments,
                soapEnvelopeNamespaceURI);
    } else {
        builder = new StAXSOAPModelBuilder(streamReader, soapFactory, soapEnvelopeNamespaceURI);
    }

    try {
        org.apache.axiom.soap.SOAPEnvelope soapEnvelope = builder.getSOAPEnvelope();
        envelope = new SOAPEnvelopeImpl((org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl) soapEnvelope);
        envelope.element.build();
        this.document = envelope.getOwnerDocument();
        envelope.setSOAPPartParent(this);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}