/** * 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; } }
/** * @param query the input of the user * @return SOAP message which is good for cross-platform web service */ public SOAPMessage sendSOAPMessage(String query, URL serverURL) throws SOAPException { /** create a SOAP msg from query */ SOAPMessage wsRequest = MessageFactory.newInstance().createMessage(); // SOAP params SOAPPart part = wsRequest.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPBody body = envelope.getBody(); // Name: a local name, a namespace prefix, and a namesapce URI. Name name = envelope.createName("query", "yyns", "http://cis555.co.nf/"); SOAPElement elem = body.addChildElement(name); elem.addTextNode(query); // body.addChildElement(envelope.createName("query", "yyns", // "http://cis555.co.nf/")).addTextNode(query); //### wsRequest.saveChanges(); /** send SOAP to P2P ring */ // get response SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection(); SOAPMessage wsResponse = conn.call(wsRequest, serverURL); conn.close(); return wsResponse; }
/** @param args */ public static void main(String[] args) { try { MessageFactory factory = MessageFactory.newInstance(); SOAPMessage soapMsg = factory.createMessage(); SOAPPart part = soapMsg.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.addTextNode("Training Details"); SOAPBodyElement element = body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog")); element.addChildElement("WS").addTextNode("Training on Web service"); SOAPBodyElement element1 = body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog")); element1.addChildElement("Spring").addTextNode("Training on Spring 3.0"); soapMsg.writeTo(System.out); FileOutputStream fOut = new FileOutputStream("SoapMessage.xml"); soapMsg.writeTo(fOut); System.out.println(); System.out.println("SOAP msg created"); } catch (Exception e) { e.printStackTrace(); } }
public STElement call() throws IOException { try { soapRequest.saveChanges(); if (debug) { System.out.print("********* REQUEST:"); Element e = new DOMReader().read(soapRequest.getSOAPPart()).getRootElement(); writer.write(e); System.out.println(); System.out.println("------------------"); } soapResponse = conn.call(soapRequest, wsdlURL); if (debug) { System.out.print("********* RESPONSE:"); Element e = new DOMReader().read(soapResponse.getSOAPPart()).getRootElement(); writer.write(e); System.out.println(); System.out.println("------------------"); } SOAPPart sp = soapResponse.getSOAPPart(); SOAPEnvelope env = sp.getEnvelope(); return new STElement(env.getBody()); } catch (SOAPException e) { e.printStackTrace(); return null; } }
@Test public void buildARecordTest() throws SOAPException, IOException, SAXException, ParserConfigurationException, TransformerException { MessageFactory factory = MessageFactory.newInstance(); SOAPMessage request = factory.createMessage(); SOAPPart part = request.getSOAPPart(); DOMSource domSource = new DOMSource(getDocumentBuilder().parse(new InputSource(new StringReader(REQUEST_MSG)))); part.setContent(domSource); Dispatch<SOAPMessage> dispatch = testService.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE); SOAPMessage response = null; try { response = dispatch.invoke(request); } catch (Exception e) { e.printStackTrace(); } if (response != null) { Source src = response.getSOAPPart().getContent(); DOMResult result = new DOMResult(); getTransformer().transform(src, result); Document resultDoc = (Document) result.getNode(); Document controlDoc = xmlParser.parse(new StringReader(TEST_RESPONSE)); assertTrue( "control document not same as instance document", comparer.isNodeEqual(controlDoc, resultDoc)); } }
private SoapMessage makeInvocation( Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties) throws Exception { Document doc = readDocument("wsse-request-clean.xml"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(); PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor(); SoapMessage msg = new SoapMessage(new MessageImpl()); Exchange ex = new ExchangeImpl(); ex.setInMessage(msg); SOAPMessage saajMsg = MessageFactory.newInstance().createMessage(); SOAPPart part = saajMsg.getSOAPPart(); part.setContent(new DOMSource(doc)); saajMsg.saveChanges(); msg.setContent(SOAPMessage.class, saajMsg); for (String key : outProperties.keySet()) { msg.put(key, outProperties.get(key)); } handler.handleMessage(msg); doc = part; for (String xpath : xpaths) { assertValid(xpath, doc); } byte[] docbytes = getMessageBytes(doc); XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); doc = StaxUtils.read(db, reader, false); WSS4JInInterceptor inHandler = new WSS4JInInterceptor(); SoapMessage inmsg = new SoapMessage(new MessageImpl()); ex.setInMessage(inmsg); inmsg.setContent(SOAPMessage.class, saajMsg); for (String key : inProperties.keySet()) { inHandler.setProperty(key, inProperties.get(key)); } inHandler.handleMessage(inmsg); return inmsg; }
public STElement getRequest(String operation, String prefix) throws SOAPException { SOAPPart sp = soapRequest.getSOAPPart(); SOAPEnvelope env = sp.getEnvelope(); STElement e = new STElement(env.getBody()); if (operation != null) if (prefix != null) e = e.addChild(operation, prefix); else e = e.addChild(operation); return e; }
public void addNamespace(String prefix, String name) { try { SOAPPart sp = soapRequest.getSOAPPart(); SOAPEnvelope env = sp.getEnvelope(); env.addNamespaceDeclaration(prefix, name); } catch (SOAPException e) { e.printStackTrace(); } }
/** * @param wsResponse the web service response from P2P ring * @return html format to show users */ String parseSOAPIntoHTML(SOAPMessage wsResponse) throws SOAPException { StringBuffer result = new StringBuffer(); SOAPPart part = wsResponse.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPBody body = envelope.getBody(); Iterator<Node> iter = body.getChildElements(envelope.createName("response", "yyns", "http://cis555.co.nf/")); NodeList childNodes = ((org.w3c.dom.Node) iter.next()).getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { result.append(childNodes.item(i).getTextContent()).append("<br>"); } return result.toString(); }
@Before public void setUp() throws Exception { msg = MessageFactory.newInstance().createMessage(); sp = msg.getSOAPPart(); envelope = sp.getEnvelope(); hdr = envelope.getHeader(); }
@Test public void updateinstanceTest() throws SOAPException, IOException, SAXException, ParserConfigurationException, TransformerException { MessageFactory factory = MessageFactory.newInstance(); SOAPMessage request = factory.createMessage(); SOAPPart part = request.getSOAPPart(); DOMSource domSource = new DOMSource(getDocumentBuilder().parse(new InputSource(new StringReader(REQUEST_MSG)))); part.setContent(domSource); Dispatch<SOAPMessage> dispatch = testService.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE); try { dispatch.invoke(request); } catch (SOAPFaultException sfe) { assertTrue("incorrect SOAPFaultException", sfe.getMessage().contains("EclipseLink-5010")); } }
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; }
@Test public void testHandleMessage() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); String samlAssertion = "<Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\"" + " AssertionID=\"_42e7a00652420d86ee884f295a3fbf02\">" + "</Assertion>"; WSSecuritySOAPHandler testedInstance = new WSSecuritySOAPHandler(); testedInstance.setPrivateKey(privateKey); testedInstance.setAssertion(samlAssertion); SOAPMessageContext mockSoapMessageContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockSoapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) .andReturn(true); MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addBodyElement(new QName("http://www.example.com", "Test")); EasyMock.expect(mockSoapMessageContext.getMessage()).andReturn(soapMessage); // prepare EasyMock.replay(mockSoapMessageContext); // operate testedInstance.handleMessage(mockSoapMessageContext); // verify EasyMock.verify(mockSoapMessageContext); LOG.debug(toString(soapPart)); }
public String invokeServiceMethod(String methodName, String[] args) { try { MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); SOAPMessage request = factory.createMessage(); SOAPPart soap = request.getSOAPPart(); SOAPEnvelope envelope = soap.getEnvelope(); SOAPBody body = envelope.getBody(); SOAPElement content = body.addBodyElement(new QName(serviceNs, methodName, "itu")); int c = 0; for (String arg : args) { SOAPElement name; name = content.addChildElement("arg" + c++); name.setTextContent(arg); } Dispatch<SOAPMessage> dispatch = webservice.createDispatch(port, SOAPMessage.class, Service.Mode.MESSAGE); SOAPMessage response = dispatch.invoke(request); String text = response.getSOAPBody().getTextContent(); return text; } catch (SOAPException e) { throw new RuntimeException(e); } }
@Test public void testCustomProcessorObject() throws Exception { Document doc = readDocument("wsse-request-clean.xml"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(); PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor(); SoapMessage msg = new SoapMessage(new MessageImpl()); Exchange ex = new ExchangeImpl(); ex.setInMessage(msg); SOAPMessage saajMsg = MessageFactory.newInstance().createMessage(); SOAPPart part = saajMsg.getSOAPPart(); part.setContent(new DOMSource(doc)); saajMsg.saveChanges(); msg.setContent(SOAPMessage.class, saajMsg); msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE); msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties"); msg.put(WSHandlerConstants.USER, "myalias"); msg.put("password", "myAliasPassword"); handler.handleMessage(msg); doc = part; assertValid("//wsse:Security", doc); assertValid("//wsse:Security/ds:Signature", doc); byte[] docbytes = getMessageBytes(doc); XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); doc = StaxUtils.read(db, reader, false); final Map<String, Object> properties = new HashMap<String, Object>(); final Map<QName, Object> customMap = new HashMap<QName, Object>(); customMap.put(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN), CustomProcessor.class); properties.put(WSS4JInInterceptor.PROCESSOR_MAP, customMap); WSS4JInInterceptor inHandler = new WSS4JInInterceptor(properties); SoapMessage inmsg = new SoapMessage(new MessageImpl()); ex.setInMessage(inmsg); inmsg.setContent(SOAPMessage.class, saajMsg); inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE); inHandler.handleMessage(inmsg); List<WSHandlerResult> results = getResults(inmsg); assertTrue(results != null && results.size() == 1); List<WSSecurityEngineResult> signatureResults = results.get(0).getActionResults().get(WSConstants.SIGN); assertTrue(signatureResults.size() == 1); Object obj = signatureResults.get(0).get("foo"); assertNotNull(obj); assertEquals(obj.getClass().getName(), CustomProcessor.class.getName()); }
public boolean handleMessage(SOAPMessageContext smc) { Boolean outbound = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outbound) { // outbound message // *** #8 *** // get token from response context String propertyValue = (String) smc.get(RESPONSE_PROPERTY); System.out.printf("%s received '%s'%n", CLASS_NAME, propertyValue); // put token in response SOAP header try { // get SOAP envelope SOAPMessage msg = smc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); // add header SOAPHeader sh = se.getHeader(); if (sh == null) sh = se.addHeader(); // add header element (name, namespace prefix, namespace) Name name = se.createName(RESPONSE_HEADER, "e", RESPONSE_NS); SOAPHeaderElement element = sh.addHeaderElement(name); // *** #9 *** // add header element value String newValue = propertyValue + "," + TOKEN; element.addTextNode(newValue); System.out.printf("%s put token '%s' on response message header%n", CLASS_NAME, TOKEN); } catch (SOAPException e) { System.out.printf("Failed to add SOAP header because of %s%n", e); } } else { // inbound message // get token from request SOAP header try { // get SOAP envelope header SOAPMessage msg = smc.getMessage(); SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPHeader sh = se.getHeader(); // check header if (sh == null) { System.out.println("Header not found."); return true; } // get Ticket header element Name nameTicket = se.createName(REQUEST_TICKET_HEADER, "e", REQUEST_NS); Iterator it = sh.getChildElements(nameTicket); // check header element if (!it.hasNext()) { System.out.printf("Header element %s not found.%n", REQUEST_TICKET_HEADER); return true; } SOAPElement elementTicket = (SOAPElement) it.next(); // *** #4 *** // get header element value String headerTicketValue = elementTicket.getValue(); System.out.printf("%s got '%s'%n", CLASS_NAME, headerTicketValue); // *** #5 *** // put Ticket token in request context System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerTicketValue); smc.put(REQUEST_TICKET_PROPERTY, headerTicketValue); // set property scope to application so that server class can access property smc.setScope(REQUEST_TICKET_PROPERTY, Scope.APPLICATION); // get Author header element Name nameAuthor = se.createName(REQUEST_AUTHOR_HEADER, "e", REQUEST_NS); Iterator itAuthor = sh.getChildElements(nameAuthor); // check header element if (!itAuthor.hasNext()) { System.out.printf("Header element %s not found.%n", REQUEST_AUTHOR_HEADER); return true; } SOAPElement elementAuthor = (SOAPElement) itAuthor.next(); // *** #4 *** // get Author header element value String headerAuthorValue = elementAuthor.getValue(); System.out.printf("%s got '%s'%n", CLASS_NAME, headerAuthorValue); // *** #5 *** // put Author token in request context System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerAuthorValue); smc.put(REQUEST_AUTHOR_PROPERTY, headerAuthorValue); // set property scope to application so that server class can access property smc.setScope(REQUEST_AUTHOR_PROPERTY, Scope.APPLICATION); // MAC // get MAC header element Name nameMac = se.createName(REQUEST_MAC_HEADER, "e", REQUEST_NS); Iterator itMac = sh.getChildElements(nameAuthor); // check header element if (!itMac.hasNext()) { System.out.printf("Header element %s not found.%n", REQUEST_MAC_HEADER); return true; } SOAPElement elementMac = (SOAPElement) itMac.next(); // *** #4 *** // get MAC header element value String headerMacValue = elementMac.getTextContent(); System.out.printf("%s got '%s'%n", CLASS_NAME, headerMacValue); // *** #5 *** // put MAC token in request context System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerMacValue); smc.put(REQUEST_MAC_PROPERTY, headerMacValue); // set property scope to application so that server class can access property smc.setScope(REQUEST_MAC_PROPERTY, Scope.APPLICATION); String bodyValue = se.getBody().getTextContent(); // *** #5 *** // put Body token in request context System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, bodyValue); smc.put(REQUEST_BODY_PROPERTY, bodyValue); // set property scope to application so that server class can access property smc.setScope(REQUEST_BODY_PROPERTY, Scope.APPLICATION); msg.writeTo(System.out); } catch (SOAPException e) { System.out.printf("Failed to get SOAP header because of %s%n", e); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; }
public boolean patientAndProviderEmailSend( String fromUser, String fromUserProvider, String toUser, String toUserProvider, String subject, String message) { String ret = ""; // System.out.println("ticket: "+ticket); try { SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance(); SOAPConnection conn = scf.createConnection(); // Create message MessageFactory mf = MessageFactory.newInstance(); SOAPMessage msg = mf.createMessage(); // Object for message parts SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope env = sp.getEnvelope(); env.addNamespaceDeclaration("soap", "http://schemas.xmlsoap.org/soap/envelop/"); env.addNamespaceDeclaration("urn", "urn:gov:hhs:fha:nhinc:common:task"); SOAPHeader header = env.getHeader(); SOAPBody body = env.getBody(); // Populate body SOAPElement be = body.addChildElement("SendMailTaskRequest", "urn"); be.addChildElement("taskID", "urn").addTextNode(EMAIL_TASK_ID); be.addChildElement("fromUser", "urn").addTextNode(fromUser); be.addChildElement("fromUserProvider", "urn").addTextNode(fromUserProvider); be.addChildElement("toUser", "urn").addTextNode(toUser); be.addChildElement("toUserProvider", "urn").addTextNode(toUserProvider); be.addChildElement("subject", "urn").addTextNode(subject); be.addChildElement("message", "urn").addTextNode(message); // be.addChildElement("ticket", "urn").addTextNode(ticket); // be.addChildElement("action", "urn").addTextNode(action); // be.addChildElement("message", "urn").addTextNode(message); // be.addChildElement("patientID", "urn").addTextNode(patientId); // Save message msg.saveChanges(); // View input // System.out.println("\n Soap request:\n"); // msg.writeTo(System.out); // Send // String urlval = "http://208.75.163.61:8080/TaskManager/TaskManagerService"; String urlval = getProperty("EmailSendEndpoint"); SOAPMessage reply = conn.call(msg, urlval); // Create transformer TransformerFactory tff = TransformerFactory.newInstance(); Transformer tf = tff.newTransformer(); // Get reply content Source source = reply.getSOAPPart().getContent(); Writer outWriter = new StringWriter(); // Set output transformation // StreamResult result = new StreamResult(System.out); StreamResult result = new StreamResult(outWriter); // transfrom to get the xml tf.transform(source, result); // close connection conn.close(); String xmlSource = outWriter.toString(); ret = xmlSource; // System.out.println("mail test: "+ret); } catch (Exception e) { e.printStackTrace(); } // assertTrue(ret.indexOf("<detail>Success</detail>")>0); if (ret.indexOf("<detail>Success</detail>") > 0) return true; return false; }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String retval = "<html> <H4>"; try { // Create a message factory. MessageFactory mf = MessageFactory.newInstance(); // Create a message from the message factory. SOAPMessage msg = mf.createMessage(); // Message creation takes care of creating the SOAPPart - a // required part of the message as per the SOAP 1.1 // specification. SOAPPart sp = msg.getSOAPPart(); // Retrieve the envelope from the soap part to start building // the soap message. SOAPEnvelope envelope = sp.getEnvelope(); // Create a soap header from the envelope. SOAPHeader hdr = envelope.getHeader(); // Create a soap body from the envelope. SOAPBody bdy = envelope.getBody(); // Add a soap body element to the soap body SOAPBodyElement gltp = bdy.addBodyElement( envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com")); gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com")) .addTextNode("SUNW"); StringBuffer urlSB = new StringBuffer(); urlSB.append(req.getScheme()).append("://").append(req.getServerName()); urlSB.append(":").append(req.getServerPort()).append(req.getContextPath()); String reqBase = urlSB.toString(); if (data == null) { data = reqBase + "/index.html"; } // Want to set an attachment from the following url. // Get context URL url = new URL(data); AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url)); ap.setContentType("text/html"); // Add the attachment part to the message. msg.addAttachmentPart(ap); // Create an endpoint for the recipient of the message. if (to == null) { to = reqBase + "/receiver"; } URL urlEndpoint = new URL(to); System.err.println("Sending message to URL: " + urlEndpoint); System.err.println("Sent message is logged in \"sent.msg\""); retval += " Sent message (check \"sent.msg\") and "; FileOutputStream sentFile = new FileOutputStream("sent.msg"); msg.writeTo(sentFile); sentFile.close(); // Send the message to the provider using the connection. SOAPMessage reply = con.call(msg, urlEndpoint); if (reply != null) { FileOutputStream replyFile = new FileOutputStream("reply.msg"); reply.writeTo(replyFile); replyFile.close(); System.err.println("Reply logged in \"reply.msg\""); retval += " received reply (check \"reply.msg\").</H4> </html>"; } else { System.err.println("No reply"); retval += " no reply was received. </H4> </html>"; } } catch (Throwable e) { e.printStackTrace(); logger.severe("Error in constructing or sending message " + e.getMessage()); retval += " There was an error " + "in constructing or sending message. </H4> </html>"; } try { OutputStream os = resp.getOutputStream(); os.write(retval.getBytes()); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); logger.severe("Error in outputting servlet response " + e.getMessage()); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/octet-stream"); try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(fif); List items = sfu.parseRequest(request); Iterator itr = items.iterator(); FileItem image1 = null, image2 = null; if (itr.hasNext()) image1 = (FileItem) itr.next(); if (itr.hasNext()) image2 = (FileItem) itr.next(); byte[] bimage1 = new byte[(int) image1.getSize()]; byte[] bimage2 = new byte[(int) image2.getSize()]; InputStream in = image1.getInputStream(); in.read(bimage1); in.close(); in = image2.getInputStream(); in.read(bimage2); byte[] img1 = new byte[bimage1.length]; for (int i = 0; i < bimage1.length; ++i) img1[i] = bimage1[i]; ByteArrayInputStream bais = new ByteArrayInputStream(img1); BufferedImage bufimg1 = ImageIO.read(bais); byte[] img2 = new byte[bimage2.length]; for (int i = 0; i < bimage2.length; ++i) img2[i] = bimage2[i]; ByteArrayInputStream bais1 = new ByteArrayInputStream(img2); BufferedImage bufimg2 = ImageIO.read(bais1); ProgressListener progressListener = new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("We are currently reading item " + pItems); if (pContentLength == -1) { System.out.println("So far, " + pBytesRead + " bytes have been read."); } else { System.out.println( "So far, " + pBytesRead + " of " + pContentLength + " bytes have been read."); } } }; sfu.setProgressListener(progressListener); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection wsdircon = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "imbagaming"); PreparedStatement st = wsdircon.prepareStatement( "SELECT wsdl,count FROM WEBSERVICEDATABASE WHERE panorama='yes' and status='up' ORDER BY count"); ResultSet rs = st.executeQuery(); String wsdlString = ""; int count = 0; if (rs.next()) { System.out.println(wsdlString = rs.getString(1)); count = rs.getInt(2); } else { response.sendRedirect("effectchoosere.htm"); } PreparedStatement st1 = wsdircon.prepareStatement( "UPDATE WEBSERVICEDATABASE SET count=" + (count + (bufimg1.getWidth() * bufimg1.getHeight() + bufimg2.getWidth() * bufimg2.getHeight())) + "WHERE wsdl=\'" + wsdlString + "\'"); System.out.println(count); st1.execute(); // parse the wsdl and get the details from it URL wsdl = new URL(wsdlString); // URL wsdl=new URL("http://localhost:8084/IPWebServices/ImageProcess?wsdl"); URLConnection conn = wsdl.openConnection(); InputStream wsdlin = conn.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(wsdlin)); char[] asdf = new char[1024 * 100]; bin.read(asdf); String ss = new String(asdf); bin.close(); wsdlin.close(); String[] info = new String[6]; info[0] = ss.substring(ss.indexOf("targetNamespace=\"") + 17, ss.indexOf("\" name")); System.out.println(info[0]); info[1] = ss.substring(ss.indexOf("name=\"") + 6, ss.indexOf("\">")); System.out.println(info[1]); info[2] = ss.substring(ss.indexOf("port name=\"") + 11, ss.indexOf("\" binding=\"")); System.out.println(info[2]); info[3] = ss.substring(ss.indexOf("<message name=\"") + 15, ss.indexOf("\">\n<part")); // DII String svcName = info[1]; String ns = info[0]; QName svcQname = new QName(ns, svcName); String portName = info[2]; QName portQname = new QName(ns, portName); Service service = Service.create(wsdl, svcQname); Dispatch<SOAPMessage> dispatch = service.createDispatch(portQname, SOAPMessage.class, Service.Mode.MESSAGE); SOAPMessage soapMsg = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMsg.getSOAPPart(); SOAPEnvelope soapEnv = soapPart.getEnvelope(); SOAPBody soapBody = soapEnv.getBody(); Name bodyName = SOAPFactory.newInstance().createName("gogogo_1", "m", ns); SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName); Name param1 = SOAPFactory.newInstance().createName("image1"); Name param2 = SOAPFactory.newInstance().createName("image2"); Name param3 = SOAPFactory.newInstance().createName("effect"); SOAPElement seimage1 = bodyElement.addChildElement(param1); SOAPElement seimage2 = bodyElement.addChildElement(param2); SOAPElement effect = bodyElement.addChildElement(param3); seimage1.addTextNode(Base64.encode(bimage1)); seimage2.addTextNode(Base64.encode(bimage2)); effect.addTextNode("panorama"); SOAPMessage resp = dispatch.invoke(soapMsg); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // handle the response from web service to obtain the processed image resp.writeTo(baos); String saveImg = new String(baos.toByteArray()); int lastI = saveImg.lastIndexOf("<return>") + 8; int firstI = saveImg.indexOf("</return>"); saveImg = saveImg.substring(lastI, firstI); byte[] dwnld = new byte[saveImg.length()]; dwnld = Base64.decode(saveImg); // decrease the count in the service directory PreparedStatement stc = wsdircon.prepareStatement( "SELECT count FROM WEBSERVICEDATABASE WHERE wsdl='" + wsdlString + "'"); rs = stc.executeQuery(); if (rs.next()) count = rs.getInt(1); count -= (bufimg1.getWidth() * bufimg1.getHeight() + bufimg2.getWidth() * bufimg2.getHeight()); if (count < 0) count = 0; PreparedStatement st2 = wsdircon.prepareStatement( "UPDATE WEBSERVICEDATABASE SET count=" + (count) + "WHERE wsdl=\'" + wsdlString + "\'"); System.out.println(count); st2.execute(); wsdircon.close(); // redirect user to the download page ServletOutputStream op = response.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType("application/octet-stream"); response.setContentLength(dwnld.length); response.setHeader( "Content-Disposition", "attachment; filename=\"" + "processedImage.jpg" + "\""); int length = 0; byte[] bbuf = new byte[1000]; ByteArrayInputStream iin = new ByteArrayInputStream(dwnld); while ((iin != null) && ((length = iin.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } // in.close(); iin.close(); op.flush(); op.close(); } } catch (Exception e) { System.out.println(e); } finally { } }
private void validateSignature(SOAPMessage soapMessage) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); SOAPPart soapPart = soapMessage.getSOAPPart(); Source source = null; try { source = soapPart.getContent(); } catch (Exception e) { } Node root = null; Document doc = null; DocumentBuilder db = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); if (root instanceof Document) { doc = (Document) root; } } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } else { // if (source instanceof JAXMStreamSource){ StreamSource streamSource = (StreamSource) source; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); doc = db.parse(streamSource.getInputStream()); root = (Node) doc.getDocumentElement(); root = root.getParentNode(); } ///////////////////////////////////////////// NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new Exception("Cannot find Signature element"); // System.out.println("Cannot find Signature element"); } KeyValueKeySelector kvks = new KeyValueKeySelector(); DOMValidateContext valContext = new DOMValidateContext(kvks, nl.item(0)); // (LoadPublicKey("", "RSA"),nl.item(0)); XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = factory.unmarshalXMLSignature(valContext); if (signature.validate(valContext)) valid = 1; else valid = 0; if (DEBUG_) System.out.println("WSupdate:HS: valid=" + valid); try { md.update(signature.getKeySelectorResult().getKey().getEncoded()); String PK_WS = getHexString(md.digest()); if (PK_WS.equals(PK_Hex)) valid = 1; else valid = 0; if (DEBUG_) System.out.println( "Signature validation by comparing URL digest PK and empadded PK (1 or 0) " + valid); if (DEBUG_) System.out.println("Public Key from SOAP: " + PK_WS); md.reset(); if (DEBUG_) System.out.println("Public Key from DB: " + PK_Hex); // md.update(LoadPublicKey("", "RSA").getEncoded()); // System.out.println("Public Key from File: " + getHexString(md.digest())); } catch (Exception e) { System.out.print(e); } // PublicKey pub = keypair.getPublic(); ///////////////////////////////////////////// // Element envelope = getFirstChildElement(root); // Element header = getFirstChildElement(envelope); // Element sigElement = getFirstChildElement(header); // DOMValidateContext valContext = new DOMValidateContext(LoadPublicKey("","RSA"), // sigElement); // valContext.setIdAttributeNS(getNextSiblingElement(header), // "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); // if(sig.validate(valContext)) valid=1 ; else valid=0; //////////////////////////////////////////// }
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); } }
/** * Parses the result-Message into this class's structure * * @param reply The reply-Message from the Server */ protected void parseResult(SOAPMessage reply) throws SOAPException { SOAPPart soapPart = reply.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); SOAPElement eElement = null; if (log.isDebugEnabled()) { log.debug("XML/A result envelope: " + soapEnvelope.toString()); } SOAPFault fault = soapBody.getFault(); if (fault != null) { handleResultFault(fault); } Name eName = soapEnvelope.createName("ExecuteResponse", "", XMLA_URI); // Get the ExecuteResponse-Node Iterator responseElements = soapBody.getChildElements(eName); if (responseElements.hasNext()) { Object eObj = responseElements.next(); if (eObj == null) { throw new JRRuntimeException("ExecuteResponse Element is null."); } eElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve ExecuteResponse Element."); } // Get the return-Node Name rName = soapEnvelope.createName("return", "", XMLA_URI); Iterator returnElements = eElement.getChildElements(rName); SOAPElement returnElement = null; if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException("return Element is null."); } returnElement = (SOAPElement) eObj; } else { // Should be old-Microsoft XMLA-SDK. Try without m-prefix Name rName2 = soapEnvelope.createName("return", "", ""); returnElements = eElement.getChildElements(rName2); if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException("return Element is null."); } returnElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve return Element."); } } // Get the root-Node Name rootName = soapEnvelope.createName("root", "", MDD_URI); SOAPElement rootElement = null; Iterator rootElements = returnElement.getChildElements(rootName); if (rootElements.hasNext()) { Object eObj = rootElements.next(); if (eObj == null) { throw new JRRuntimeException("root Element is null."); } rootElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve root Element."); } // Get the OlapInfo-Node Name olapInfoName = soapEnvelope.createName("OlapInfo", "", MDD_URI); SOAPElement olapInfoElement = null; Iterator olapInfoElements = rootElement.getChildElements(olapInfoName); if (olapInfoElements.hasNext()) { Object eObj = olapInfoElements.next(); if (eObj == null) { throw new JRRuntimeException("OlapInfo Element is null."); } olapInfoElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve OlapInfo Element."); } parseOLAPInfoElement(olapInfoElement); // Get the Axes Element Name axesName = soapEnvelope.createName("Axes", "", MDD_URI); SOAPElement axesElement = null; Iterator axesElements = rootElement.getChildElements(axesName); if (axesElements.hasNext()) { Object eObj = axesElements.next(); if (eObj == null) { throw new JRRuntimeException("Axes Element is null"); } axesElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve Axes Element."); } parseAxesElement(axesElement); // Get the CellData Element Name cellDataName = soapEnvelope.createName("CellData", "", MDD_URI); SOAPElement cellDataElement = null; Iterator cellDataElements = rootElement.getChildElements(cellDataName); if (cellDataElements.hasNext()) { Object eObj = cellDataElements.next(); if (eObj == null) { throw new JRRuntimeException("CellData element is null"); } cellDataElement = (SOAPElement) eObj; } else { throw new JRRuntimeException("Could not retrieve CellData Element."); } parseCellDataElement(cellDataElement); }
public boolean handleMessage(SOAPMessageContext context) { boolean isSuccess = true; SOAPMessage message = null; boolean isRequest = false; String msgType = Constant.MESSAGE_TYPE_REQUEST; String requestID = null; String requestTimeStamp = null; String responseTimeStamp = null; String nameSpace = null; String webServiceName = null; try { if (context != null) { // get soap message from context message = context.getMessage(); if (message != null) { isRequest = ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); if (isRequest) { // assign a unique request id requestID = UUID.randomUUID().toString(); context.put(Constant.WS_REQUEST_ID, requestID); // get the request time stamp requestTimeStamp = Utility.getTimeStamp(Constant.WS_TIMESTAMP_FORMAT); // find the name space and service name QName wsdlService = null; if (context.get(SOAPMessageContext.WSDL_SERVICE) != null) { wsdlService = (QName) context.get(SOAPMessageContext.WSDL_SERVICE); nameSpace = wsdlService.getNamespaceURI(); webServiceName = wsdlService.getLocalPart(); context.put(Constant.WS_NAME, webServiceName); } // dump the request dump(message, msgType, requestTimeStamp, webServiceName, requestID); // add the authentication header QName userNameElement = new QName(nameSpace, Constant.SOAP_USERNAME); QName passwordElement = new QName(nameSpace, Constant.SOAP_PASSWORD); SOAPHeader header = message.getSOAPHeader(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); header = soapEnvelope.addHeader(); SOAPElement userNameSOAPElement = header.addChildElement(userNameElement); userNameSOAPElement.addTextNode(Utility.getWSProperty(Constant.USERNAME_KEY)); SOAPElement passwordSOAPElement = header.addChildElement(passwordElement); passwordSOAPElement.addTextNode( Utility.convertHexToString(Utility.getWSProperty(Constant.PASSWORD_KEY))); } else { msgType = Constant.MESSAGE_TYPE_RESPONSE; requestID = (String) context.get(Constant.WS_REQUEST_ID); webServiceName = (String) context.get(Constant.WS_NAME); responseTimeStamp = Utility.getTimeStamp(Constant.WS_TIMESTAMP_FORMAT); if (message.getSOAPHeader() != null) { message.getSOAPHeader().detachNode(); } dump(message, msgType, responseTimeStamp, webServiceName, requestID); } } } } catch (Exception e) { } return isSuccess; }