use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.
the class SAMLSOAPReceiver method FormMessageResponse.
/**
* This message forms the SAML Response and puts it in the
* SOAPMessage's Body.
*/
private SOAPMessage FormMessageResponse(HttpServletResponse servletResp, Response resp) {
SOAPMessage msg = null;
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
StringBuffer envBegin = new StringBuffer(100);
envBegin.append("<").append(sc.SOAP_ENV_PREFIX).append(":Envelope").append(sc.SPACE).append("xmlns:").append(sc.SOAP_ENV_PREFIX).append("=\"").append(sc.SOAP_URI).append("\">").append(sc.NL);
envBegin.append("<").append(sc.SOAP_ENV_PREFIX).append(":Body>").append(sc.NL);
StringBuffer envEnd = new StringBuffer(100);
envEnd.append(sc.START_END_ELEMENT).append(sc.SOAP_ENV_PREFIX).append(":Body>").append(sc.NL);
envEnd.append(sc.START_END_ELEMENT).append(sc.SOAP_ENV_PREFIX).append(":Envelope>").append(sc.NL);
try {
StringBuffer sb = new StringBuffer(300);
sb.append(envBegin).append(resp.toString()).append(envEnd);
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("response created is: " + sb.toString());
}
ByteArrayOutputStream bop = new ByteArrayOutputStream();
bop.write(sb.toString().getBytes(sc.DEFAULT_ENCODING));
msg = msgFactory.createMessage(mimeHeaders, new ByteArrayInputStream(bop.toByteArray()));
} catch (Exception e) {
SAMLUtils.debug.error("could not build response:" + e.getMessage());
servletResp.setStatus(servletResp.SC_INTERNAL_SERVER_ERROR);
return FormSOAPError(servletResp, "Server", "cannotBuildResponse", "cannotVerifyIdentity");
}
return msg;
}
use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.
the class SPSingleLogoutServiceSOAP method doPost.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// handle DOS attack
SAMLUtils.checkHTTPContentLength(req);
// Get SP entity ID
String spMetaAlias = SAML2MetaUtils.getMetaAliasByUri(req.getRequestURI());
if (SPCache.isFedlet) {
if ((spMetaAlias == null) || (spMetaAlias.length() == 0)) {
// pick the first available one
List spMetaAliases = SAML2Utils.getSAML2MetaManager().getAllHostedServiceProviderMetaAliases("/");
if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
// get first one
spMetaAlias = (String) spMetaAliases.get(0);
}
}
}
String spEntityID = SAML2Utils.getSAML2MetaManager().getEntityByMetaAlias(spMetaAlias);
String realm = SAML2MetaUtils.getRealmByMetaAlias(spMetaAlias);
if (!SAML2Utils.isSPProfileBindingSupported(realm, spEntityID, SAML2Constants.SLO_SERVICE, SAML2Constants.SOAP)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSLOSOAP.doPost : uri =" + req.getRequestURI() + ", spMetaAlias=" + spMetaAlias + ", spEntityID=" + spEntityID);
}
SOAPMessage msg = SOAPCommunicator.getInstance().getSOAPMessage(req);
SOAPMessage reply = null;
reply = onMessage(msg, req, resp, realm, spEntityID);
if (reply != null) {
// are generated as part of the save.
if (reply.saveRequired()) {
reply.saveChanges();
}
resp.setStatus(HttpServletResponse.SC_OK);
SAML2Utils.putHeaders(reply.getMimeHeaders(), resp);
// Write out the message on the response stream
OutputStream os = resp.getOutputStream();
reply.writeTo(os);
os.flush();
} else {
// Form SOAP fault
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} catch (SAML2Exception ex) {
SAML2Utils.debug.error("SPSingleLogoutServiceSOAP", ex);
SAMLUtils.sendError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "singleLogoutFailed", ex.getMessage());
return;
} catch (SOAPException soap) {
SAML2Utils.debug.error("SPSingleLogoutServiceSOAP", soap);
SAMLUtils.sendError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "singleLogoutFailed", soap.getMessage());
return;
}
}
use of javax.xml.soap.SOAPMessage in project tdi-studio-se by Talend.
the class MsDynamicsWrapper method retrievePolicy.
/**
* Retrieves the MS CRM 2011 policy
*
* @return the policy string
* @throws JaxenException issue with the response format
* @throws IOException generic IO issue
* @throws SOAPException issue with SOAP invocation
*/
public String retrievePolicy() throws IOException, SOAPException, JaxenException {
String msg = FileUtil.readStringFromClasspath("/org/talend/mscrm/login/passport/RetrievePolicy.xml", MsDynamicsWrapper.class);
SOAPMessage response = soap.execute(HTTPS + host + CRM_DISCOVERY_ENDPOINT, msg);
XPath xp = soap.createXPath("//crm:Policy/text()", response);
xp.addNamespace("crm", CRM_DISCOVERY_XMLNS);
Text result = (Text) xp.selectSingleNode(response.getSOAPBody());
return result.getValue();
}
use of javax.xml.soap.SOAPMessage in project tdi-studio-se by Talend.
the class MsDynamicsWrapper method login.
/**
* Retrieves data from the CRM 2011 Online
*
* @param entity CRM 2011 entity (e.g. account or opportunity)
* @param columns Entity fields (e.g. accountid, name etc.)
* @param csvFile name of the CSV file where the results will be stored
* @return number of rows retrieved
* @throws JaxenException issue with the response format
* @throws IOException generic IO issue
* @throws SOAPException issue with SOAP invocation
*/
// public int retrieveMultiple(String entity, String[] columns, String csvFile) throws IOException, SOAPException,
// JaxenException {
// int cnt = 0;
// CSVWriter cw = FileUtil.createUtf8CsvEscapingWriter(new File(csvFile));
// try {
// int pageNumber = 1;
// String cookie = "";
// boolean hasNext = true;
// while (hasNext) {
// List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
// RetrievePageInfo info = retrievePage(entity, columns, pageNumber++, cookie, ret);
// for (Map<String, String> m : ret) {
// String[] row = new String[columns.length];
// for (int i = 0; i < columns.length; i++) {
// row[i] = m.get(columns[i]);
// }
// cw.writeNext(row);
// }
// cnt += ret.size();
// cw.flush();
// cookie = info.getPageCookie();
// if ("0".equalsIgnoreCase(info.getMoreRecords()))
// hasNext = false;
// }
// } finally {
// cw.close();
// }
// return cnt;
// }
/**
* Paging information holder
*/
// private class RetrievePageInfo {
//
// private String pageCookie;
//
// private String moreRecords;
//
// public RetrievePageInfo(String cookie, String more) {
// setPageCookie(cookie);
// setMoreRecords(more);
// }
//
// public String getPageCookie() {
// return pageCookie;
// }
//
// public void setPageCookie(String pageCookie) {
// this.pageCookie = pageCookie;
// }
//
// public String getMoreRecords() {
// return moreRecords;
// }
//
// public void setMoreRecords(String moreRecords) {
// this.moreRecords = moreRecords;
// }
// }
/**
* Retrieves a single page of RetrieveMultiple result
*
* @param entity CRM 2011 entity (e.g. account or opportunity)
* @param columns Entity fields (e.g. accountid, name etc.)
* @param pageNumber the result page number (1..N)
* @param cookie API paging cookie
* @param ret the List of Maps that will be populated with the data
* @return the RetrievePageInfo structure that describes the status of the retrieval
* @throws JaxenException issue with the response format
* @throws IOException generic IO issue
* @throws SOAPException issue with SOAP invocation
*/
// protected RetrievePageInfo retrievePage(String entity, String[] columns, int pageNumber, String cookie,
// List<Map<String, String>> ret) throws IOException, SOAPException, JaxenException {
// String msg = FileUtil.readStringFromClasspath("/com/gooddata/msdynamics/RetrieveMultiple.xml",
// MsDynamicsWrapper.class);
// msg = msg.replace(CRM_ORGANIZATION_PLACEHOLDER, getOrganization());
// msg = msg.replace(CRM_TICKET_PLACEHOLDER, getCrmTicket());
// msg = msg.replace(CRM_ENTITY_PLACEHOLDER, entity);
// msg = msg.replace(CRM_PAGE_NUMBER_PLACEHOLDER, Integer.toString(pageNumber));
// msg = msg.replace(CRM_PAGE_COUNT_PLACEHOLDER, Integer.toString(PAGE_COUNT));
// if (cookie != null && cookie.length() > 0) {
// msg = msg.replace(CRM_PAGE_COOKIE_PLACEHOLDER, "<ns4:PageCookie><![CDATA[" + cookie + "]]></ns4:PageCookie>");
// } else {
// msg = msg.replace(CRM_PAGE_COOKIE_PLACEHOLDER, "");
// }
// String columnsElement = "";
// for (int i = 0; i < columns.length; i++) {
// columnsElement += "<ns4:Attribute>" + columns[i] + "</ns4:Attribute>";
// }
// msg = msg.replace(CRM_ATTRIBUTES_PLACEHOLDER, columnsElement);
// SOAPMessage response = soap.execute(HTTPS + host + CRM_ENDPOINT, msg);
// XPath xp = soap.createXPath("//crm:RetrieveMultipleResult", response);
// xp.addNamespace("crm", RESULT_XMLNS);
// List result = xp.selectNodes(response.getSOAPBody());
// if (result != null && result.size() == 1) {
// SOAPElement e = (SOAPElement) result.get(0);
// String more = e.getAttribute("MoreRecords");
// String newCookie = e.getAttribute("PagingCookie");
// if (more != null && more.length() > 0 && newCookie != null && newCookie.length() > 0) {
// xp = soap.createXPath("//crm:BusinessEntity", response);
// xp.addNamespace("crm", ENTITY_XMLNS);
// result = xp.selectNodes(response.getSOAPBody());
// for (Object o : result) {
// e = (SOAPElement) o;
// Map<String, String> instance = new HashMap<String, String>();
// Iterator elements = e.getChildElements();
// while (elements.hasNext()) {
// SOAPElement name = (SOAPElement) elements.next();
// String value = name.getFirstChild().getNodeValue();
// instance.put(name.getElementName().getLocalName(), value);
// }
// ret.add(instance);
// }
// return new RetrievePageInfo(newCookie, more);
// } else {
// throw new SOAPException("RetrieveMultiple: Invalid response. The response doesn't contain either "
// + "the MoreRecords or the PagingCookie attributes.");
// }
//
// } else {
// throw new SOAPException("RetrieveMultiple: Invalid response. The response doesn't contain "
// + "the RetrieveMultipleResult element.");
// }
// }
/**
* Logs into the MS CRM 2011 Online
*
* @return the Live ID token
* @throws JaxenException issue with the response format
* @throws IOException generic IO issue
* @throws SOAPException issue with SOAP invocation
*/
public String login() throws IOException, SOAPException, JaxenException {
String msg = FileUtil.readStringFromClasspath("/org/talend/mscrm/login/passport/LiveIdLogin.xml", MsDynamicsWrapper.class);
msg = msg.replaceAll(LIVE_ID_SERVER_PLACEHOLDER, getHost());
msg = msg.replaceAll(LIVE_ID_USERNAME_PLACEHOLDER, getUsername());
msg = msg.replaceAll(LIVE_ID_PASSWORD_PLACEHOLDER, getPassword());
msg = msg.replaceAll(LIVE_ID_POLICY_PLACEHOLDER, getPolicy());
SOAPMessage response = soap.execute(HTTPS + LIVE_ID_HOST + LIVE_ID_ENDPOINT, msg);
XPath xp = soap.createXPath("//wsse:BinarySecurityToken/text()", response);
xp.addNamespace("wsse", WSSE_XMLNS);
Node result = (Node) xp.selectSingleNode(response.getSOAPBody());
return result.getValue();
}
use of javax.xml.soap.SOAPMessage in project nhin-d by DirectProject.
the class DirectSOAPHandler method handleMessage.
/**
* This method handles the incoming and outgoing SOAP-Message. It's an
* excellent point to manipulate the SOAP.
*
* @param SOAPMessageContext
* The SOAPMessageContext object.
* @return true for successful handling, false otherwise.
*/
@Override
public boolean handleMessage(SOAPMessageContext context) {
LOGGER.info("Entering DirectSOAPHandler.handleMessage(SOAPMessageContext)");
// Inquire incoming or outgoing message.
boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
try {
if (outbound) {
LOGGER.info("Handling an outbound message");
boolean isACK = !context.containsKey(ENDPOINT_ADDRESS);
SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
dumpSOAPMessage(msg);
SOAPPart sp = msg.getSOAPPart();
// edit Envelope
SOAPEnvelope env = sp.getEnvelope();
SOAPHeader sh = env.addHeader();
@SuppressWarnings("unused") SOAPBody sb = env.getBody();
try {
if (threadData.getAction() != null) {
QName qname = new QName("http://www.w3.org/2005/08/addressing", "Action");
SOAPHeaderElement saction = sh.addHeaderElement(qname);
boolean must = true;
saction.setMustUnderstand(must);
saction.setValue(threadData.getAction());
}
if (threadData.getRelatesTo() != null) {
QName qname = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo");
SOAPHeaderElement relates = sh.addHeaderElement(qname);
relates.setValue(threadData.getRelatesTo());
}
if (threadData.getFrom() != null) {
QName qname = new QName("http://www.w3.org/2005/08/addressing", "From");
QName child = new QName("http://www.w3.org/2005/08/addressing", "Address");
SOAPHeaderElement efrom = sh.addHeaderElement(qname);
SOAPElement address = efrom.addChildElement(child);
address.setValue(threadData.getFrom());
}
if (threadData.getMessageId() != null) {
QName qname = new QName("http://www.w3.org/2005/08/addressing", "MessageID");
SOAPHeaderElement message = sh.addHeaderElement(qname);
message.setValue(threadData.getMessageId());
}
if (threadData.getTo() != null) {
QName qname = new QName("http://www.w3.org/2005/08/addressing", "To");
SOAPHeaderElement sto = sh.addHeaderElement(qname);
sto.setValue(threadData.getTo());
}
SOAPHeaderElement directHeader = sh.addHeaderElement(new QName("urn:direct:addressing", "addressBlock"));
directHeader.setPrefix("direct");
directHeader.setRole("urn:direct:addressing:destination");
directHeader.setRelay(true);
if (StringUtils.isNotBlank(threadData.getDirectFrom())) {
SOAPElement directFromElement = directHeader.addChildElement(new QName("from"));
directFromElement.setPrefix("direct");
URI uri = new URI(threadData.getDirectFrom());
directFromElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
}
if (StringUtils.isNotBlank(threadData.getDirectTo())) {
/**
* consider multiple recipients
*/
String[] directTos = threadData.getDirectTo().split(";");
for (String directToAddr : directTos) {
SOAPElement directToElement = directHeader.addChildElement(new QName("to"));
directToElement.setPrefix("direct");
URI uri = new URI(directToAddr);
directToElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
}
}
SOAPElement directMetadataLevelElement = directHeader.addChildElement(new QName("metadata-level"));
directMetadataLevelElement.setPrefix("direct");
directMetadataLevelElement.setValue(MetadataLevelEnum.MINIMAL.getLevel());
} catch (Throwable tb) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Failed to write SOAP Header", tb);
} else {
LOGGER.error("Failed to write SOAP Header: " + tb.getMessage());
}
}
if (isACK) {
SafeThreadData.clean(Thread.currentThread().getId());
}
} else {
LOGGER.info("Handling an inbound message");
SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
boolean isResponse = isResponse(msg);
if (!isResponse) {
// Issue 249 - before handling the inbound case, we should clear
// out the old thread data if we don't this the To: (SMTP recipients) will
// append from the previous thread data
SafeThreadData.clean(Thread.currentThread().getId());
}
SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
ServletRequest sr = (ServletRequest) context.get(MessageContext.SERVLET_REQUEST);
if (sr != null) {
threadData.setRemoteHost(sr.getRemoteHost());
threadData.setThisHost(sr.getServerName());
threadData.setPid(getPID());
}
SOAPPart sp = msg.getSOAPPart();
// edit Envelope
SOAPEnvelope env = sp.getEnvelope();
SOAPHeader sh = env.getHeader();
@SuppressWarnings("unchecked") Iterator<Node> it = sh.extractAllHeaderElements();
while (it.hasNext()) {
try {
Node header = it.next();
if (StringUtils.contains(header.toString(), "MessageID")) {
threadData.setMessageId(header.getTextContent());
} else if (StringUtils.contains(header.toString(), "Action")) {
threadData.setAction(header.getTextContent());
} else if (StringUtils.contains(header.toString(), "RelatesTo")) {
threadData.setRelatesTo(header.getTextContent());
} else if (StringUtils.contains(header.toString(), "ReplyTo")) {
NodeList reps = header.getChildNodes();
for (int i = 0; i < reps.getLength(); i++) {
Node address = reps.item(i);
if (StringUtils.contains(address.getNodeName(), "Address")) {
threadData.setEndpoint(address.getTextContent());
}
}
} else if (StringUtils.contains(header.toString(), "From")) {
NodeList reps = header.getChildNodes();
for (int i = 0; i < reps.getLength(); i++) {
Node address = reps.item(i);
if (StringUtils.contains(address.getNodeName(), "Address")) {
threadData.setFrom(address.getTextContent());
}
}
} else if (// must be after ReplyTo
StringUtils.contains(header.toString(), "To")) {
threadData.setTo(header.getTextContent());
} else if (StringUtils.contains(header.toString(), "addressBlock")) {
NodeList childNodes = header.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (StringUtils.contains(node.getNodeName(), "from")) {
threadData.setDirectFrom(node.getTextContent());
} else if (StringUtils.contains(node.getNodeName(), "to")) {
// XDR-MULTIPLE-RECIPIENT-ISSUE - this is the part where old thread data
// gets into the To: and will cause unwanted recipients
// (see above for the clear)
String recipient = node.getTextContent();
if (threadData.getDirectTo() == null) {
threadData.setDirectTo(recipient);
} else {
/**
* if multiple recipients, save addresses in one parameters separate by (;)
*/
threadData.setDirectTo(threadData.getDirectTo() + ";" + recipient);
}
} else if (StringUtils.contains(node.getNodeName(), "metadata-level")) {
threadData.setDirectMetadataLevel(node.getTextContent());
}
}
}
} catch (Throwable tb) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Failed to read input parameter.", tb);
} else {
LOGGER.error("Failed to read input parameter.");
}
}
}
threadData.save();
}
} catch (Exception e) {
LOGGER.warn("Error handling SOAP message.", e);
return false;
}
return true;
}
Aggregations