List of usage examples for javax.xml.soap SOAPConnection close
public abstract void close() throws SOAPException;
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downRefdataPartnerXml(String file_refdata_partner_xml) { boolean disp = false; ProgressBar pb = new ProgressBar(); try {/*from w w w. j a v a 2 s . c om*/ // Start timer long startTime = System.currentTimeMillis(); if (disp) System.out.print("- Downloading Refdata partner file... "); else { pb.init("- Downloading Refdata partner file... "); pb.start(); } // Create soaprequest SOAPMessage soapRequest = MessageFactory.newInstance().createMessage(); // Set SOAPAction header line MimeHeaders headers = soapRequest.getMimeHeaders(); headers.addHeader("SOAPAction", "http://refdatabase.refdata.ch/Download"); // Set SOAP main request part SOAPPart soapPart = soapRequest.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody soapBody = envelope.getBody(); // Construct SOAP request message SOAPElement soapBodyElement1 = soapBody.addChildElement("DownloadPartnerInput"); soapBodyElement1.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/"); SOAPElement soapBodyElement2 = soapBodyElement1.addChildElement("PTYPE"); soapBodyElement2.addNamespaceDeclaration("", "http://refdatabase.refdata.ch/Partner_in"); soapBodyElement2.addTextNode("ALL"); soapRequest.saveChanges(); // If needed print out soapRequest in a pretty format // System.out.println(prettyFormatSoapXml(soapRequest)); // Create connection to SOAP server SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = soapConnectionFactory.createConnection(); // wsURL contains service end point String wsURL = "http://refdatabase.refdata.ch/Service/Partner.asmx?WSDL"; SOAPMessage soapResponse = connection.call(soapRequest, wsURL); // Extract response Document doc = soapResponse.getSOAPBody().extractContentAsDocument(); String strBody = getStringFromDoc(doc); String xmlBody = prettyFormat(strBody); // Note: parsing the Document tree and using the removeAttribute function is hopeless! xmlBody = xmlBody.replaceAll("xmlns.*?\".*?\" ", ""); long len = writeToFile(xmlBody, file_refdata_partner_xml); if (!disp) pb.stopp(); long stopTime = System.currentTimeMillis(); System.out.println("\r- Downloading Refdata partner file... " + len / 1024 + " kB in " + (stopTime - startTime) / 1000.0f + " sec"); connection.close(); } catch (Exception e) { if (!disp) pb.stopp(); System.err.println(" Exception: in 'downRefdataPartnerXml'"); e.printStackTrace(); } }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ//w w w .j a va 2 s .c om * * @param operation The operation to invoke */ public static String invokeOperation(OperationInfo operation) throws Exception { try { // Determine if the operation style is RPC boolean isRPC = false; if (operation.getStyle() != null) isRPC = operation.getStyle().equalsIgnoreCase("rpc"); else ; // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //my extension - START //envelope.addNamespaceDeclaration("_ns1", operation.getNamespaceURI()); //my extension - END if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns1", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated return strResponse; } catch (Throwable ex) { throw new Exception("Error invoking operation", ex); } }
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;/*from w ww. ja va2 s .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:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
private String sendTQL(String query) { log.debug(query);/* w ww .java 2s . c o m*/ String result = null; SOAPMessage reply = null; SOAPConnection connection = null; try { // Next, create the actual message MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage(); message.getMimeHeaders().setHeader("SOAPAction", "itqlbean:executeQueryToString"); SOAPBody soapBody = message.getSOAPPart().getEnvelope().getBody(); soapBody.addNamespaceDeclaration("xsd", JDOMNamespaceUtil.XSD_NS.getURI()); soapBody.addNamespaceDeclaration("xsi", JDOMNamespaceUtil.XSI_NS.getURI()); soapBody.addNamespaceDeclaration("itqlbean", this.getItqlEndpointURL()); SOAPElement eqts = soapBody.addChildElement("executeQueryToString", "itqlbean"); SOAPElement queryStr = eqts.addChildElement("queryString", "itqlbean"); queryStr.setAttributeNS(JDOMNamespaceUtil.XSI_NS.getURI(), "xsi:type", "xsd:string"); CDATASection queryCDATA = message.getSOAPPart().createCDATASection(query); queryStr.appendChild(queryCDATA); message.saveChanges(); // First create the connection SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance(); connection = soapConnFactory.createConnection(); reply = connection.call(message, this.getItqlEndpointURL()); if (reply.getSOAPBody().hasFault()) { reportSOAPFault(reply); if (log.isDebugEnabled()) { // log the full soap body response DOMBuilder builder = new DOMBuilder(); org.jdom2.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument()); log.debug(new XMLOutputter().outputString(jdomDoc)); } } else { NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*", "executeQueryToStringReturn"); if (nl.getLength() > 0) { result = nl.item(0).getFirstChild().getNodeValue(); } log.debug(result); } } catch (SOAPException e) { log.error("Failed to prepare or send iTQL via SOAP", e); throw new RuntimeException("Cannot query triple store at " + this.getItqlEndpointURL(), e); } finally { try { connection.close(); } catch (SOAPException e) { log.error("Failed to close SOAP connection", e); throw new RuntimeException( "Failed to close SOAP connection for triple store at " + this.getItqlEndpointURL(), e); } } return result; }
From source file:org.apache.axis2.saaj.SOAPConnectionTest.java
public void testClose() { try {//from w w w .j a v a 2s . c o m SOAPConnection sCon = SOAPConnectionFactory.newInstance().createConnection(); sCon.close(); } catch (SOAPException e) { fail("Unexpected Exception " + e); } }
From source file:org.apache.axis2.saaj.SOAPConnectionTest.java
public void testCloseTwice() { SOAPConnectionFactory soapConnectionFactory = null; try {//from w ww. j a va2s .co m soapConnectionFactory = SOAPConnectionFactory.newInstance(); } catch (SOAPException e) { fail("Unexpected Exception " + e); } SOAPConnection sCon = null; try { sCon = soapConnectionFactory.createConnection(); sCon.close(); } catch (SOAPException e) { fail("Unexpected Exception " + e); } try { sCon.close(); fail("Expected Exception did not occur"); } catch (SOAPException e) { assertTrue(true); } }
From source file:org.apache.axis2.saaj.SOAPConnectionTest.java
public void testCallOnCloseConnection() { SOAPConnectionFactory soapConnectionFactory = null; try {//from ww w . ja v a 2 s . c om soapConnectionFactory = SOAPConnectionFactory.newInstance(); } catch (SOAPException e) { fail("Unexpected Exception " + e); } SOAPConnection sCon = null; try { sCon = soapConnectionFactory.createConnection(); sCon.close(); } catch (SOAPException e) { fail("Unexpected Exception " + e); } try { sCon.call(null, new Object()); fail("Expected Exception did not occur"); } catch (SOAPException e) { assertTrue(true); } }
From source file:org.belio.service.gateway.SafcomGateway.java
private boolean sendMessage(QueueType queueType, Outbox outbox) { try {//from w w w . java2 s . c o m String now = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); MessageDigest md = MessageDigest.getInstance("MD5"); String serviceId = outbox.getServiceID(); String endpointDef = ""; // if (queueType.equals(QueueType.BULK)) { // endpointDef = networkproperties.getProperty("safcom_mt_endpoint"); // } else { endpointDef = networkproperties.getProperty("safcom_endpoint"); // } String code = outbox.getShortCode(); String spIdString = outbox.getSdpId(); String spPasswordString = createSpPass(spIdString, now, md); String recepient = "tel:" + outbox.getMsisdn(); String actualmessage = URLDecoder.decode(URLEncoder.encode(outbox.getText(), "UTF-8"), "UTF-8"); Launcher.LOG.info("T----------------------------------------J" + actualmessage); String gencorrelator = String.valueOf(outbox.getRefNo()); // Create SOAP Connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // Send SOAP Message to SOAP Server SOAPMessage messageToSend = getSoapMessageFromString(getMessage(spIdString, spPasswordString, recepient, serviceId, now, actualmessage, code, gencorrelator, endpointDef)); Calendar start = Calendar.getInstance(); SOAPMessage soapResponse = soapConnection.call(messageToSend, networkproperties.getProperty("safcom_sms")); Launcher.LOG.info( recepient + " - took " + (Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis())); // SOAPMessage soapResponse = null; System.out.println("XXXXXXXXXXXXXXXXXXX====Sending Safaricom message"); // printSOAPResponse(soapResponse);//TODO log SOAPBody body = soapResponse.getSOAPBody(); if (body.hasFault()) { SOAPFault newFault = body.getFault(); // QName fcode = newFault.getFaultCodeAsQName(); // String string = newFault.getFaultString(); // String actor = newFault.getFaultActor(); // System.out.println(">>>>>>>>>>>>>"+fcode); System.out.println(">>>>>>>>>>>>>" + newFault.getFaultString()); soapConnection.close(); return false; } else { //TO DO log soapConnection.close(); return true; } } catch (Exception ex) { Launcher.LOG.info(ex.getMessage()); } return false; }
From source file:org.cerberus.service.soap.impl.SoapService.java
@Override public AnswerItem<SOAPExecution> callSOAP(String envelope, String servicePath, String method, String attachmentUrl) {//from w w w .ja v a 2 s . c o m AnswerItem result = new AnswerItem(); SOAPExecution executionSOAP = new SOAPExecution(); ByteArrayOutputStream out = null; MessageEvent message = null; if (StringUtils.isNullOrEmpty(servicePath)) { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_SERVICEPATHMISSING); result.setResultMessage(message); return result; } if (StringUtils.isNullOrEmpty(method)) { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_METHODMISSING); result.setResultMessage(message); return result; } if (StringUtils.isNullOrEmpty(envelope)) { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP_ENVELOPEMISSING); result.setResultMessage(message); return result; } SOAPConnectionFactory soapConnectionFactory; SOAPConnection soapConnection = null; try { //Initialize SOAP Connection soapConnectionFactory = SOAPConnectionFactory.newInstance(); soapConnection = soapConnectionFactory.createConnection(); MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Connection opened"); // Create SOAP Request MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Create request"); SOAPMessage input = createSoapRequest(envelope, method); //Add attachment File if specified //TODO: this feature is not implemented yet therefore is always empty! if (!StringUtils.isNullOrEmpty(attachmentUrl)) { this.addAttachmentPart(input, attachmentUrl); } // Store the SOAP Call out = new ByteArrayOutputStream(); input.writeTo(out); MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS call : " + out.toString()); executionSOAP.setSOAPRequest(input); result.setItem(executionSOAP); // Call the WS MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Calling WS"); SOAPMessage soapResponse = soapConnection.call(input, servicePath); MyLogger.log(SoapService.class.getName(), Level.DEBUG, "Called WS"); out = new ByteArrayOutputStream(); // Store the response soapResponse.writeTo(out); MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS response received"); MyLogger.log(SoapService.class.getName(), Level.DEBUG, "WS response : " + out.toString()); executionSOAP.setSOAPResponse(soapResponse); message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSOAP); message.setDescription( message.getDescription().replace("%SERVICEPATH%", servicePath).replace("%SOAPMETHOD%", method)); result.setItem(executionSOAP); } catch (SOAPException | UnsupportedOperationException | IOException | SAXException | ParserConfigurationException | CerberusException e) { MyLogger.log(SoapService.class.getName(), Level.ERROR, e.toString()); message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP); message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath) .replace("%SOAPMETHOD%", method).replace("%DESCRIPTION%", e.getMessage())); result.setResultMessage(message); return result; } finally { try { if (soapConnection != null) { soapConnection.close(); } if (out != null) { out.close(); } } catch (SOAPException | IOException ex) { Logger.getLogger(SoapService.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } finally { result.setResultMessage(message); } } return result; }
From source file:org.energy_home.jemma.ah.internal.greenathome.GreenathomeAppliance.java
private void getPVForecast() { try {/* w ww . j a va2 s . c o m*/ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Calendar cal = new GregorianCalendar(); if (cal.get(Calendar.HOUR_OF_DAY) < 11) cal.add(Calendar.DAY_OF_MONTH, -1); String date = format.format(cal.getTime()); // Create SOAP Connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // Send SOAP Message to SOAP Server String url = "http://ws.i-em.eu/v4/iem.asmx"; SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(date), url); // Process the SOAP Response double[] val = getValuesFromSOAPResponse(soapResponse); if (val != null) { if (val.length > 0) forecast = new ArrayList<Double>(); for (int i = 0; i < val.length; i++) { if (Double.isNaN(val[i])) val[i] = 0; forecast.add(val[i]); } } forecast_debug += "---fsize: " + forecast.size(); soapConnection.close(); } catch (Exception e) { forecast_debug += "---EXCEPT: " + e.getMessage(); } }