List of usage examples for javax.xml.soap SOAPBody addDocument
public SOAPBodyElement addDocument(org.w3c.dom.Document document) throws SOAPException;
From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java
/** * Performs JAX-WS service call using SOAP API. * * @param url//from w ww .j a va2 s. co 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:it.cnr.icar.eric.common.soap.SOAPSender.java
/** * * Creates a SOAPMessage with bodyDoc as only child. */// w ww. java 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.centurylink.mdw.hub.servlet.SoapServlet.java
protected String createOldStyleSoapResponse(String soapVersion, String xml) throws SOAPException { try {/*from w w w .j a v a 2 s. c o m*/ SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.addDocument(DomHelper.toDomDocument(xml)); return DomHelper.toXmlNoWhiteSpace(soapMessage.getSOAPPart()); } catch (Exception ex) { throw new SOAPException(ex.getMessage(), ex); } }
From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java
/** * Allow version specific factory passed in TODO: allow specifying response * headers/*www . j a v a2s . com*/ */ protected String createSoapResponse(String soapVersion, String xml) throws SOAPException { try { SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.addDocument(DomHelper.toDomDocument(xml)); return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement()); } catch (Exception ex) { throw new SOAPException(ex.getMessage(), ex); } }
From source file:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java
private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException { log.debug("Entered send: " + cb.getName()); // set up the factories and create a SOAP factory SOAPConnection soapConnection; Document doc = null;//from ww w .ja v a2 s .co m URL endpoint = null; try { soapConnection = SOAPConnectionFactory.newInstance().createConnection(); MessageFactory messageFactory = MessageFactory.newInstance(); // Create a message from the message factory. SOAPMessage soapMessage = messageFactory.createMessage(); // Set the SOAP Action here MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", cb.getAction()); // set credentials // String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()); String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64( (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes())); headers.addHeader("Authorization", "Basic " + authorization); log.debug("Authentication: " + authorization); // create a SOAP part have populate the envelope SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING); SOAPHeader head = envelope.getHeader(); if (head == null) head = envelope.addHeader(); // create a SOAP body SOAPBody body = envelope.getBody(); log.debug("Request XSL Style Sheet:\n" + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl()))); // convert request string to document and then transform body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl())); // build the request structure soapMessage.saveChanges(); log.debug("Soap request successfully built: "); log.debug(" Body:\n" + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body)))); if (shConfig.useProxy()) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", shConfig.getProxyHost()); System.setProperty("http.proxyPort", "" + shConfig.getProxyPort()); if (shConfig.useProxyCredentials()) { System.setProperty("http.proxyUser", shConfig.getProxyUser()); System.setProperty("http.proxyPassword", shConfig.getProxyPassword()); } } endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint())); // now make that call over the SOAP connection SOAPMessage reply = null; AdapterException ae = null; for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) { log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint); try { reply = soapConnection.call(soapMessage, endpoint); log.debug("Attempt " + i + ": received response: " + reply); } catch (Exception e) { ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint), e); Thread.sleep(100); } } // close down the connection soapConnection.close(); if (reply == null) throw ae; SOAPFault fault = reply.getSOAPBody().getFault(); if (fault == null) { doc = reply.getSOAPBody().extractContentAsDocument(); } else { // Extracts the entire Soap Fault message coming back from CIS String faultString = XmlUtils.nodeToString(fault); throw new AdapterException(503, faultString, null); } } catch (AdapterException e) { throw e; } catch (Exception e) { throw new AdapterException(504, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())), e); } finally { if (shConfig.useProxy()) { System.setProperty("http.proxySet", "false"); } } log.debug("Exiting send: " + cb.getName()); return doc; }
From source file:org.soapfromhttp.service.CallSOAP.java
/** * Contruction dynamique de la requte SOAP * * @param pBody/*from www .j ava 2 s .c o m*/ * @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: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}. /* w w w . j av a2s . com*/ * @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:it.cnr.icar.eric.common.SOAPMessenger.java
/** Send a SOAP request to the registry server. Main entry point for * this class. If credentials have been set on the registry connection, * they will be used to sign the request. * * @param requestString/* w w w . j ava2 s. c o m*/ * String that will be placed in the body of the * SOAP message to be sent to the server * * @param attachments * HashMap consisting of entries each of which * corresponds to an attachment where the entry key is the ContentId * and the entry value is a javax.activation.DataHandler of the * attachment. A parameter value of null means no attachments. * * @return * RegistryResponseHolder that represents the response from the * server */ @SuppressWarnings("unchecked") public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments) throws JAXRException { boolean logRequests = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false")) .booleanValue(); if (logRequests) { PrintStream requestLogPS = null; try { requestLogPS = new PrintStream( new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml"))); requestLogPS.println(requestString); } catch (IOException e) { e.printStackTrace(); } finally { if (requestLogPS != null) { requestLogPS.close(); } } } // ================================================================= // // Remove the XML Declaration, if any // if (requestString.startsWith("<?xml")) { // requestString = requestString.substring(requestString.indexOf("?>")+2).trim(); // } // // StringBuffer soapText = new StringBuffer( // "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">"); // // soapText.append("<soap-env:Header>\n"); // // tell server about our superior SOAP Fault capabilities // soapText.append("<"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName); // soapText.append(" xmlns='"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace); // soapText.append("'>"); // soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes); // soapText.append("</"); // soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName); // soapText.append(">\n"); // soapText.append("</soap-env:Header>\n"); // soapText.append("<soap-env:Body>\n"); // soapText.append(requestString); // soapText.append("</soap-env:Body>"); // soapText.append("</soap-env:Envelope>"); MessageFactory messageFactory; SOAPMessage message = null; SOAPPart sp = null; SOAPEnvelope se = null; SOAPBody sb = null; SOAPHeader sh = null; if (log.isTraceEnabled()) { log.trace("requestString=\"" + requestString + "\""); } try { messageFactory = MessageFactory.newInstance(); message = messageFactory.createMessage(); sp = message.getSOAPPart(); se = sp.getEnvelope(); sb = se.getBody(); sh = se.getHeader(); /* * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> * <soap-env:Header> * <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities> * * change with explicit namespace * <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities> */ SOAPHeaderElement capabilityElement = sh .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1", BindingUtility.SOAP_CAPABILITY_HEADER_Namespace)); // capabilityElement.addAttribute( // se.createName("xmlns"), // BindingUtility.SOAP_CAPABILITY_HEADER_Namespace); capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes); /* * body */ // Remove the XML Declaration, if any if (requestString.startsWith("<?xml")) { requestString = requestString.substring(requestString.indexOf("?>") + 2).trim(); } // Generate DOM Document from request xml string DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8")); // Inject request into body sb.addDocument(builderFactory.newDocumentBuilder().parse(stream)); // Is it never the case that there attachments but no credentials if ((attachments != null) && !attachments.isEmpty()) { addAttachments(message, attachments); } if (credentialInfo == null) { throw new JAXRException(resourceBundle.getString("message.credentialInfo")); } WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo); SOAPMessage response = send(message); // Check to see if the session has expired // by checking for an error response code // TODO: what error code to we look for? if (isSessionExpired(response)) { credentialInfo.sessionId = null; // sign the SOAPMessage this time // TODO: session - add method to do the signing // signSOAPMessage(msg); // send signed message // SOAPMessage response = send(msg); } // Process the main SOAPPart of the response //check for soapfault and throw RegistryException SOAPFault fault = response.getSOAPBody().getFault(); if (fault != null) { throw createRegistryException(fault); } Reader reader = processResponseBody(response, "Response"); RegistryResponseType ebResponse = null; try { Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller() .unmarshal(new InputSource(reader)); if (obj instanceof JAXBElement<?>) // if Element: take ComplexType from Element obj = ((JAXBElement<RegistryResponseType>) obj).getValue(); ebResponse = (RegistryResponseType) obj; } catch (Exception x) { log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"), x); throw new JAXRException(resourceBundle.getString("message.invalidServerResponse")); } // Process the attachments of the response if any HashMap<String, Object> responseAttachments = processResponseAttachments(response); return new RegistryResponseHolder(ebResponse, responseAttachments); } catch (SAXException e) { throw new JAXRException(e); } catch (ParserConfigurationException e) { throw new JAXRException(e); } catch (UnsupportedEncodingException x) { throw new JAXRException(x); } catch (MessagingException x) { throw new JAXRException(x); } catch (FileNotFoundException x) { throw new JAXRException(x); } catch (IOException e) { throw new JAXRException(e); } catch (SOAPException x) { x.printStackTrace(); throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x); } catch (TransformerConfigurationException x) { throw new JAXRException(x); } catch (TransformerException x) { throw new JAXRException(x); } }