List of usage examples for javax.xml.soap SOAPEnvelope getHeader
public SOAPHeader getHeader() throws SOAPException;
From source file:com.profesorfalken.payzen.webservices.sdk.handler.soap.HeaderHandler.java
/** * Takes the outgoing SOAP message and modifies it adding the header * information/* w w w. j av a 2 s . c o m*/ * * @param smc SOAP message context * @return */ @Override public boolean handleMessage(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (Boolean.TRUE.equals(outboundProperty)) { SOAPMessage message = smc.getMessage(); try { SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); //Creates header into SOAP envelope SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } // Add shopId addHeaderField(header, "shopId", this.shopId); // Timestamp TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(tz); String nowAsISO = df.format(new Date()); addHeaderField(header, "timestamp", nowAsISO); // Mode addHeaderField(header, "mode", this.mode); // Add requestId String requestId = UUID.randomUUID().toString(); addHeaderField(header, "requestId", requestId); // Authentication token String tokenString = requestId + nowAsISO; addHeaderField(header, "authToken", sign(tokenString, shopKey)); } catch (SOAPException e) { logger.error("Error sending header", e); } } return outboundProperty; }
From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.BennuWebServiceHandler.java
@Override public boolean handleMessage(SOAPMessageContext context) { Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); //for response message only, true for outbound messages, false for inbound if (!isRequest) { try {/* w w w .j a v a 2 s.co m*/ WebServiceServerConfiguration configuration = getWebServiceServerConfiguration( ((com.sun.xml.ws.api.server.WSEndpoint) context.get("com.sun.xml.ws.api.server.WSEndpoint")) .getImplementationClass().getName()); SOAPMessage soapMsg = context.getMessage(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPHeader soapHeader = soapEnv.getHeader(); if (!configuration.isActive()) { generateSOAPErrorMessage(soapMsg, "Sorry webservice is disabled at application level!"); } if (configuration.isAuthenticatioNeeded()) { if (configuration.isUsingWSSecurity()) { if (soapHeader == null) { generateSOAPErrorMessage(soapMsg, "No header in message, unabled to validate security credentials"); } String username = null; String password = null; String nonce = null; String created = null; Iterator<SOAPElement> childElements = soapHeader.getChildElements(QNAME_WSSE_SECURITY); if (childElements.hasNext()) { SOAPElement securityElement = childElements.next(); Iterator<SOAPElement> usernameTokens = securityElement .getChildElements(QNAME_WSSE_USERNAME_TOKEN); if (usernameTokens.hasNext()) { SOAPElement usernameToken = usernameTokens.next(); username = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_USERNAME) .next()).getValue(); password = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_PASSWORD) .next()).getValue(); nonce = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_NONCE).next()) .getValue(); created = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_CREATED).next()) .getValue(); } } if (username == null || password == null || nonce == null || created == null) { generateSOAPErrorMessage(soapMsg, "Missing information, unabled to validate security credentials"); } SecurityHeader securityHeader = new SecurityHeader(configuration, username, password, nonce, created); if (!securityHeader.isValid()) { generateSOAPErrorMessage(soapMsg, "Invalid credentials"); } else { context.put(BennuWebService.SECURITY_HEADER, securityHeader); context.setScope(BennuWebService.SECURITY_HEADER, Scope.APPLICATION); } } else { com.sun.xml.ws.transport.Headers httpHeader = (Headers) context .get(MessageContext.HTTP_REQUEST_HEADERS); String username = null; String password = null; List<String> list = httpHeader.get("authorization"); if (list != null) { for (String value : list) { if (value.startsWith("Basic")) { String[] split = value.split(" "); try { String decoded = new String(Base64.decodeBase64(split[1]), "UTF-8"); String[] split2 = decoded.split(":"); if (split2.length == 2) { username = split2[0]; password = split2[1]; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } if (username == null || password == null) { generateSOAPErrorMessage(soapMsg, "Missing information, unabled to validate security credentials"); } if (!configuration.validate(username, password)) { generateSOAPErrorMessage(soapMsg, "Invalid credentials"); } } } } catch (SOAPException e) { System.err.println(e); } } //continue other handler chain return true; }
From source file:be.agiv.security.handler.WSAddressingHandler.java
private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException { LOG.debug("adding WS-Addressing headers"); SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope(); SOAPHeader header = envelope.getHeader(); if (null == header) { header = envelope.addHeader();//from w w w . j a va2 s . c om } String wsuPrefix = null; String wsAddrPrefix = null; Iterator namespacePrefixesIter = envelope.getNamespacePrefixes(); while (namespacePrefixesIter.hasNext()) { String namespacePrefix = (String) namespacePrefixesIter.next(); String namespace = envelope.getNamespaceURI(namespacePrefix); if (WSConstants.WS_ADDR_NAMESPACE.equals(namespace)) { wsAddrPrefix = namespacePrefix; } else if (WSConstants.WS_SECURITY_UTILITY_NAMESPACE.equals(namespace)) { wsuPrefix = namespacePrefix; } } if (null == wsAddrPrefix) { wsAddrPrefix = getUniquePrefix("a", envelope); envelope.addNamespaceDeclaration(wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE); } if (null == wsuPrefix) { /* * Using "wsu" is very important for the IP-STS X509 credential. * Apparently the STS refuses when the namespace prefix of the * wsu:Id on the WS-Addressing To element is different from the * wsu:Id prefix on the WS-Security timestamp. */ wsuPrefix = "wsu"; envelope.addNamespaceDeclaration(wsuPrefix, WSConstants.WS_SECURITY_UTILITY_NAMESPACE); } SOAPFactory factory = SOAPFactory.newInstance(); SOAPHeaderElement actionHeaderElement = header .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "Action", wsAddrPrefix)); actionHeaderElement.setMustUnderstand(true); actionHeaderElement.addTextNode(this.action); SOAPHeaderElement messageIdElement = header .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "MessageID", wsAddrPrefix)); String messageId = "urn:uuid:" + UUID.randomUUID().toString(); context.put(MESSAGE_ID_CONTEXT_ATTRIBUTE, messageId); messageIdElement.addTextNode(messageId); SOAPHeaderElement replyToElement = header .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "ReplyTo", wsAddrPrefix)); SOAPElement addressElement = factory.createElement("Address", wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE); addressElement.addTextNode("http://www.w3.org/2005/08/addressing/anonymous"); replyToElement.addChildElement(addressElement); SOAPHeaderElement toElement = header .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "To", wsAddrPrefix)); toElement.setMustUnderstand(true); toElement.addTextNode(this.to); String toIdentifier = "to-id-" + UUID.randomUUID().toString(); toElement.addAttribute(new QName(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", wsuPrefix), toIdentifier); try { toElement.setIdAttributeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", true); } catch (UnsupportedOperationException e) { // Axis2 has missing implementation of setIdAttributeNS LOG.error("error setting Id attribute: " + e.getMessage()); } context.put(TO_ID_CONTEXT_ATTRIBUTE, toIdentifier); }
From source file:eu.payzen.webservices.sdk.handler.soap.HeaderHandler.java
/** * Takes the outgoing SOAP message and modifies it adding the header * information/*from w ww . j av a2s .c o m*/ * * @param smc SOAP message context * @return boolean indicating outbound property */ public boolean handleMessage(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (Boolean.TRUE.equals(outboundProperty)) { SOAPMessage message = smc.getMessage(); try { SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); //Creates header into SOAP envelope SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } // Add shopId addHeaderField(header, "shopId", this.shopId); // Add User name if (wsUser != null) { addHeaderField(header, "wsUser", this.wsUser); } // Add return url if (returnUrl != null) { addHeaderField(header, "returnUrl", this.returnUrl); } // Add ecsPaymentId if (ecsPaymentId != null) { addHeaderField(header, "ecsPaymentId", this.ecsPaymentId); } // Add remoteId if (remoteId != null) { addHeaderField(header, "remoteId", this.remoteId); } //DynamicHeaders if (dynamicHeaders != null) { for (String key : dynamicHeaders.keySet()) { String value = dynamicHeaders.get(key); if (value != null) { addHeaderField(header, key, value); } } } // Timestamp TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(tz); String nowAsISO = df.format(new Date()); addHeaderField(header, "timestamp", nowAsISO); // Mode addHeaderField(header, "mode", this.mode); // Add requestId String requestId = UUID.randomUUID().toString(); addHeaderField(header, "requestId", requestId); // Authentication token String tokenString = requestId + nowAsISO; addHeaderField(header, "authToken", sign(tokenString, shopKey)); } catch (SOAPException e) { logger.error("Error sending header", e); } } return outboundProperty; }
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;/* w w w. j a va2s . 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:cl.nic.dte.net.ConexionSii.java
@SuppressWarnings("unchecked") private String getSemilla() throws UnsupportedOperationException, SOAPException, IOException, XmlException, ConexionSiiException { SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance(); SOAPConnection con = scFactory.createConnection(); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.detachNode();// ww w .j a v a2 s . c o m String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_SEMILLA"); Name bodyName = envelope.createName("getSeed", "m", urlSolicitud); message.getMimeHeaders().addHeader("SOAPAction", ""); body.addBodyElement(bodyName); URL endpoint = new URL(urlSolicitud); SOAPMessage responseSII = con.call(message, endpoint); SOAPPart sp = responseSII.getSOAPPart(); SOAPBody b = sp.getEnvelope().getBody(); cl.sii.xmlSchema.RESPUESTADocument resp = null; for (Iterator<SOAPBodyElement> res = b.getChildElements( sp.getEnvelope().createName("getSeedResponse", "ns1", urlSolicitud)); res.hasNext();) { for (Iterator<SOAPBodyElement> ret = res.next().getChildElements( sp.getEnvelope().createName("getSeedReturn", "ns1", urlSolicitud)); ret.hasNext();) { HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/XMLSchema"); XmlOptions opts = new XmlOptions(); opts.setLoadSubstituteNamespaces(namespaces); resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts); } } if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) { return resp.getRESPUESTA().getRESPBODY().getSEMILLA(); } else { throw new ConexionSiiException( "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: " + resp.getRESPUESTA().getRESPHDR().getGLOSA()); } }
From source file:cl.nic.dte.net.ConexionSii.java
@SuppressWarnings("unchecked") public String getToken(PrivateKey pKey, X509Certificate cert) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, SAXException, IOException, ParserConfigurationException, XmlException, UnsupportedOperationException, SOAPException, ConexionSiiException { String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_TOKEN"); String semilla = getSemilla(); GetTokenDocument req = GetTokenDocument.Factory.newInstance(); req.addNewGetToken().addNewItem().setSemilla(semilla); HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/SiiDte"); XmlOptions opts = new XmlOptions(); opts = new XmlOptions(); opts.setSaveImplicitNamespaces(namespaces); opts.setLoadSubstituteNamespaces(namespaces); opts.setSavePrettyPrint();/*from www . j av a 2s . c o m*/ opts.setSavePrettyPrintIndent(0); req = GetTokenDocument.Factory.parse(req.newInputStream(opts), opts); // firmo req.sign(pKey, cert); SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance(); SOAPConnection con = scFactory.createConnection(); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.detachNode(); Name bodyName = envelope.createName("getToken", "m", urlSolicitud); SOAPBodyElement gltp = body.addBodyElement(bodyName); Name toKname = envelope.createName("pszXml"); SOAPElement toKsymbol = gltp.addChildElement(toKname); opts = new XmlOptions(); opts.setCharacterEncoding("ISO-8859-1"); opts.setSaveImplicitNamespaces(namespaces); toKsymbol.addTextNode(req.xmlText(opts)); message.getMimeHeaders().addHeader("SOAPAction", ""); URL endpoint = new URL(urlSolicitud); message.writeTo(System.out); SOAPMessage responseSII = con.call(message, endpoint); SOAPPart sp = responseSII.getSOAPPart(); SOAPBody b = sp.getEnvelope().getBody(); cl.sii.xmlSchema.RESPUESTADocument resp = null; for (Iterator<SOAPBodyElement> res = b.getChildElements( sp.getEnvelope().createName("getTokenResponse", "ns1", urlSolicitud)); res.hasNext();) { for (Iterator<SOAPBodyElement> ret = res.next().getChildElements( sp.getEnvelope().createName("getTokenReturn", "ns1", urlSolicitud)); ret.hasNext();) { namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/XMLSchema"); opts.setLoadSubstituteNamespaces(namespaces); resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts); } } if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) { return resp.getRESPUESTA().getRESPBODY().getTOKEN(); } else { throw new ConexionSiiException( "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: " + resp.getRESPUESTA().getRESPHDR().getGLOSA()); } }
From source file:cl.nic.dte.net.ConexionSii.java
@SuppressWarnings("unchecked") private RESPUESTADocument getEstadoDTE(String rutConsultante, Documento dte, String token, String urlSolicitud) throws UnsupportedOperationException, SOAPException, MalformedURLException, XmlException { String rutEmisor = dte.getEncabezado().getEmisor().getRUTEmisor(); String rutReceptor = dte.getEncabezado().getReceptor().getRUTRecep(); Integer tipoDTE = dte.getEncabezado().getIdDoc().getTipoDTE().intValue(); long folioDTE = dte.getEncabezado().getIdDoc().getFolio(); String fechaEmision = Utilities.fechaEstadoDte .format(dte.getEncabezado().getIdDoc().getFchEmis().getTime()); long montoTotal = dte.getEncabezado().getTotales().getMntTotal(); SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance(); SOAPConnection con = scFactory.createConnection(); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.detachNode();/* ww w. ja va 2 s.c o m*/ Name bodyName = envelope.createName("getEstDte", "m", urlSolicitud); SOAPBodyElement gltp = body.addBodyElement(bodyName); Name toKname = envelope.createName("RutConsultante"); SOAPElement toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutConsultante.substring(0, rutConsultante.length() - 2)); toKname = envelope.createName("DvConsultante"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutConsultante.substring(rutConsultante.length() - 1, rutConsultante.length())); toKname = envelope.createName("RutCompania"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutEmisor.substring(0, rutEmisor.length() - 2)); toKname = envelope.createName("DvCompania"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutEmisor.substring(rutEmisor.length() - 1, rutEmisor.length())); toKname = envelope.createName("RutReceptor"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutReceptor.substring(0, rutReceptor.length() - 2)); toKname = envelope.createName("DvReceptor"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(rutReceptor.substring(rutReceptor.length() - 1, rutReceptor.length())); toKname = envelope.createName("TipoDte"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(Integer.toString(tipoDTE)); toKname = envelope.createName("FolioDte"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(Long.toString(folioDTE)); toKname = envelope.createName("FechaEmisionDte"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(fechaEmision); toKname = envelope.createName("MontoDte"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(Long.toString(montoTotal)); toKname = envelope.createName("Token"); toKsymbol = gltp.addChildElement(toKname); toKsymbol.addTextNode(token); message.getMimeHeaders().addHeader("SOAPAction", ""); URL endpoint = new URL(urlSolicitud); SOAPMessage responseSII = con.call(message, endpoint); SOAPPart sp = responseSII.getSOAPPart(); SOAPBody b = sp.getEnvelope().getBody(); for (Iterator<SOAPBodyElement> res = b.getChildElements( sp.getEnvelope().createName("getEstDteResponse", "ns1", urlSolicitud)); res.hasNext();) { for (Iterator<SOAPBodyElement> ret = res.next().getChildElements( sp.getEnvelope().createName("getEstDteReturn", "ns1", urlSolicitud)); ret.hasNext();) { HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/XMLSchema"); XmlOptions opts = new XmlOptions(); opts.setLoadSubstituteNamespaces(namespaces); return RESPUESTADocument.Factory.parse(ret.next().getValue(), opts); } } return null; }
From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java
public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) { //System.err.println("onMessage called for RegistrySOAPServlet"); SOAPMessage soapResponse = null; SOAPHeader sh = null;//from w w w . ja v a 2s. c o m try { // set 'sh' variable ASAP (before "firstly") SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPBody sb = se.getBody(); sh = se.getHeader(); // Firstly we put save the attached repository items in a map HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>(); Iterator<?> apIter = msg.getAttachments(); while (apIter.hasNext()) { AttachmentPart ap = (AttachmentPart) apIter.next(); //Get the content for the attachment RepositoryItem ri = processIncomingAttachment(ap); idToRepositoryItemMap.put(ri.getId(), ri); } // Log received message //if (log.isTraceEnabled()) { // Warning! BAOS.toString() uses platform's default encoding /* ByteArrayOutputStream msgOs = new ByteArrayOutputStream(); msg.writeTo(msgOs); msgOs.close(); System.err.println(msgOs.toString()); */ //System.err.println(sb.getTextContent()); // log.trace("incoming message:\n" + msgOs.toString()); //} // verify signature // returns false if no security header, throws exception if invalid CredentialInfo credentialInfo = new CredentialInfo(); boolean noRegRequired = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.noUserRegistrationRequired", "false")) .booleanValue(); if (!noRegRequired) { WSS4JSecurityUtilBST.verifySOAPEnvelopeOnServerBST(se, credentialInfo); } //The ebXML registry request is the only element in the SOAPBody StringWriter requestXML = new StringWriter(); //The request as an XML String String requestRootElement = null; Iterator<?> iter = sb.getChildElements(); int i = 0; while (iter.hasNext()) { Object obj = iter.next(); if (!(obj instanceof SOAPElement)) { continue; } if (i++ == 0) { SOAPElement elem = (SOAPElement) obj; Name name = elem.getElementName(); requestRootElement = name.getLocalName(); StreamResult result = new StreamResult(requestXML); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(elem), result); } else { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.invalidRequest")); } } if (requestRootElement == null) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest")); } // unmarshalling request to message Object message = bu.getRequestObject(requestRootElement, requestXML.toString()); if (message instanceof JAXBElement<?>) { // If Element; take ComplexType from Element message = ((JAXBElement<?>) message).getValue(); } // request sets ServerContext with ComplexType: RegistryObjectType BSTRequest request = new BSTRequest(req, credentialInfo, message, idToRepositoryItemMap); Response response = request.process(); // response.getMessage() is ComplexType again soapResponse = createResponseSOAPMessage(response); if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus() .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) { idToRepositoryItemMap = response.getIdToRepositoryItemMap(); Iterator<?> mapKeysIter = idToRepositoryItemMap.keySet().iterator(); while (mapKeysIter.hasNext()) { String id = (String) mapKeysIter.next(); RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id); String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id); DataHandler dh = repositoryItem.getDataHandler(); AttachmentPart ap = soapResponse.createAttachmentPart(dh); ap.setMimeHeader("Content-Type", "text/xml"); ap.setContentId(cid); soapResponse.addAttachmentPart(ap); if (log.isTraceEnabled()) { log.trace("adding attachment: contentId=" + id); } } } } catch (Throwable t) { //Do not log ObjectNotFoundException as it clutters the log if (!(t instanceof ObjectNotFoundException)) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException", new Object[] { t.getMessage() }), t); Throwable cause = t.getCause(); while (cause != null) { log.error(ServerResourceBundle.getInstance().getString("message.CausedBy", new Object[] { cause.getMessage() }), cause); cause = cause.getCause(); } } soapResponse = createFaultSOAPMessage(t, sh); } if (log.isTraceEnabled()) { try { ByteArrayOutputStream rspOs = new ByteArrayOutputStream(); soapResponse.writeTo(rspOs); rspOs.close(); // Warning! BAOS.toString() uses platform's default encoding log.trace("response message:\n" + rspOs.toString()); } catch (Exception e) { log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage", new Object[] { e.getMessage() }), e); } } return soapResponse; }
From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java
@SuppressWarnings("unchecked") public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) { SOAPMessage soapResponse = null; SOAPHeader soapHeader = null; try {/*w w w. j av a 2s . co m*/ // extract SOAP related parts from incoming SOAP message // set 'soapHeader' variable ASAP (before "firstly") SOAPPart soapPart = msg.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); soapHeader = soapEnvelope.getHeader(); /**************************************************************** * * REPOSITORY ITEM HANDLING (IN) REPOSITORY ITEM HANDLING (IN) * ***************************************************************/ // Firstly we put save the attached repository items in a map HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>(); Iterator<AttachmentPart> apIter = msg.getAttachments(); while (apIter.hasNext()) { AttachmentPart ap = apIter.next(); // Get the content for the attachment RepositoryItem ri = processIncomingAttachment(ap); idToRepositoryItemMap.put(ri.getId(), ri); } /**************************************************************** * * LOGGING (IN) LOGGING (IN) LOGGING (IN) LOGGING (IN) * ***************************************************************/ // Log received message if (log.isTraceEnabled()) { // Warning! BAOS.toString() uses platform's default encoding ByteArrayOutputStream msgOs = new ByteArrayOutputStream(); msg.writeTo(msgOs); msgOs.close(); log.trace("incoming message:\n" + msgOs.toString()); } /**************************************************************** * * MESSAGE VERIFICATION (IN) MESSAGE VERIFICATION (IN) * ***************************************************************/ CredentialInfo credentialInfo = new CredentialInfo(); WSS4JSecurityUtilSAML.verifySOAPEnvelopeOnServerSAML(soapEnvelope, credentialInfo); /**************************************************************** * * RS:REQUEST HANDLING RS:REQUEST HANDLING RS:REQUEST * ***************************************************************/ // The ebXML registry request is the only element in the SOAPBody StringWriter requestXML = new StringWriter(); // The request as an // XML String String requestRootElement = null; Iterator<?> iter = soapBody.getChildElements(); int i = 0; while (iter.hasNext()) { Object obj = iter.next(); if (!(obj instanceof SOAPElement)) { continue; } if (i++ == 0) { SOAPElement elem = (SOAPElement) obj; Name name = elem.getElementName(); requestRootElement = name.getLocalName(); StreamResult result = new StreamResult(requestXML); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(elem), result); } else { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.invalidRequest")); } } if (requestRootElement == null) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest")); } // unmarshalling request to message Object message = bu.getRequestObject(requestRootElement, requestXML.toString()); if (message instanceof JAXBElement<?>) { // If Element; take ComplexType from Element message = ((JAXBElement<?>) message).getValue(); } SAMLRequest request = new SAMLRequest(req, credentialInfo.assertion, message, idToRepositoryItemMap); Response response = request.process(); /**************************************************************** * * RESPONSE HANDLING RESPONSE HANDLING RESPONSE HANDLING * ***************************************************************/ soapResponse = createResponseSOAPMessage(response); if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus() .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) { idToRepositoryItemMap = response.getIdToRepositoryItemMap(); Iterator<String> mapKeysIter = idToRepositoryItemMap.keySet().iterator(); while (mapKeysIter.hasNext()) { String id = mapKeysIter.next(); RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id); String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id); DataHandler dh = repositoryItem.getDataHandler(); AttachmentPart ap = soapResponse.createAttachmentPart(dh); ap.setContentId(cid); soapResponse.addAttachmentPart(ap); if (log.isTraceEnabled()) { log.trace("adding attachment: contentId=" + id); } } } } catch (Throwable t) { // Do not log ObjectNotFoundException as it clutters the log if (!(t instanceof ObjectNotFoundException)) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException", new Object[] { t.getMessage() }), t); Throwable cause = t.getCause(); while (cause != null) { log.error(ServerResourceBundle.getInstance().getString("message.CausedBy", new Object[] { cause.getMessage() }), cause); cause = cause.getCause(); } } soapResponse = createFaultSOAPMessage(t, soapHeader); } if (log.isTraceEnabled()) { try { ByteArrayOutputStream rspOs = new ByteArrayOutputStream(); soapResponse.writeTo(rspOs); rspOs.close(); // Warning! BAOS.toString() uses platform's default encoding log.trace("response message:\n" + rspOs.toString()); } catch (Exception e) { log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage", new Object[] { e.getMessage() }), e); } } return soapResponse; }