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:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url//w  w w  .j  a v  a2 s. c o  m
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}

From source file:py.una.pol.karaku.test.test.services.KarakuFaultMessageResolverTest.java

/**
 * @return/*  w w  w .  ja v a2  s .c o m*/
 * @throws OPException
 * @throws Exception
 */
private SOAPMessage getFromString(String xml) throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage(new MimeHeaders(),
            new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))));
    return message;
}

From source file:ee.ria.xroad.proxy.serverproxy.ProxyMonitorServiceHandlerTest.java

/**
 * Init class-wide test instances/*from w  ww . j a v a2 s . c  om*/
 */
@BeforeClass
public static void initCommon() throws JAXBException, SOAPException {
    unmarshaller = JAXBContext
            .newInstance(ObjectFactory.class, SoapHeader.class, GetSecurityServerMetricsResponse.class)
            .createUnmarshaller();
    messageFactory = MessageFactory.newInstance();
}

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

private SOAPMessage createSoapMessage(GetChargingPlans value) throws PEPException {
    try {/*from ww  w .j av  a2 s. c o  m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(GetChargingPlans.class);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        jaxbContext.createMarshaller().marshal(value, document);

        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        soapMessage.getSOAPBody().addDocument(document);
        Name headername = soapMessage.getSOAPPart().getEnvelope().createName("Action", "",
                "http://schemas.microsoft.com/ws/2005/05/addressing/none/");
        SOAPHeaderElement soapAction = soapMessage.getSOAPHeader().addHeaderElement(headername);
        soapAction.setMustUnderstand(true);
        soapAction.setTextContent("http://tempuri.org/ISmartCharging/GetChargingPlans");
        return soapMessage;
    } catch (DOMException | JAXBException | ParserConfigurationException | SOAPException ex) {
        throw new PEPException(ex);
    }
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a plain password and username.
 * <p>/*from   w  ww .j av  a2s.  c  o  m*/
 * 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 SOAP message with a plain password and username
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getPlainPasswordMessage(final String path, final String user,
        final String password) throws Exception {
    return MessageFactory.newInstance().createMessage(new MimeHeaders(),
            getPlainPasswordStream(path, user, password));
}

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

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

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

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

    Node node = TestUtil.getNode(parent, nsi, "someFirstPart");
    assertNotNull(node);//from  w  w w  .j  av  a2s . c  o m

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

From source file:eu.europeana.uim.sugarcrmclient.plugin.SugarCRMServiceImpl.java

/**
 * Constructor//  w  w w .  j  ava  2 s.  c  o m
 */
public SugarCRMServiceImpl() {
    this.pollingListeners = new LinkedHashMap<String, PollingListener>();

    BlockingInitializer initializer = new BlockingInitializer() {
        @Override
        public void initializeInternal() {
            MessageFactory mf = null;
            try {
                mf = MessageFactory.newInstance();
            } catch (SOAPException e1) {
                e1.printStackTrace();
            }

            ExtendedSaajSoapMessageFactory mfactory = new ExtendedSaajSoapMessageFactory(mf);
            WebServiceTemplate webServiceTemplate = new WebServiceTemplate(mfactory);

            JibxMarshaller marshaller = new JibxMarshaller();

            marshaller.setStandalone(true);
            marshaller.setTargetClass(eu.europeana.uim.sugarcrmclient.jibxbindings.Login.class);
            marshaller.setTargetClass(eu.europeana.uim.sugarcrmclient.jibxbindings.GetEntries.class);
            marshaller.setEncoding("UTF-8");
            marshaller.setTargetPackage("eu.europeana.uim.sugarcrmclient.jibxbindings");

            try {
                marshaller.afterPropertiesSet();
            } catch (JiBXException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            System.out.println(
                    marshaller.supports(eu.europeana.uim.sugarcrmclient.jibxbindings.GetEntries.class));
            System.out.println(marshaller.supports(eu.europeana.uim.sugarcrmclient.jibxbindings.Login.class));

            webServiceTemplate.setMarshaller(marshaller);
            webServiceTemplate.setUnmarshaller(marshaller);

            sugarwsClient = new SugarWsClientImpl();
            String userName = PropertyReader.getProperty(UimConfigurationProperty.SUGARCRM_USERNAME);
            String password = PropertyReader.getProperty(UimConfigurationProperty.SUGARCRM_PASSWORD);
            String uri = PropertyReader.getProperty(UimConfigurationProperty.SUGARCRM_HOST);
            webServiceTemplate.setDefaultUri(uri);
            sugarwsClient.setUsername(userName);
            sugarwsClient.setPassword(password);
            sugarwsClient.setWebServiceTemplate(webServiceTemplate);

            try {
                sugarwsClient.setSessionID(
                        sugarwsClient.login(ClientUtils.createStandardLoginObject(userName, password)));
            } catch (JIXBLoginFailureException e) {
                sugarwsClient.setSessionID("-1");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("Done");
        }

    };
    initializer.initialize(SugarWsClientImpl.class.getClassLoader());

}

From source file:org.drools.server.CxfSoapClientServerGridTest.java

private SOAPMessage createMessageForKsession(String ksessionName) throws SOAPException {

    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);//from  www. j a  v  a  2 s  .co  m
    String add = "";
    String packages = "org.test";
    if (ksessionName.equals("ksession2")) {
        add = "2";
        packages = "org.grid.test";
    }
    String cmd = "";
    cmd += "<batch-execution lookup=\"" + ksessionName + "\">\n";
    cmd += "  <insert out-identifier=\"message\">\n";
    cmd += "      <" + packages + ".Message" + add + ">\n";
    cmd += "         <text>Helllo World" + ksessionName + "</text>\n";
    cmd += "      </" + packages + ".Message" + add + ">\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);
    OutputStream os = new ByteArrayOutputStream();
    try {
        soapMessage.writeTo(os);
    } catch (IOException ex) {
        Logger.getLogger(CxfSoapClientServerGridTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    //System.out.println("SOAP = "+os.toString());
    return soapMessage;

}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerTest.java

/**
 * Init class-wide test instances//from  w  w  w.j  av  a 2 s. c  o  m
 */
@BeforeClass
public static void initCommon() throws JAXBException, SOAPException {
    unmarshaller = JAXBContext.newInstance(ObjectFactory.class, SoapHeader.class).createUnmarshaller();
    messageFactory = MessageFactory.newInstance();
    marshaller = JAXBContext.newInstance(WsdlRequestData.class).createMarshaller();
}

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();/*from  w w w .j a va  2 s  . c om*/
    return soapMessage;

}