List of usage examples for javax.xml.soap SOAPMessage writeTo
public abstract void writeTo(OutputStream out) throws SOAPException, IOException;
From source file:GoogleSearch.java
public static void main(String args[]) throws Exception { URL url = new URL("http://api.google.com/GoogleSearch.wsdl"); QName serviceName = new QName("urn:GoogleSearch", "GoogleSearchService"); QName portName = new QName("urn:GoogleSearch", "GoogleSearchPort"); Service service = Service.create(url, serviceName); Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE); SOAPMessage request = MessageFactory.newInstance().createMessage(null, new FileInputStream("yourGoogleKey.xml")); SOAPMessage response = dispatch.invoke(request); response.writeTo(System.out); }
From source file:Main.java
public static void main(String[] args) throws Exception { SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance(); SOAPConnection connection = sfc.createConnection(); MessageFactory mf = MessageFactory.newInstance(); SOAPMessage sm = mf.createMessage(); SOAPHeader sh = sm.getSOAPHeader(); SOAPBody sb = sm.getSOAPBody(); sh.detachNode();/*from w ww .j a v a2 s . co m*/ QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d"); SOAPBodyElement bodyElement = sb.addBodyElement(bodyName); QName qn = new QName("aName"); SOAPElement quotation = bodyElement.addChildElement(qn); quotation.addTextNode("TextMode"); System.out.println("\n Soap Request:\n"); sm.writeTo(System.out); System.out.println(); URL endpoint = new URL("http://yourServer.com"); SOAPMessage response = connection.call(sm, endpoint); System.out.println(response.getContentDescription()); }
From source file:SOAPRequest.java
public static void main(String[] args) { try {/*from w w w .ja va 2s.c o m*/ SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance(); SOAPConnection connection = sfc.createConnection(); MessageFactory mf = MessageFactory.newInstance(); SOAPMessage sm = mf.createMessage(); SOAPHeader sh = sm.getSOAPHeader(); SOAPBody sb = sm.getSOAPBody(); sh.detachNode(); QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d"); SOAPBodyElement bodyElement = sb.addBodyElement(bodyName); QName qn = new QName("aName"); SOAPElement quotation = bodyElement.addChildElement(qn); quotation.addTextNode("TextMode"); System.out.println("\n Soap Request:\n"); sm.writeTo(System.out); System.out.println(); URL endpoint = new URL("http://yourServer.com"); SOAPMessage response = connection.call(sm, endpoint); System.out.println(response.getContentDescription()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ/*w w w . jav a2 s . c o m*/ * * @param operation The operation to invoke */ public static void main(String[] args) { try { /*OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("HelloWorld_sayHello"); operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>"); operation.setNamespaceURI("urn:jbosstest"); operation.setOutputMessageName("HelloWorld_sayHelloResponse"); operation.setOutputMessageText("<sayHello><return>0</return></sayHello>"); operation.setSoapActionURI(""); operation.setStyle("document"); operation.setTargetMethodName("sayHello"); operation.setTargetObjectURI(null); operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/ OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("ConversionRateSoapIn"); operation.setInputMessageText( "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>"); operation.setNamespaceURI("http://www.webserviceX.NET/"); operation.setOutputMessageName("ConversionRateSoapOut"); operation.setOutputMessageText( "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>"); operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate"); operation.setStyle("document"); operation.setTargetMethodName("ConversionRate"); operation.setTargetObjectURI(null); operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx"); // Determine if the operation style is RPC boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc"); // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //envelope.addNamespaceDeclaration("", operation.getNamespaceURI()); if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated //return strResponse; } catch (Throwable ex) { log.error("Error invoking operation:"); log.error(ex.getMessage()); } //return ""; }
From source file:net.sf.sripathi.ws.mock.util.WebServiceutil.java
/** * Invokes the web service using SAAJ API. * //ww w . j a v a2 s . c o m * @param request soap request string. * @param url end point URL. * @param user user name for authentication. * @param password password for authentication. * * @return response soap string. */ public static String callWebService(String request, String url, String user, String password) { if (request == null) request = ""; try { SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection(); MimeHeaders hd = new MimeHeaders(); hd.addHeader("Content-Type", "text/xml"); if (StringUtil.isValid(user) && StringUtil.isValid(password)) { String authorization = new String(Base64.encodeBase64((user + ":" + password).getBytes())); hd.addHeader("Authorization", "Basic " + authorization); } SOAPMessage msg = MessageFactory.newInstance().createMessage(hd, new ByteArrayInputStream(request.getBytes())); SOAPMessage resp = conn.call(msg, url); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resp.writeTo(baos); return new String(baos.toByteArray()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return sw.toString(); } }
From source file:Main.java
public static String soapMessageToString(SOAPMessage message) { String result = null;// w w w .j a v a 2s . c om if (message != null) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); message.writeTo(baos); result = baos.toString(); } catch (Exception e) { } finally { if (baos != null) { try { baos.close(); } catch (IOException ioe) { } } } } return result; }
From source file:it.govpay.web.handler.MessageLoggingHandlerUtils.java
@SuppressWarnings("unchecked") public static boolean logToSystemOut(SOAPMessageContext smc, String tipoServizio, int versioneServizio, Logger log) {// w w w. j ava2 s . c o m Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); GpContext ctx = null; Message msg = new Message(); SOAPMessage message = smc.getMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); msg.setContent(baos.toByteArray()); } catch (Exception e) { log.error("Exception in handler: " + e); } Map<String, List<String>> httpHeaders = null; if (outboundProperty.booleanValue()) { ctx = GpThreadLocal.get(); httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_RESPONSE_HEADERS); msg.setType(MessageType.RESPONSE_OUT); ctx.getContext().getResponse().setOutDate(new Date()); ctx.getContext().getResponse().setOutSize(Long.valueOf(baos.size())); } else { try { ctx = new GpContext(smc, tipoServizio, versioneServizio); ThreadContext.put("op", ctx.getTransactionId()); GpThreadLocal.set(ctx); } catch (Exception e) { log.error(e.getMessage(), e); return false; } httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_REQUEST_HEADERS); msg.setType(MessageType.REQUEST_IN); msg.setContentType(((HttpServletRequest) smc.get(MessageContext.SERVLET_REQUEST)).getContentType()); ctx.getContext().getRequest().setInDate(new Date()); ctx.getContext().getRequest().setInSize(Long.valueOf(baos.size())); } if (httpHeaders != null) { for (String key : httpHeaders.keySet()) { if (httpHeaders.get(key) != null) { if (key == null) msg.addHeader(new Property("Status-line", httpHeaders.get(key).get(0))); else if (httpHeaders.get(key).size() == 1) msg.addHeader(new Property(key, httpHeaders.get(key).get(0))); else msg.addHeader(new Property(key, ArrayUtils.toString(httpHeaders.get(key)))); } } } ctx.log(msg); return true; }
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 va 2 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:ee.ria.xroad.common.message.SoapUtils.java
/** * Returns the XML representing the SOAP message as bytes. * @param soap message to be converted to byte content * @return byte[]/*from w w w . java 2s . c om*/ * @throws IOException if errors occur while writing message bytes */ public static byte[] getBytes(SOAPMessage soap) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { soap.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); soap.writeTo(out); } catch (SOAPException e) { // Avoid throwing SOAPException, since it is essentially an // IOException if we cannot produce the XML throw new IOException(e); } return out.toByteArray(); }
From source file:ee.ria.xroad.common.message.SoapUtils.java
/** * Returns the XML representing the SOAP message. * @param soap message to be converted into XML * @param charset charset to use when generating the XML string * @return XML String representing the soap message * @throws IOException in case of errors *//*from ww w .j a v a 2 s . co m*/ public static String getXml(SOAPMessage soap, String charset) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { soap.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); soap.writeTo(out); } catch (SOAPException e) { // Avoid throwing SOAPException, since it is essentially an // IOException if we cannot produce the XML throw new IOException(e); } return out.toString(charset); }