Example usage for javax.xml.soap SOAPMessage writeTo

List of usage examples for javax.xml.soap SOAPMessage writeTo

Introduction

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

Prototype

public abstract void writeTo(OutputStream out) throws SOAPException, IOException;

Source Link

Document

Writes this SOAPMessage object to the given output stream.

Usage

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

/**
 * Tests that {@link SOAPMessage#writeTo(java.io.OutputStream)} performs namespace repairing.
 * /*  www.j  a va2 s  .  c om*/
 * @throws Exception
 */
@Validated
@Test
public void testWriteToNamespaceRepairing() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    SOAPPart part = message.getSOAPPart();
    SOAPBody body = part.getEnvelope().getBody();
    body.appendChild(part.createElementNS("urn:ns", "p:test"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    String content = baos.toString("UTF-8");
    assertTrue(content.contains("<p:test xmlns:p=\"urn:ns\"/>"));
}

From source file:be.agiv.security.handler.WSSecurityHandler.java

private void addProofOfPossessionSignature(SOAPMessageContext context, SOAPMessage soapMessage,
        SOAPPart soapPart, WSSecHeader wsSecHeader, WSSecTimestamp wsSecTimeStamp)
        throws SOAPException, IOException, WSSecurityException {
    if (null == this.key) {
        return;/*from  w  w  w  .  ja  v a2  s. c  om*/
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    soapMessage.writeTo(outputStream);
    LOG.debug("SOAP message before signing: " + new String(outputStream.toByteArray()));
    Vector<WSEncryptionPart> signParts = new Vector<WSEncryptionPart>();
    signParts.add(new WSEncryptionPart(wsSecTimeStamp.getId()));

    LOG.debug("token identifier: " + this.tokenIdentifier);

    WSSConfig wssConfig = new WSSConfig();
    WSSecSignature sign = new WSSecSignature(wssConfig);
    if (this.samlReference) {
        sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
        sign.setCustomTokenValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
    } else {
        sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
    }
    sign.setSecretKey(this.key);
    sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
    sign.setCustomTokenId(this.tokenIdentifier);
    sign.prepare(soapPart, null, wsSecHeader);
    sign.setParts(signParts);
    List<Reference> referenceList = sign.addReferencesToSign(signParts, wsSecHeader);
    sign.computeSignature(referenceList, false, null);
}

From source file:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java

/**
 * Constructs and executes a SOAP message.  For {@code basic} authentication, YADA uses the 
 * java soap api, and the {@link SOAPConnection} object stored in the query object.  For 
 * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC}
 * in {@link #YADA_BIN}. //from  www  .j av  a2 s  .  co  m
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    String result = "";
    resetCountParameter(yq);
    SOAPConnection connection = (SOAPConnection) yq.getConnection();
    for (int row = 0; row < yq.getData().size(); row++) {
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();
        String soapUrl = yq.getSoap(row);

        try {
            this.endpoint = new URL(soapUrl);
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();

            byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes());

            // Assume a SOAP message was built previously
            MimeHeaders mimeHeaders = message.getMimeHeaders();
            if ("basic".equals(this.soapAuth.toLowerCase())) {
                mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken));
                mimeHeaders.addHeader("SOAPAction", this.soapAction);
                mimeHeaders.addHeader("Content-Type", "text/xml");
                SOAPHeader header = message.getSOAPHeader();
                SOAPBody body = message.getSOAPBody();
                header.detachNode();

                l.debug("query:\n" + this.queryString);

                try {
                    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(new ByteArrayInputStream(this.soapData.getBytes()));

                    //SOAPBodyElement docElement = 
                    body.addDocument(xml);

                    Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass));

                    SOAPMessage response = connection.call(message, this.endpoint);
                    try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) {
                        response.writeTo(responseOutputStream);
                        result = responseOutputStream.toString();
                    }
                } catch (IOException e) {
                    String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
                l.debug("SOAP Body:\n" + result);
            } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase())
                    || "negotiate".equals(this.soapAuth.toLowerCase())) {
                ArrayList<String> args = new ArrayList<>();
                args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC);
                args.add("-X");
                args.add("-s");
                args.add(this.soapSource + this.soapPath);
                args.add("-u");
                args.add(this.soapDomain + "\\" + this.soapUser);
                args.add("-p");
                args.add(this.soapPass);
                args.add("-a");
                args.add(this.soapAuth);
                args.add("-q");
                args.add(this.soapData);
                args.add("-t");
                args.add(this.soapAction);
                String[] cmds = args.toArray(new String[0]);
                l.debug("Executing soap request via script: " + Arrays.toString(cmds));
                String s = null;
                try {
                    ProcessBuilder pb = new ProcessBuilder(args);
                    l.debug(pb.environment().toString());
                    pb.redirectErrorStream(true);
                    Process p = pb.start();
                    try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                        while ((s = si.readLine()) != null) {
                            l.debug(s);
                            if (null == result) {
                                result = "";
                            }
                            result += s;
                        }
                    }
                } catch (IOException e) {
                    String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'.  Make sure the curl executable is still accessible.";
                    throw new YADAAdaptorExecutionException(msg, e);
                }
            }
        } catch (SOAPException e) {
            String msg = "There was a problem creating or executing the SOAP message, or receiving the response.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (SAXException e) {
            String msg = "Unable to parse SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (ParserConfigurationException e) {
            String msg = "There was a problem creating the xml document for the SOAP message body.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (YADAResourceException e) {
            String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC;
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (MalformedURLException e) {
            String msg = "Can't create URL from provided source and path.";
            throw new YADAAdaptorExecutionException(msg, e);
        } finally {
            try {
                ConnectionFactory.releaseResources(connection, yq.getSoap().get(0));
            } catch (YADAConnectionException e) {
                l.error(e.getMessage());
            }
        }

        yqr.addResult(row, result);

    }

}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test//  w w  w.  ja v a2 s.  com
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

void dumpMessage(String info, SOAPMessage msg) throws SOAPException {
    if (log.isTraceEnabled()) {
        if (info != null) {
            System.err.print(info);
        }//  w  w w.  java  2 s.  c o m

        try {
            msg.writeTo(System.err);
            System.err.println();
        } catch (IOException x) {
            return;
        }
    }
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.olap.OLAPQueryExecuter.java

public JROlapResult createOlapResult() throws Exception {
    prepareQuery();/*from   w  ww.j  a  v a 2 s. c o  m*/

    try {
        IReportConnection conn = IReportManager.getInstance().getDefaultConnection();
        if (conn instanceof MondrianConnection) {
            Connection mconn = ((MondrianConnection) conn).getMondrianConnection();
            if (mconn == null) {
                throw new Exception("The supplied mondrian.olap.Connection object is null.");
            }

            Query query = mconn.parseQuery(queryString);

            xmlaResult = new IROlapResult();

            // create result from a Mondrian Query...
            parseQuery(query);
            return xmlaResult;
            //Result result = mconn.execute(query);
            //return new JRMondrianResult(result);
        } else if (conn instanceof JRXMLADataSourceConnection) {
            JRXMLADataSourceConnection xmlaConnection = ((JRXMLADataSourceConnection) conn);
            xmlaResult = new JRXmlaResult();

            try {
                setAxisSOAPClientConfig();

                this.sf = SOAPFactory.newInstance();
                this.connection = createSOAPConnection();
                SOAPMessage queryMessage = createQueryMessage(xmlaConnection);

                queryMessage.writeTo(System.out);
                System.out.println();

                URL soapURL = new URL(getSoapUrl(xmlaConnection));
                System.out.println("URL: " + soapURL);

                System.out.flush();

                SOAPMessage resultMessage = executeQuery(queryMessage, soapURL);

                parseResult(resultMessage);
            } catch (MalformedURLException e) {
                log.error(e);
                throw new JRRuntimeException(e);
            } catch (SOAPException e) {
                log.error(e);
                throw new JRRuntimeException(e);
            } finally {
                restoreSOAPClientConfig();
            }

            return xmlaResult;
        } else {
            throw new Exception(
                    "The supplied Connection is not an OLAP connection. An XML/A or Mondrian connection is required.");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {

    }
}

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

private void invokeServiceWithProvidedSOAPRequest() throws SoapComponentException {
    try {/* ww w  .j a v  a 2s.  c  o m*/
        final String filename = new StringBuilder(serviceName).append(NAME_DELIMITER).append(operationName)
                .append(NAME_DELIMITER).toString();
        final File requestFile = new File(workingDir, filename + REQUEST_FILE_SUFFIX);
        final File responseFile = new File(workingDir, filename + RESPONSE_FILE_SUFFIX);

        String delimiter = "";
        if (!serviceURI.startsWith("/")) {
            delimiter = "/";
        }
        final ManagedServer managedServer = osbCluster.getManagedServer().get(0);
        final URL url = new URL(DEFAULT_PROTO, managedServer.getHostName(), managedServer.getPort(),
                delimiter + serviceURI);
        final String requestEnvelope = FileUtils.readFileToString(requestFile);
        JAXWSDispatch jaxwsDispatch = new JAXWSDispatch();
        ProgressMonitor.init(3, "Connecting to service..."); //1 progress event in jaxwsDispatch.invoke()
        final SOAPMessage res = jaxwsDispatch.invoke(url, requestEnvelope);

        String msg = "Successfuly received response of operation: " + operationName;
        logger.debug(msg);
        cor.addMsg(msg);

        ProgressMonitor.increment("Saving response to disk...");
        if (responseFile.exists()) {
            FileUtils.forceDelete(responseFile);
        }
        try (FileOutputStream fos = new FileOutputStream(responseFile)) {
            res.writeTo(fos);
        }
        msg = "Response of operation: " + operationName + " was stored in [FILE: %s]";
        logger.debug(String.format(msg, responseFile.getAbsolutePath()));
        cor.addMsg(msg, "<a href='file://" + responseFile.getAbsolutePath() + "'>"
                + responseFile.getAbsolutePath() + "</a>", FileSystem.getRelativePath(responseFile));
        cor.markSuccessful();
    } catch (IOException | SOAPException ex) {
        throw new SoapComponentException(ex);
    }
}

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

private void createExtraErrorAndWriteResponse(final HttpServletResponse httpServletResponse,
        final String errorText)
        throws SOAPException, JAXBException, DatatypeConfigurationException, IOException {

    final MessageFactory factory = MessageFactory.newInstance();
    final SOAPMessage message = factory.createMessage();
    final SOAPBody body = message.getSOAPBody();

    final SOAPFault fault = body.addFault();
    final QName faultName = new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, FaultCode.CLIENT.toString());
    fault.setFaultCode(faultName);//from ww w. ja  v  a 2 s .com
    fault.setFaultString(this.soapFaultString);

    final Detail detail = fault.addDetail();

    final ExtraJaxbMarshaller extraJaxbMarshaller = new ExtraJaxbMarshaller();
    final ExtraErrorReasonType reason = ExtraErrorReasonType.INVALID_REQUEST;
    final ExtraErrorType extraError = ExtraHelper.generateError(reason, this.extraErrorCode, errorText);
    extraJaxbMarshaller.marshalExtraError(extraError, detail);

    // Schreibt die SOAPMessage in einen String.
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    message.writeTo(out);
    // Das Encoding, in dem sich die Message rausschreibt, kann man als
    // Property abfragen.
    final Object encodingProperty = message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
    String soapMessageEncoding = "UTF-8";
    if (encodingProperty != null) {
        soapMessageEncoding = encodingProperty.toString();
    }
    final String errorXml = out.toString(soapMessageEncoding);

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType("text/xml");
    httpServletResponse.getWriter().write(errorXml);
    httpServletResponse.getWriter().flush();
    httpServletResponse.getWriter().close();
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

private String prettyFormatSoapXml(SOAPMessage soap) {
    try {//from   w ww . j  av a  2  s. c om
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soap.writeTo(out);
        String msg = new String(out.toByteArray());
        return prettyFormat(msg);
    } catch (SOAPException | IOException e) {
        return "";
    }
}

From source file:org.kie.camel.component.cxf.CxfSoapTest.java

@Test
public void test1() throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body.addBodyElement(payloadName);/*w w  w.  j  a va 2 s .com*/

    String cmd = "";
    cmd += "<batch-execution lookup=\"ksession1\">\n";
    cmd += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd += "      <org.kie.pipeline.camel.Person>\n";
    cmd += "         <name>salaboy</name>\n";
    cmd += "         <age>27</age>\n";
    cmd += "      </org.kie.pipeline.camel.Person>\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);

    Object object = this.context.createProducerTemplate().requestBody("direct://http", soapMessage);
    OutputStream out = new ByteArrayOutputStream();
    out = new ByteArrayOutputStream();
    soapMessage = (SOAPMessage) object;
    soapMessage.writeTo(out);
    String response = out.toString();
    assertTrue(response.contains("fact-handle identifier=\"salaboy\""));
}