List of usage examples for javax.xml.soap SOAPMessage getSOAPBody
public SOAPBody getSOAPBody() throws SOAPException
From source file:com.streamreduce.util.JiraClient.java
public List<Element> getIssueStatuses() throws SOAPException { debugLog(LOGGER, "Getting issue statuses"); StringBuilder sb = new StringBuilder() .append(" <soap:getStatuses soapenv:encodingStyle=\"" + encodingStyle + "\">\n") .append(" <in0 xsi:type=\"xsd:string\">" + jiraToken + "</in0>\n") .append(" </soap:getStatuses>\n"); SOAPMessage issueStatusesResponse = invokeSoap(JiraStudioApp.JIRA, sb.toString()); NodeList issueStatuses = issueStatusesResponse.getSOAPBody().getElementsByTagName("multiRef"); return asList(issueStatuses); }
From source file:com.streamreduce.util.JiraClient.java
public List<Element> getIssuePriorities() throws SOAPException { debugLog(LOGGER, "Getting issue priorities"); StringBuilder sb = new StringBuilder() .append(" <soap:getPriorities soapenv:encodingStyle=\"" + encodingStyle + "\">\n") .append(" <in0 xsi:type=\"xsd:string\">" + jiraToken + "</in0>\n") .append(" </soap:getPriorities>\n"); SOAPMessage issuePrioritiesResponse = invokeSoap(JiraStudioApp.JIRA, sb.toString()); NodeList issuePriorities = issuePrioritiesResponse.getSOAPBody().getElementsByTagName("multiRef"); return asList(issuePriorities); }
From source file:com.streamreduce.util.JiraClient.java
public List<org.w3c.dom.Element> getSubTaskIssueTypes() throws SOAPException { debugLog(LOGGER, "Getting sub-task issue types"); StringBuilder sb = new StringBuilder() .append(" <soap:getSubTaskIssueTypes soapenv:encodingStyle=\"" + encodingStyle + "\">\n") .append(" <in0 xsi:type=\"xsd:string\">" + jiraToken + "</in0>\n") .append(" </soap:getSubTaskIssueTypes>\n"); SOAPMessage subTaskIssueTypesResponse = invokeSoap(JiraStudioApp.JIRA, sb.toString()); NodeList subTaskIssueTypes = subTaskIssueTypesResponse.getSOAPBody().getElementsByTagName("multiRef"); return asList(subTaskIssueTypes); }
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 ww.ja v a 2 s.c o m * @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:com.streamreduce.util.JiraClient.java
public SOAPMessage invokeSoap(JiraStudioApp app, String soapBody) throws SOAPException { String cacheKey = (app + "-SOAP-" + soapBody.hashCode()); Object objectFromCache = requestCache.getIfPresent(cacheKey); if (objectFromCache != null) { debugLog(LOGGER, " (From cache)"); return (SOAPMessage) objectFromCache; }//from w ww. j av a 2s. c om // Wrap the SOAP body content in an envelope/body container StringBuilder sb = new StringBuilder(); String soapBaseURL = getBaseUrl(); String soapNamespaceURL; sb.append("<soapenv:Envelope ").append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ") .append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ") .append("xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "); switch (app) { case CONFLUENCE: soapNamespaceURL = "http://soap.rpc.confluence.atlassian.com"; soapBaseURL += "/wiki/rpc/soap-axis/confluenceservice-v1"; break; case JIRA: soapNamespaceURL = "http://soap.rpc.jira.atlassian.com"; soapBaseURL += "/rpc/soap/jirasoapservice-v2"; break; default: throw new SOAPException("Unknown Jira Studio application: " + app); } sb.append("xmlns:soap=\"" + soapNamespaceURL + "\">\n"); sb.append("<soapenv:Body>\n"); sb.append(soapBody); sb.append("</soapenv:Body></soapenv:Envelope>"); String rawResponse; List<Header> requestHeaders = new ArrayList<>(); requestHeaders.add(new BasicHeader("SOAPAction", "")); try { rawResponse = HTTPUtils.openUrl(soapBaseURL, "POST", sb.toString(), MediaType.TEXT_XML, null, null, requestHeaders, null); } catch (Exception e) { LOGGER.error(String.format("Unable to make SOAP call to %s: %s", soapBaseURL, e.getMessage()), e); throw new SOAPException(e); } Source response = new StreamSource(new StringReader(rawResponse)); MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage message = msgFactory.createMessage(); SOAPPart env = message.getSOAPPart(); env.setContent(response); if (message.getSOAPBody().hasFault()) { SOAPFault fault = message.getSOAPBody().getFault(); LOGGER.error("soap fault in jira soap response: " + fault.getFaultString()); } requestCache.put(cacheKey, message); return message; }
From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java
public Node extractResponseNode(SOAPMessage response) throws SOAPException { Node responseNode;//from www . j a va 2 s.c o m ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { response.writeTo(outStream); } catch (IOException e) { throw new RuntimeException(e); } // logger.LogBetfairDebugEntry("SOAP Response: " + outStream.toString()); if (response.getSOAPBody().hasFault()) { responseNode = response.getSOAPBody().getFault(); } else if (response.getSOAPBody().getFirstChild() == null) { // Response type is void responseNode = response.getSOAPBody(); } else { // extract the body SOAPBody respBody = response.getSOAPBody(); // First child should be the service name object Node serviceResponseNode = respBody.getFirstChild(); // second child responseNode = serviceResponseNode.getFirstChild(); } return responseNode; }
From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java
private void attachPayload(PartInfo partInfo, SOAPMessage message) throws ParserConfigurationException, SOAPException, IOException, SAXException { String mimeType = null;/*w ww .j a v a2 s . co m*/ boolean compressed = false; for (Property prop : partInfo.getPartProperties().getProperties()) { if (Property.MIME_TYPE.equals(prop.getName())) { mimeType = prop.getValue(); } if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName()) && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) { compressed = true; } } byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId()); DataSource dataSource = new ByteArrayDataSource(binaryData, compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType); DataHandler dataHandler = new DataHandler(dataSource); if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config this.documentBuilderFactory.setNamespaceAware(true); DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder(); message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream())); partInfo.setHref(null); return; } AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler); attachmentPart.setContentId(partInfo.getHref()); message.addAttachmentPart(attachmentPart); }
From source file:eu.domibus.ebms3.receiver.MSHWebservice.java
/** * This method persists incoming messages into the database (and handles decompression before) * * @param request the message to persist * @param legConfiguration processing information for the message * @throws SOAPException//from w w w . j ava2 s. c om * @throws JAXBException * @throws TransformerException * @throws IOException * @throws EbMS3Exception */ //TODO: improve error handling private String persistReceivedMessage(SOAPMessage request, LegConfiguration legConfiguration, String pmodeKey, Messaging messaging) throws SOAPException, JAXBException, TransformerException, EbMS3Exception { boolean bodyloadFound = false; for (PartInfo partInfo : messaging.getUserMessage().getPayloadInfo().getPartInfo()) { String cid = partInfo.getHref(); MSHWebservice.LOG.debug("looking for attachment with cid: " + cid); boolean payloadFound = false; if (cid == null || cid.isEmpty()) { if (bodyloadFound) { throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0003, "More than one Partinfo without CID found", messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING); } bodyloadFound = true; payloadFound = true; partInfo.setInBody(true); Node bodyContent = (((Node) request.getSOAPBody().getChildElements().next())); Source source = new DOMSource(bodyContent); ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); Transformer transformer = this.transformerFactory.newTransformer(); transformer.transform(source, result); partInfo.setBinaryData(out.toByteArray()); } @SuppressWarnings("unchecked") Iterator<AttachmentPart> attachmentIterator = request.getAttachments(); AttachmentPart attachmentPart; while (attachmentIterator.hasNext() && !payloadFound) { attachmentPart = attachmentIterator.next(); //remove square brackets from cid for further processing attachmentPart.setContentId(AttachmentUtil.cleanContentId(attachmentPart.getContentId())); MSHWebservice.LOG.debug("comparing with: " + attachmentPart.getContentId()); if (attachmentPart.getContentId().equals(AttachmentUtil.cleanContentId(cid))) { partInfo.setBinaryData(attachmentPart.getRawContentBytes()); partInfo.setInBody(false); payloadFound = true; } } if (!payloadFound) { throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0011, "No Attachment found for cid: " + cid + " of message: " + messaging.getUserMessage().getMessageInfo().getMessageId(), messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING); } } boolean compressed = this.compressionService.handleDecompression(messaging.getUserMessage(), legConfiguration); this.payloadProfileValidator.validate(messaging, pmodeKey); this.propertyProfileValidator.validate(messaging, pmodeKey); MSHWebservice.LOG.debug("Compression for message with id: " + messaging.getUserMessage().getMessageInfo().getMessageId() + " applied: " + compressed); MessageLogEntry messageLogEntry = new MessageLogEntry(); messageLogEntry.setMessageId(messaging.getUserMessage().getMessageInfo().getMessageId()); messageLogEntry.setMessageType(MessageType.USER_MESSAGE); messageLogEntry.setMshRole(MSHRole.RECEIVING); messageLogEntry.setReceived(new Date()); String mpc = messaging.getUserMessage().getMpc(); messageLogEntry.setMpc((mpc == null || mpc.isEmpty()) ? Mpc.DEFAULT_MPC : mpc); messageLogEntry.setMessageStatus(MessageStatus.RECEIVED); this.messageLogDao.create(messageLogEntry); this.messagingDao.create(messaging); return messageLogEntry.getMessageId(); }
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 a v a 2 s . c om*/ * 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); } }
From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
private void reportSOAPFault(SOAPMessage reply) throws SOAPException { String error = reply.getSOAPBody().getFirstChild().getFirstChild().getNodeValue(); throw new RuntimeException("There was a SOAP Fault from Mulgara: " + error); }