Example usage for javax.xml.soap MessageFactory createMessage

List of usage examples for javax.xml.soap MessageFactory createMessage

Introduction

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

Prototype

public abstract SOAPMessage createMessage() throws SOAPException;

Source Link

Document

Creates a new SOAPMessage object with the default SOAPPart , SOAPEnvelope , SOAPBody , and SOAPHeader objects.

Usage

From source file:it.cnr.icar.eric.common.soap.SOAPSender.java

/**
 *
 * Creates a SOAPMessage with bodyDoc as only child.
 *//*from   w w  w .  j  a v  a  2 s . com*/
public SOAPMessage createSOAPMessage(Document bodyDoc) throws JAXRException {
    SOAPMessage msg = null;

    try {
        MessageFactory factory = MessageFactory.newInstance();
        msg = factory.createMessage();
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        //SOAPHeader sh = se.getHeader(); 
        SOAPBody sb = se.getBody();

        sb.addDocument(bodyDoc);
        msg.saveChanges();
    } catch (SOAPException e) {
        e.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.URLNotFound"), e);
    }
    return msg;
}

From source file:test.integ.be.fedict.hsm.ws.WSS4JTest.java

@Test
public void testSecurity() throws Exception {
    QName serviceName = new QName("http://www.example.com/test", "TestService");
    Service service = Service.create(serviceName);
    QName portName = new QName("http://www.example.com/test", "TestPort");
    String endpointAddress = this.baseURL + "test";
    LOG.debug("endpoint address: " + endpointAddress);
    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    BindingProvider bindingProvider = (BindingProvider) dispatch;
    SOAPBinding soapBinding = (SOAPBinding) bindingProvider.getBinding();
    List handlerChain = soapBinding.getHandlerChain();
    handlerChain.add(new WSS4JTestSOAPHandler());
    soapBinding.setHandlerChain(handlerChain);
    MessageFactory messageFactory = soapBinding.getMessageFactory();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPBody soapBody = soapMessage.getSOAPBody();
    QName payloadName = new QName("http://www.example.com/test", "Payload", "prefix");
    SOAPBodyElement soapBodyElement = soapBody.addBodyElement(payloadName);
    soapBodyElement.addTextNode("hello world");

    SOAPMessage replyMessage = dispatch.invoke(soapMessage);
}

From source file:com.polivoto.networking.SoapClient.java

private SOAPMessage createSOAPRequest() throws SOAPException, IOException {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://votingservice.develops.capiz.org";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /* El siguiente es un ejemplo tomado de donde me bas para armar la solicitud.
    Constructed SOAP Request Message:// w ww.j  a  v a 2 s.  c o  m
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
        <example:VerifyEmail>
            <example:email>mutantninja@gmail.com</example:email>
            <example:LicenseKey>123</example:LicenseKey>
        </example:VerifyEmail>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("serviceChooser", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("json", "example");
    soapBodyElem1.addTextNode(json.toString());
    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "serviceChooser");
    soapMessage.saveChanges();
    return soapMessage;
}

From source file:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java

private void prepareDeploySOAP(File file) throws IOException, SOAPException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlDeploy = body.addChildElement(ODE_ELEMENT_DEPLOY);
    SOAPElement xmlZipFilename = xmlDeploy.addChildElement(ODE_ELEMENT_ZIPNAME);
    xmlZipFilename.setTextContent(FilenameUtils.getName(file.toString()).split("\\.")[0]);

    SOAPElement xmlZipContent = xmlDeploy.addChildElement(ODE_ELEMENT_PACKAGE);
    SOAPElement xmlBase64ZipFile = xmlZipContent.addChildElement(ODE_ELEMENT_ZIP, "dep", NS_DEPLOY_SERVICE);

    xmlBase64ZipFile.addAttribute(new QName(NS_XML_MIME, CONTENT_TYPE_STRING), ZIP_CONTENT_TYPE);

    StringBuilder content = new StringBuilder();
    byte[] arr = FileUtils.readFileToByteArray(file);
    byte[] encoded = Base64.encodeBase64Chunked(arr);
    for (int i = 0; i < encoded.length; i++) {
        content.append((char) encoded[i]);
    }/*w w w  .j  a v a2 s . c om*/

    xmlBase64ZipFile.setTextContent(content.toString());

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);
    fContent = b.toString();
}

From source file:com.usps.UspsServlet.java

private SOAPMessage createSOAPRequest(String parameter) {
    SOAPMessage soapMessage = null;
    try {/*from www  .jav  a  2 s.  c o  m*/
        MessageFactory messageFactory = MessageFactory.newInstance();
        soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
        envelope.addNamespaceDeclaration("upss", "http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0");
        envelope.addNamespaceDeclaration("wsf", "http://www.ups.com/schema/wsf");
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.addNamespaceDeclaration("common", "http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0");

        // SOAP Body Generated Here
        // all of the nodes below are mandatory
        // if any optional nodes are desired refer to the ECHO API or SOAPUI for
        // exact Node names
        SOAPBody soapBody = envelope.getBody();

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("Security", "wsse");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message:");
        soapMessage.writeTo(System.out);

    } catch (SOAPException | IOException ex) {
        Logger.getLogger(UspsServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return soapMessage;
}

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  w ww  . j a  v  a2  s  . co  m*/
    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:SendSOAPMessage.java

/**
 * send a simple soap message with JAXM API.
 *//*from   w w  w  .  ja  va2  s .co  m*/
public void sendMessage(String url) {

    try {
        /**
         * Construct a default SOAP message factory.
         */
        MessageFactory mf = MessageFactory.newInstance();
        /**
         * Create a SOAP message object.
         */
        SOAPMessage soapMessage = mf.createMessage();
        /**
         * Get SOAP part.
         */
        SOAPPart soapPart = soapMessage.getSOAPPart();
        /**
         * Get SOAP envelope.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        /**
         * Get SOAP body.
         */
        SOAPBody soapBody = soapEnvelope.getBody();

        /**
         * Add child element with the specified name.
         */
        SOAPElement element = soapBody.addChildElement("HelloWorld");

        /**
         * Add text message
         */
        element.addTextNode("Welcome to SunOne Web Services!");

        soapMessage.saveChanges();

        /**
         * Construct a default SOAP connection factory.
         */
        SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();

        /**
         * Get SOAP connection.
         */
        SOAPConnection soapConnection = connectionFactory.createConnection();

        /**
         * Construct endpoint object.
         */
        URLEndpoint endpoint = new URLEndpoint(url);

        /**
         * Send SOAP message.
         */
        SOAPMessage resp = soapConnection.call(soapMessage, endpoint);

        /**
         * Print response to the std output.
         */
        resp.writeTo(System.out);

        /**
         * close the connection
         */
        soapConnection.close();

    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (SOAPException soape) {
        soape.printStackTrace();
    }
}

From source file:org.soapfromhttp.service.CallSOAP.java

/**
 * Contruction dynamique de la requte SOAP
 *
 * @param pBody/* w ww.  ja  v  a 2s .com*/
 * @param method
 * @return SOAPMessage
 * @throws SOAPException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private SOAPMessage createSOAPRequest(final String pBody, final String method)
        throws SOAPException, IOException, SAXException, ParserConfigurationException {

    // Prcise la version du protocole SOAP  utiliser (ncessaire pour les appels de WS Externe)
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

    SOAPMessage soapMessage = messageFactory.createMessage();

    MimeHeaders headers = soapMessage.getMimeHeaders();

    // Prcise la mthode du WSDL  interroger
    headers.addHeader("SOAPAction", method);
    // Encodage UTF-8
    headers.addHeader("Content-Type", "text/xml;charset=UTF-8");

    final SOAPBody soapBody = soapMessage.getSOAPBody();

    // convert String into InputStream - traitement des caracres escaps > < ... (contraintes de l'affichage IHM)
    //InputStream is = new ByteArrayInputStream(HtmlUtils.htmlUnescape(pBody).getBytes());
    InputStream is = new ByteArrayInputStream(pBody.getBytes());
    DocumentBuilder builder = null;

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    // Important  laisser sinon KO
    builderFactory.setNamespaceAware(true);
    try {
        builder = builderFactory.newDocumentBuilder();

        Document document = builder.parse(is);

        soapBody.addDocument(document);
    } catch (ParserConfigurationException e) {
        MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
    } finally {
        is.close();
        if (builder != null) {
            builder.reset();
        }
    }
    soapMessage.saveChanges();

    return soapMessage;
}

From source file:backend.Weather.java

private SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    String serverURI = "http://ws.cdyne.com/";
    SOAPEnvelope envelope = soapPart.getEnvelope();

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetCityWeatherByZIP");
    QName attributeName = new QName("xmlns");
    soapBodyElem.addAttribute(attributeName, "http://ws.cdyne.com/WeatherWS/");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("ZIP");
    soapBodyElem1.addTextNode("02215");
    soapMessage.saveChanges();/*  ww  w  .j  a  v a 2s.com*/
    return soapMessage;

}

From source file:com.fortify.bugtracker.tgt.archer.connection.ArcherAuthenticatingRestConnection.java

public Long addValueToValuesList(Long valueListId, String value) {
    LOG.info("[Archer] Adding value '" + value + "' to value list id " + valueListId);
    // Adding items to value lists is not supported via REST API, so we need to revert to SOAP API
    // TODO Simplify this method?
    // TODO Make this method more fail-safe (like checking for the correct response element)?
    Long result = null;/*from w w  w .  j a v  a 2 s. c  o m*/
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(
                envelope.createName("CreateValuesListValue", "", "http://archer-tech.com/webservices/"));
        bodyElement.addChildElement("sessionToken").addTextNode(tokenProviderRest.getToken());
        bodyElement.addChildElement("valuesListId").addTextNode(valueListId + "");
        bodyElement.addChildElement("valuesListValueName").addTextNode(value);
        message.saveChanges();

        SOAPMessage response = executeRequest(HttpMethod.POST,
                getBaseResource().path("/ws/field.asmx").request()
                        .header("SOAPAction", "\"http://archer-tech.com/webservices/CreateValuesListValue\"")
                        .accept("text/xml"),
                Entity.entity(message, "text/xml"), SOAPMessage.class);
        @SuppressWarnings("unchecked")
        Iterator<Object> it = response.getSOAPBody().getChildElements();
        while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof SOAPElement) {
                result = new Long(((SOAPElement) o).getTextContent());
            }
        }
        System.out.println(response);
    } catch (SOAPException e) {
        throw new RuntimeException("Error executing SOAP request", e);
    }
    return result;
}