Example usage for javax.xml.soap MessageFactory newInstance

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

Introduction

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

Prototype

public static MessageFactory newInstance() throws SOAPException 

Source Link

Document

Creates a new MessageFactory object that is an instance of the default implementation (SOAP 1.1).

Usage

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

/**
 *
 * Creates a SOAPMessage with bodyDoc as only child.
 *//*from  ww w  . j  av a 2  s.c o  m*/
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:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a digested password, username and nonce.
 * <p>/*from   w ww  .j  ava 2 s  . co m*/
 * The nonce will be generated during the securing process.
 * <p>
 * A freemarker template should be provided, it will be used to generate the
 * final message from the received parameters.
 *
 * @param path
 *            path to the freemarker template
 * @param user
 *            user to include in the message
 * @param password
 *            password to include in the message
 * @return a digested password {@code SOAPMessage}
 * @return a SOAP message with a digested password, username and nonce
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getDigestedPasswordMessage(final String path, final String user,
        final String password) throws Exception {
    return MessageFactory.newInstance().createMessage(new MimeHeaders(),
            getDigestedPasswordStream(path, user, password));
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

@Override
public boolean handleMessage(final SOAPMessageContext context) {

    // Nur fuer den Eingang
    final Boolean isOutBound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (isOutBound) {
        return true;
    }/*from w  ww.  jav  a  2s.c  om*/

    // Servlet-Context speichern
    final ServletContext servletContext = (ServletContext) context.get(MessageContext.SERVLET_CONTEXT);

    SOAPBody soapBody = getSoapBody(context);

    try {

        // Pruefe SOAP-Body
        if (soapBody == null) {
            try {
                // Erstelle neue SOAP-Message mit SOAP-Body
                final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
                soapBody = soapMessage.getSOAPBody();
                context.setMessage(soapMessage);
            } catch (final SOAPException e) {
                LOG.error("Exception beim Erstellen einer SOAP-Message.", e);
            }
            // Request ungueltig - z.B. ungueltiges XML
            throw new InvalidExtraRequestException(resourceBundle.getString(Messages.ERROR_REQUEST_NO_EXTRA));
        }

        // Hole Transport-Element
        final Node transportNode = getTransportElement(soapBody);
        if (transportNode == null) {
            // kein 'Transport'-Element, Request ungueltig
            throw new InvalidExtraRequestException(resourceBundle.getString(Messages.ERROR_REQUEST_NO_EXTRA));
        }

        // Validiere Request-XML gegen eXTra-Schema
        validateExtraRequest(transportNode, servletContext);

    } catch (final InvalidExtraRequestException e) {
        return handleException(soapBody, e.getMessage(), ExtraErrorReasonType.INVALID_REQUEST);
    } catch (final Exception e) {
        LOG.error("Unbekannter Fehler beim Request-Validierung.", e);
        return handleException(soapBody, resourceBundle.getString(Messages.ERROR_REQUEST_VALIDATION_UNKNOWN),
                ExtraErrorReasonType.UNSPECIFIED);
    }
    return true;
}

From source file:org.osgpfoundation.osgp.webdemoapp.application.config.ApplicationContext.java

/**
 * Spring SoapMessageFactory for creating Soap Messages
 * @return SaajSoapMessageFactory/*from w  w w. j a va  2  s .  c o m*/
 */
private SaajSoapMessageFactory messageFactory() {
    final SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory();
    try {
        messageFactory.setMessageFactory(MessageFactory.newInstance());
    } catch (final SOAPException e) {
        e.printStackTrace();
    }
    return messageFactory;
}

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

private void prepareUndeploySOAP(String packageId) throws SOAPException, IOException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlUndeploy = body.addChildElement(ODE_ELEMENT_UNDEPLOY);
    SOAPElement xmlPackageName = xmlUndeploy.addChildElement(ODE_ELEMENT_PACKAGENAME);
    xmlPackageName.setTextContent(packageId);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);// w w w  . ja v a 2s .  com
    fContent = b.toString();
}

From source file:com.usps.UspsServlet.java

private SOAPMessage createSOAPRequest(String parameter) {
    SOAPMessage soapMessage = null;
    try {//ww  w  . j av a2 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  w  w.ja  va  2  s  .  c o  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:org.springframework.ws.transport.http.HttpComponentsMessageSenderIntegrationTest.java

@Test
public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();//ww  w. ja va2  s .  c  o m
    WebServiceConnection connection = null;
    try {

        StaticApplicationContext appContext = new StaticApplicationContext();
        appContext.registerSingleton("messageSender", HttpComponentsMessageSender.class);
        appContext.refresh();

        HttpComponentsMessageSender messageSender = appContext.getBean("messageSender",
                HttpComponentsMessageSender.class);
        connection = messageSender.createConnection(new URI("http://localhost:" + port));

        connection.send(new SaajSoapMessage(messageFactory.createMessage()));
        connection.receive(new SaajSoapMessageFactory(messageFactory));

        appContext.close();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (jettyServer.isRunning()) {
            jettyServer.stop();
        }
    }

}

From source file:net.bpelunit.test.unit.TestSOAPEncoder.java

@Test
public void testDecodeDocLit() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage rcvMessage = factory.createMessage(null,
            this.getClass().getResourceAsStream(PATH_TO_FILES + "doclit2.xmlfrag"));
    SOAPOperationCallIdentifier operation = TestUtil.getCall(PATH_TO_FILES, PARTNER_WSDL, PARTNER_OPERATION,
            SOAPOperationDirectionIdentifier.INPUT);

    ISOAPEncoder encoder = new DocumentLiteralEncoder();
    Element parent = encoder.deconstruct(operation, rcvMessage);

    NamespaceContextImpl nsi = new NamespaceContextImpl();
    nsi.setNamespace("tns", "http://xxx");

    Node node = TestUtil.getNode(parent, nsi, "tns:about");
    assertNotNull(node);//  ww w  .j a v  a  2s .c  o m

    Node node2 = TestUtil.getNode(parent, nsi, "tns:about/tns:me");
    assertNotNull(node2);
}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
public String getToken(PrivateKey pKey, X509Certificate cert)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException, SAXException, IOException, ParserConfigurationException, XmlException,
        UnsupportedOperationException, SOAPException, ConexionSiiException {

    String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_TOKEN");

    String semilla = getSemilla();

    GetTokenDocument req = GetTokenDocument.Factory.newInstance();

    req.addNewGetToken().addNewItem().setSemilla(semilla);

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();

    opts = new XmlOptions();
    opts.setSaveImplicitNamespaces(namespaces);
    opts.setLoadSubstituteNamespaces(namespaces);
    opts.setSavePrettyPrint();/*w w w .j  a v a2  s  .co  m*/
    opts.setSavePrettyPrintIndent(0);

    req = GetTokenDocument.Factory.parse(req.newInputStream(opts), opts);

    // firmo
    req.sign(pKey, cert);

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();

    Name bodyName = envelope.createName("getToken", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("pszXml");

    SOAPElement toKsymbol = gltp.addChildElement(toKname);

    opts = new XmlOptions();
    opts.setCharacterEncoding("ISO-8859-1");
    opts.setSaveImplicitNamespaces(namespaces);

    toKsymbol.addTextNode(req.xmlText(opts));

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    message.writeTo(System.out);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    cl.sii.xmlSchema.RESPUESTADocument resp = null;
    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getTokenResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getTokenReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            opts.setLoadSubstituteNamespaces(namespaces);

            resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) {
        return resp.getRESPUESTA().getRESPBODY().getTOKEN();
    } else {
        throw new ConexionSiiException(
                "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: "
                        + resp.getRESPUESTA().getRESPHDR().getGLOSA());
    }

}