private void doTestSoapConnection(boolean disableChunking) throws Exception { SOAPFactory soapFac = SOAPFactory.newInstance(); MessageFactory msgFac = MessageFactory.newInstance(); SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance(); SOAPMessage msg = msgFac.createMessage(); if (disableChunking) { // this is the custom header checked by ServiceImpl msg.getMimeHeaders().addHeader("Transfer-Encoding-Disabled", "true"); // this is a hint to SOAPConnection that the chunked encoding is not needed msg.getMimeHeaders().addHeader("Transfer-Encoding", "disabled"); } QName sayHi = new QName("http://www.jboss.org/jbossws/saaj", "sayHello"); msg.getSOAPBody().addChildElement(soapFac.createElement(sayHi)); AttachmentPart ap1 = msg.createAttachmentPart(); char[] content = new char[16 * 1024]; Arrays.fill(content, 'A'); ap1.setContent(new String(content), "text/plain"); msg.addAttachmentPart(ap1); AttachmentPart ap2 = msg.createAttachmentPart(); ap2.setContent("Attachment content - Part 2", "text/plain"); msg.addAttachmentPart(ap2); msg.saveChanges(); SOAPConnection con = conFac.createConnection(); final String serviceURL = baseURL.toString(); URL endpoint = new URL(serviceURL); SOAPMessage response = con.call(msg, endpoint); QName sayHiResp = new QName("http://www.jboss.org/jbossws/saaj", "sayHelloResponse"); Iterator<?> sayHiRespIterator = response.getSOAPBody().getChildElements(sayHiResp); SOAPElement soapElement = (SOAPElement) sayHiRespIterator.next(); assertNotNull(soapElement); assertEquals(2, response.countAttachments()); String[] values = response.getMimeHeaders().getHeader("Transfer-Encoding-Disabled"); if (disableChunking) { // this means that the ServiceImpl executed the code branch verifying // that chunking was disabled assertNotNull(values); assertTrue(values.length == 1); } else { assertNull(values); } }
/** * processRequest processes PhaseIV Web Service calls. It creates a soap message from input string * xmlRequest and invokes Phase IV Web Service processRequest method. * * @param PhaseIV xmlRequest * @return PhaseIV xmlResponse * @throws Exception */ public String processRequest(String xmlRequest, String clientURL) throws Exception { try { if (Utils.getInstance().isNullString(xmlRequest) || Utils.getInstance().isNullString(clientURL)) { logger.debug("Recieved xmlRequest or clientURL as null"); return null; } logger.debug("processRequest--> xmlRequest :" + xmlRequest); ByteArrayInputStream inStream = new ByteArrayInputStream(xmlRequest.getBytes()); StreamSource source = new StreamSource(inStream); MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage sMsg = msgFactory.createMessage(); SOAPPart sPart = sMsg.getSOAPPart(); sPart.setContent(source); MimeHeaders mimeHeader = sMsg.getMimeHeaders(); mimeHeader.setHeader("SOAPAction", "http://ejbs.phaseiv.bsg.adp.com"); logger.debug("processRequest-->in PhaseIVClient before call"); SOAPMessage respMsg = executeCall(sMsg, clientURL); logger.debug("processRequest-->in PhaseIVClient after call"); // SOAPFault faultCode = // respMsg.getSOAPPart().getEnvelope().getBody().getFault(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); respMsg.writeTo(outStream); logger.debug("processRequest xmlResponse:" + outStream.toString()); return outStream.toString(); } catch (Exception exp) { logger.error("processRequest --> Error while processing request : " + exp.getMessage()); logger.error("processRequest --> error xmlRequest:" + xmlRequest); exp.printStackTrace(); throw exp; } }
private void transportHeaders(Packet packet, boolean inbound, SOAPMessage msg) throws SOAPException { Map<String, List<String>> headers = getTransportHeaders(packet, inbound); if (headers != null) { addSOAPMimeHeaders(msg.getMimeHeaders(), headers); } if (msg.saveRequired()) msg.saveChanges(); }
public Document invokeMethod(DynamicBinder dBinder, Document inputDoc) throws ComponentException { try { logger.info( "URI : " + dBinder.wsdlURI + "\n porttype: " + dBinder.portType + " \n operation: " + dBinder.operation + "\n endpoint: " + dBinder.endPoint); QName serviceName = new QName(dBinder.targetNS, dBinder.serviceName); Service serv = Service.create(serviceName); QName portQName = new QName(dBinder.targetNS, dBinder.portType); serv.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, dBinder.endPoint); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); // TODO: add namespaces declared on the SOAPBody level to the envelope message.getSOAPPart().getEnvelope().addNamespaceDeclaration("tns1", dBinder.targetNS); message.getSOAPBody().addDocument(inputDoc); message.getMimeHeaders().addHeader("SOAPAction", dBinder.operation); message.saveChanges(); Dispatch<SOAPMessage> smDispatch = serv.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE); List<Handler> handlers = smDispatch.getBinding().getHandlerChain(); handlers.add(new SOAPLoggingHandler()); smDispatch.getBinding().setHandlerChain(handlers); SOAPMessage soapResponse = null; try { soapResponse = smDispatch.invoke(message); } catch (Exception e) { logger.error("Fault has been returned in SOAP message!!!"); return null; } return toDocument(soapResponse); } catch (Exception e) { logger.error(e.getMessage()); throw new ComponentException(e.getMessage()); } }
public SOAPClient(String url, String soapAction) throws UnsupportedOperationException, SOAPException { // Create the connection SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance(); conn = scf.createConnection(); // Create message MessageFactory mf = MessageFactory.newInstance(); soapRequest = mf.createMessage(); wsdlURL = url; // add SOAP Action if (soapAction != null) { MimeHeaders hd = soapRequest.getMimeHeaders(); hd.addHeader("SOAPAction", soapAction); } }
private static SOAPMessage createSOAPRequest() throws Exception { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); String serverURI = "http://ws.cdyne.com/"; // SOAP Envelope SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration("example", serverURI); /* Constructed SOAP Request Message: <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>[email protected]</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("VerifyEmail", "example"); SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example"); soapBodyElem1.addTextNode("*****@*****.**"); SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example"); soapBodyElem2.addTextNode("123"); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", serverURI + "VerifyEmail"); soapMessage.saveChanges(); /* Print the request message */ System.out.print("Request SOAP Message:"); soapMessage.writeTo(System.out); System.out.println(); return soapMessage; }
@Override public void mapTo(Context context, SOAPBindingData target) throws Exception { SOAPMessage soapMessage = target.getSOAPMessage(); MimeHeaders mimeHeaders = soapMessage.getMimeHeaders(); SOAPHeader soapHeader = soapMessage.getSOAPHeader(); for (Property property : context.getProperties(Scope.IN)) { Object value = property.getValue(); if (value != null) { String name = property.getName(); QName qname = XMLHelper.createQName(name); boolean qualifiedForSoapHeader = Strings.trimToNull(qname.getNamespaceURI()) != null; if (qualifiedForSoapHeader && matches(qname)) { if (value instanceof Node) { Node domNode = soapHeader.getOwnerDocument().importNode((Node) value, true); soapHeader.appendChild(domNode); } else if (value instanceof Configuration) { Element configElement = new ElementPuller().pull(new StringReader(value.toString())); Node configNode = soapHeader.getOwnerDocument().importNode(configElement, true); soapHeader.appendChild(configNode); } else { String v = value.toString(); if (SOAPHeadersType.XML.equals(getSOAPHeadersType())) { try { Element xmlElement = new ElementPuller().pull(new StringReader(v)); Node xmlNode = soapHeader.getOwnerDocument().importNode(xmlElement, true); soapHeader.appendChild(xmlNode); } catch (Throwable t) { soapHeader.addChildElement(qname).setValue(v); } } else { soapHeader.addChildElement(qname).setValue(v); } } } else { if (matches(name)) { mimeHeaders.addHeader(name, String.valueOf(value)); } } } } }
private SOAPMessage actionToSoap(RpcInvokeAction action) throws Exception { useFirstElementPrefix = true; SOAPMessage message = messageFactory.createMessage(); actionData = WsRpcActionUtil.getWsRpcActionData(((SimpleRpcInvokeAction) action).getProperties()); SOAPEnvelope env = message.getSOAPPart().getEnvelope(); env.addNamespaceDeclaration(ACTION_PREFIX, actionData.getMethodInputNameSpace()); setFields(action.getFields(), env.getBody()); if (actionData.getSoapAction().length() > 0) { message.getMimeHeaders().addHeader("SOAPAction", actionData.getSoapAction()); } // Base auth headers from http://www.whitemesa.com/soapauth.html#S322 /* * all auth standarts: http://www.soapui.org/testing-dojo/best-practices/authentication.html */ if (props.getPassword() != null && props.getUserName() != null && !props.getUserName().trim().equals("")) { SOAPHeaderElement auth = message .getSOAPHeader() .addHeaderElement( new QName("http://soap-authentication.org/basic/2001/10/", "BasicAuth", "h")); auth.setMustUnderstand(true); auth.addChildElement("Name").setValue(props.getUserName()); auth.addChildElement("Password").setValue(props.getPassword()); } logMessage("Request message:", message); return message; }
/* * ??? * * @param response * @param responseBean * @throws DOMException * @throws SOAPException */ private void extractHeaderDataSOAP(SOAPMessage response, HttpResponseBean responseBean) throws SOAPException { // extract MimeHeaders MimeHeaders mime = response.getMimeHeaders(); Iterator<MimeHeader> iter = mime.getAllHeaders(); while (iter.hasNext()) { MimeHeader mimeH = iter.next(); responseBean.addEntryToResponseHeaders(mimeH.getName(), mimeH.getValue()); } // extract SOAPHeaders from the envelope and a them to the mimeHeaders if (response.getSOAPHeader() != null) { javax.xml.soap.SOAPHeader header = response.getSOAPHeader(); NodeList nodes = header.getChildNodes(); for (int x = 0; x < nodes.getLength(); x++) { // if the header entry contains child nodes - write them with the node names if (nodes.item(x).hasChildNodes()) { NodeList childnodes = nodes.item(x).getChildNodes(); StringBuilder buff = new StringBuilder(); for (int y = 0; y < childnodes.getLength(); y++) { if (!"".equals(buff.toString())) { buff.append(" "); } buff.append(childnodes.item(y).getLocalName()).append(":"); buff.append(childnodes.item(y).getTextContent()); } responseBean.addEntryToResponseHeaders(nodes.item(x).getLocalName(), buff.toString()); } else { responseBean.addEntryToResponseHeaders( nodes.item(x).getLocalName(), nodes.item(x).getTextContent()); } } } }
protected SOAPMessage createQueryMessage() { String queryStr = getQueryString(); if (log.isDebugEnabled()) { log.debug("MDX query: " + queryStr); } try { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage message = mf.createMessage(); MimeHeaders mh = message.getMimeHeaders(); mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\""); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); Name nEx = envelope.createName("Execute", "", XMLA_URI); SOAPElement eEx = body.addChildElement(nEx); // add the parameters // COMMAND parameter // <Command> // <Statement>queryStr</Statement> // </Command> Name nCom = envelope.createName("Command", "", XMLA_URI); SOAPElement eCommand = eEx.addChildElement(nCom); Name nSta = envelope.createName("Statement", "", XMLA_URI); SOAPElement eStatement = eCommand.addChildElement(nSta); eStatement.addTextNode(queryStr); // <Properties> // <PropertyList> // <DataSourceInfo>dataSource</DataSourceInfo> // <Catalog>catalog</Catalog> // <Format>Multidimensional</Format> // <AxisFormat>TupleFormat</AxisFormat> // </PropertyList> // </Properties> Map paraList = new HashMap(); String datasource = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE); paraList.put("DataSourceInfo", datasource); String catalog = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG); paraList.put("Catalog", catalog); paraList.put("Format", "Multidimensional"); paraList.put("AxisFormat", "TupleFormat"); addParameterList(envelope, eEx, "Properties", "PropertyList", paraList); message.saveChanges(); if (log.isDebugEnabled()) { log.debug("XML/A query message: " + message.toString()); } return message; } catch (SOAPException e) { throw new JRRuntimeException(e); } }
@Override public final SOAPMessage call(final SOAPMessage request, final Object endpoint) throws SOAPException { SOAPMessage message = null; final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final MimeHeaders headers = request.getMimeHeaders(); final String[] contentType = headers.getHeader("Content-Type"); final String[] soapAction = headers.getHeader("SOAPAction"); // build the Content-Type HTTP header parameter if not defined if (null == contentType) { final StringBuilder header = new StringBuilder(); if (null == soapAction) { header.append("application/soap+xml; charset=UTF-8;"); } else { header.append("text/xml; charset=UTF-8;"); } // not defined as a MIME header but we need it as an HTTP header parameter this.conn.addRequestProperty("Content-Type", header.toString()); } else { if (contentType.length > 1) { throw new IllegalArgumentException("Content-Type defined more than once."); } // user specified as a MIME header so add it as an HTTP header parameter this.conn.addRequestProperty("Content-Type", contentType[0]); } // specify SOAPAction as an HTTP header parameter if (null != soapAction) { if (soapAction.length > 1) { throw new IllegalArgumentException("SOAPAction defined more than once."); } this.conn.addRequestProperty("SOAPAction", soapAction[0]); } request.writeTo(bos); this.conn.connect(new URL(endpoint.toString()), bos); final MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); try { message = factory.createMessage(null, this.conn.getInputStream()); } catch (IOException e) { message = factory.createMessage(null, this.conn.getErrorStream()); } } catch (MalformedURLException e) { throw new SOAPException(e); } catch (IOException e) { throw new SOAPException(e); } catch (GSSException e) { throw new SOAPException(e); } catch (PrivilegedActionException e) { throw new SOAPException(e); } finally { try { bos.close(); } catch (IOException ioe) { assert true; } this.close(); } return message; }
SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException { boolean isFailure = false; URL url = null; HttpURLConnection httpConnection = null; int responseCode = 0; try { if (endPoint.getProtocol().equals("https")) // if(!setHttps) initHttps(); // Process the URL JaxmURI uri = new JaxmURI(endPoint.toString()); String userInfo = uri.getUserinfo(); url = endPoint; if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri); // TBD // Will deal with https later. if (!url.getProtocol().equalsIgnoreCase("http") && !url.getProtocol().equalsIgnoreCase("https")) { log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https"); throw new IllegalArgumentException( "Protocol " + url.getProtocol() + " not supported in URL " + url); } httpConnection = (HttpURLConnection) createConnection(url); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setUseCaches(false); httpConnection.setInstanceFollowRedirects(true); if (message.saveRequired()) message.saveChanges(); MimeHeaders headers = message.getMimeHeaders(); Iterator it = headers.getAllHeaders(); boolean hasAuth = false; // true if we find explicit Auth header while (it.hasNext()) { MimeHeader header = (MimeHeader) it.next(); String[] values = headers.getHeader(header.getName()); if (values.length == 1) httpConnection.setRequestProperty(header.getName(), header.getValue()); else { StringBuffer concat = new StringBuffer(); int i = 0; while (i < values.length) { if (i != 0) concat.append(','); concat.append(values[i]); i++; } httpConnection.setRequestProperty(header.getName(), concat.toString()); } if ("Authorization".equals(header.getName())) { hasAuth = true; log.fine("SAAJ0091.p2p.https.auth.in.POST.true"); } } if (!hasAuth && userInfo != null) { initAuthUserInfo(httpConnection, userInfo); } OutputStream out = httpConnection.getOutputStream(); message.writeTo(out); out.flush(); out.close(); httpConnection.connect(); try { responseCode = httpConnection.getResponseCode(); // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } // else if (responseCode != HttpURLConnection.HTTP_OK) // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207)) else if ((responseCode / 100) != 2) { log.log( Level.SEVERE, "SAAJ0008.p2p.bad.response", new String[] {httpConnection.getResponseMessage()}); throw new SOAPExceptionImpl( "Bad response: (" + responseCode + httpConnection.getResponseMessage()); } } catch (IOException e) { // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds! responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } else { throw e; } } } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.severe("SAAJ0009.p2p.msg.send.failed"); throw new SOAPExceptionImpl("Message send failed", ex); } SOAPMessage response = null; if (responseCode == HttpURLConnection.HTTP_OK || isFailure) { try { MimeHeaders headers = new MimeHeaders(); String key, value; // Header field 0 is the status line so we skip it. int i = 1; while (true) { key = httpConnection.getHeaderFieldKey(i); value = httpConnection.getHeaderField(i); if (key == null && value == null) break; if (key != null) { StringTokenizer values = new StringTokenizer(value, ","); while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim()); } i++; } InputStream httpIn = (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream()); byte[] bytes = readFully(httpIn); int length = httpConnection.getContentLength() == -1 ? bytes.length : httpConnection.getContentLength(); // If no reply message is returned, // content-Length header field value is expected to be zero. if (length == 0) { response = null; log.warning("SAAJ0014.p2p.content.zero"); } else { ByteInputStream in = new ByteInputStream(bytes, length); response = messageFactory.createMessage(headers, in); } httpIn.close(); httpConnection.disconnect(); } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex); throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage()); } } return response; }