public static String sendSOAP( EndpointReference soapEPR, String requestString, String action, String operation) throws Exception { ServiceClient sender = PmServiceClient.getServiceClient(); OperationClient operationClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); // creating message context MessageContext outMsgCtx = new MessageContext(); // assigning message context's option object into instance variable Options opts = outMsgCtx.getOptions(); // setting properties into option log.debug(soapEPR); opts.setTo(soapEPR); opts.setAction(action); opts.setTimeOutInMilliSeconds(180000); log.debug(requestString); SOAPEnvelope envelope = null; try { SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); envelope = fac.getDefaultEnvelope(); OMNamespace omNs = fac.createOMNamespace( "http://rpdr.partners.org/", //$NON-NLS-1$ "rpdr"); //$NON-NLS-1$ // creating the SOAP payload OMElement method = fac.createOMElement(operation, omNs); OMElement value = fac.createOMElement("RequestXmlString", omNs); // $NON-NLS-1$ value.setText(requestString); method.addChild(value); envelope.getBody().addChild(method); } catch (FactoryConfigurationError e) { log.error(e.getMessage()); throw new Exception(e); } outMsgCtx.setEnvelope(envelope); operationClient.addMessageContext(outMsgCtx); operationClient.execute(true); MessageContext inMsgtCtx = operationClient.getMessageContext("In"); // $NON-NLS-1$ SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); OMElement soapResponse = responseEnv.getBody().getFirstElement(); // System.out.println("Sresponse: "+ soapResponse.toString()); OMElement soapResult = soapResponse.getFirstElement(); // System.out.println("Sresult: "+ soapResult.toString()); String i2b2Response = soapResult.getText(); log.debug(i2b2Response); return i2b2Response; }
public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException { Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingSwA"); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); ServiceClient sender = new ServiceClient(); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); System.out.println("Sending file : " + fileName + " as SwA"); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = factory.getDefaultEnvelope(); OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns); OMElement request = factory.createOMElement("request", ns); OMElement imageId = factory.createOMElement("imageId", ns); imageId.setText(attachmentID); request.addChild(imageId); payload.addChild(request); env.getBody().addChild(payload); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); String imageContentId = body.getFirstChildWithName( new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse")) .getFirstChildWithName(new QName("http://services.samples/xsd", "response")) .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId")) .getText(); Attachments attachment = response.getAttachmentMap(); dataHandler = attachment.getDataHandler(imageContentId); File tempFile = File.createTempFile("swa-", ".gif"); FileOutputStream fos = new FileOutputStream(tempFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); System.out.println("Saved response to file : " + tempFile.getAbsolutePath()); return response; }
public static void transferFile(File file, String destinationFile) throws Exception { Options options = new Options(); options.setTo(targetEPR); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); // Increase the time out when sending large attachments options.setTimeOutInMilliSeconds(10000); options.setTo(targetEPR); options.setAction("urn:uploadFile"); // assume the use runs this sample at // <axis2home>/samples/soapwithattachments/ dir ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem( "../../repository", null); ServiceClient sender = new ServiceClient(configContext, null); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); FileDataSource fileDataSource = new FileDataSource(file); // Create a dataHandler using the fileDataSource. Any implementation of // javax.activation.DataSource interface can fit here. DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = fac.getDefaultEnvelope(); OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa"); OMElement uploadFile = fac.createOMElement("uploadFile", omNs); OMElement nameEle = fac.createOMElement("name", omNs); nameEle.setText(destinationFile); OMElement idEle = fac.createOMElement("attchmentID", omNs); idEle.setText(attachmentID); uploadFile.addChild(nameEle); uploadFile.addChild(idEle); env.getBody().addChild(uploadFile); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); OMElement element = body.getFirstElement() .getFirstChildWithName( new QName("http://service.soapwithattachments.sample", "return")); System.out.println(element.getText()); }
/** * Auto generated method signature * * @see com.pa.SecondFileService#getEmp * @param getEmp4 */ public com.pa.GetEmpResponse getEmp(com.pa.GetEmp getEmp4) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[1].getName()); _operationClient.getOptions().setAction("urn:getEmp"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient( _operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope( getFactory(_operationClient.getOptions().getSoapVersionURI()), getEmp4, optimizeContent(new javax.xml.namespace.QName("http://pa.com", "getEmp")), new javax.xml.namespace.QName("http://pa.com", "getEmp")); // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext( org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM( _returnEnv.getBody().getFirstElement(), com.pa.GetEmpResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.pa.GetEmpResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey( new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap.get( new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap.get( new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] {messageClass}); m.invoke(ex, new java.lang.Object[] {messageObject}); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } }
public CadConsultaCadastro2Stub.ConsultaCadastro2Result consultaCadastro2( final CadConsultaCadastro2Stub.NfeDadosMsg nfeDadosMsg, final CadConsultaCadastro2Stub.NfeCabecMsgE nfeCabecMsg) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { final org.apache.axis2.client.OperationClient _operationClient = this._serviceClient.createClient(this._operations[0].getName()); _operationClient .getOptions() .setAction( "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2/consultaCadastro2"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); this.addPropertyToOperationClient( _operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = this.toEnvelope( Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()), nfeDadosMsg, this.optimizeContent( new javax.xml.namespace.QName( "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "consultaCadastro2")), new javax.xml.namespace.QName( "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "consultaCadastro2")); env.build(); // add the children only if the parameter is not null if (nfeCabecMsg != null) { final org.apache.axiom.om.OMElement omElementnfeCabecMsg = this.toOM( nfeCabecMsg, this.optimizeContent( new javax.xml.namespace.QName( "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "consultaCadastro2"))); this.addHeader(omElementnfeCabecMsg, env); } // adding SOAP soap_headers this._serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); final org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext( org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); final java.lang.Object object = this.fromOM( _returnEnv.getBody().getFirstElement(), CadConsultaCadastro2Stub.ConsultaCadastro2Result.class, this.getEnvelopeNamespaces(_returnEnv)); return (CadConsultaCadastro2Stub.ConsultaCadastro2Result) object; } catch (final org.apache.axis2.AxisFault f) { final org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (this.faultExceptionNameMap.containsKey( new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "consultaCadastro2"))) { // make the fault by reflection try { final java.lang.String exceptionClassName = (java.lang.String) this.faultExceptionClassNameMap.get( new org.apache.axis2.client.FaultMapKey( faultElt.getQName(), "consultaCadastro2")); final Class<?> exceptionClass = java.lang.Class.forName(exceptionClassName); final Constructor<?> constructor = exceptionClass.getConstructor(String.class); final java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class final java.lang.String messageClassName = (java.lang.String) this.faultMessageMap.get( new org.apache.axis2.client.FaultMapKey( faultElt.getQName(), "consultaCadastro2")); final Class<?> messageClass = java.lang.Class.forName(messageClassName); final java.lang.Object messageObject = this.fromOM(faultElt, messageClass, null); final java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", messageClass); m.invoke(ex, messageObject); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (final ClassCastException | InstantiationException | IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } }
/** * This method creates 3 soap envelopes for 3 different client based sessions. Then it randomly * choose one envelope for each iteration and send it to the ESB. ESB should be configured with * session affinity load balancer and the SampleClientInitiatedSession dispatcher. This will * output request number, session number and the server ID for each iteration. So it can be * observed that one session number always associated with one server ID. */ private void sessionfullClient() { String synapsePort = "8280"; int iterations = 100; boolean infinite = true; String pPort = getProperty("port", synapsePort); String pIterations = getProperty("i", null); String addUrl = getProperty("addurl", null); String trpUrl = getProperty("trpurl", null); String prxUrl = getProperty("prxurl", null); String sleep = getProperty("sleep", null); String session = getProperty("session", null); long sleepTime = -1; if (sleep != null) { try { sleepTime = Long.parseLong(sleep); } catch (NumberFormatException ignored) { } } if (pPort != null) { try { Integer.parseInt(pPort); synapsePort = pPort; } catch (NumberFormatException e) { // run with default value } } if (pIterations != null) { try { iterations = Integer.parseInt(pIterations); if (iterations != -1) { infinite = false; } } catch (NumberFormatException e) { // run with default values } } Options options = new Options(); options.setTo( new EndpointReference("http://localhost:" + synapsePort + "/services/LBService1")); options.setAction("urn:sampleOperation"); options.setTimeOutInMilliSeconds(10000000); try { SOAPEnvelope env1 = buildSoapEnvelope("c1", "v1"); SOAPEnvelope env2 = buildSoapEnvelope("c2", "v1"); SOAPEnvelope env3 = buildSoapEnvelope("c3", "v1"); SOAPEnvelope[] envelopes = {env1, env2, env3}; ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null); ServiceClient client = new ServiceClient(configContext, null); // set addressing, transport and proxy url if (addUrl != null && !"null".equals(addUrl)) { client.engageModule("addressing"); options.setTo(new EndpointReference(addUrl)); } if (trpUrl != null && !"null".equals(trpUrl)) { options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl); } else { client.engageModule("addressing"); } if (prxUrl != null && !"null".equals(prxUrl)) { HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties(); try { URL url = new URL(prxUrl); proxyProperties.setProxyName(url.getHost()); proxyProperties.setProxyPort(url.getPort()); proxyProperties.setUserName(""); proxyProperties.setPassWord(""); proxyProperties.setDomain(""); options.setProperty(HTTPConstants.PROXY, proxyProperties); } catch (MalformedURLException e) { throw new AxisFault("Error creating proxy URL", e); } } client.setOptions(options); int i = 0; int sessionNumber = 0; String[] cookies = new String[3]; boolean httpSession = session != null && "http".equals(session); int cookieNumber = 0; while (i < iterations || infinite) { i++; if (sleepTime != -1) { try { Thread.sleep(sleepTime); } catch (InterruptedException ignored) { } } MessageContext messageContext = new MessageContext(); sessionNumber = getSessionTurn(envelopes.length); messageContext.setEnvelope(envelopes[sessionNumber]); cookieNumber = getSessionTurn(cookies.length); String cookie = cookies[cookieNumber]; if (httpSession) { setSessionID(messageContext, cookie); } try { OperationClient op = client.createClient(ServiceClient.ANON_OUT_IN_OP); op.addMessageContext(messageContext); op.execute(true); MessageContext responseContext = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); String receivedCookie = extractSessionID(responseContext); String receivedSetCookie = getSetCookieHeader(responseContext); if (httpSession) { if (receivedSetCookie != null && !"".equals(receivedSetCookie)) { cookies[cookieNumber] = receivedCookie; } } SOAPEnvelope responseEnvelope = responseContext.getEnvelope(); OMElement vElement = responseEnvelope.getBody().getFirstChildWithName(new QName("Value")); System.out.println( "Request: " + i + " with Session ID: " + (httpSession ? cookie : sessionNumber) + " ---- " + "Response : with " + (httpSession && receivedCookie != null ? (receivedSetCookie != null ? receivedSetCookie : receivedCookie) : " ") + " " + vElement.getText()); } catch (AxisFault axisFault) { System.out.println( "Request with session id " + (httpSession ? cookie : sessionNumber) + " " + "- Get a Fault : " + axisFault.getMessage()); } } } catch (AxisFault axisFault) { System.out.println(axisFault.getMessage()); } }
/* * (non-Javadoc) * @see org.apache.axis2.jaxws.core.controller.InvocationController#invoke(org.apache.axis2.jaxws.core.InvocationContext) */ public MessageContext doInvoke(MessageContext request) { // We need the qname of the operation being invoked to know which // AxisOperation the OperationClient should be based on. // Note that the OperationDesc is only set through use of the Proxy. Dispatch // clients do not use operations, so the operationDesc will be null. In this // case an anonymous AxisService with anoymouns AxisOperations for the supported // MEPs will be created; and it is that anonymous operation name which needs to // be specified QName operationName = getOperationNameToUse(request, ServiceClient.ANON_OUT_IN_OP); // TODO: Will the ServiceClient stick around on the InvocationContext // or will we need some other mechanism of creating this? // Try to create an OperationClient from the passed in ServiceClient InvocationContext ic = request.getInvocationContext(); ServiceClient svcClient = ic.getServiceClient(); OperationClient opClient = createOperationClient(svcClient, operationName); initOperationClient(opClient, request); // Setup the client so that it knows whether the underlying call to // Axis2 knows whether or not to start a listening port for an // asynchronous response. Boolean useAsyncMep = (Boolean) request.getProperty(Constants.USE_ASYNC_MEP); if ((useAsyncMep != null && useAsyncMep.booleanValue()) || opClient.getOptions().isUseSeparateListener()) { configureAsyncListener(opClient); } else { if (log.isDebugEnabled()) { log.debug( "Asynchronous message exchange not enabled. The invocation will be synchronous."); } } org.apache.axis2.context.MessageContext axisRequestMsgCtx = request.getAxisMessageContext(); org.apache.axis2.context.MessageContext axisResponseMsgCtx = null; MessageContext response = null; AxisFault faultexception = null; // don't let the keyword "fault" confuse you. This is an exception class. try { execute(opClient, true, axisRequestMsgCtx); } catch (AxisFault af) { // If an AxisFault was thrown, we need to cleanup the original OperationContext. // Failure to do so results in a memory leak. opClient.getOperationContext().cleanup(); // save the fault in case it didn't come from the endpoint, and thus // there would be no message on the MessageContext faultexception = af; if (log.isDebugEnabled()) { log.debug( axisRequestMsgCtx.getLogIDString() + " AxisFault received from client: " + af.getMessage()); } } try { // Collect the response MessageContext and envelope axisResponseMsgCtx = opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); response = new MessageContext(axisResponseMsgCtx); response.setMEPContext(request.getMEPContext()); // If the Message object is still null, then it's possible that a // local AxisFault was thrown and we need to save it for later throwing // We do not want to create a message and go through the whole handler or // XMLFault processing because it's unnecessary. // // Same is true if we get a valid non-fault server response but some jaxws // client processing (a handler, perhaps) throws an exception. // // If the response message itself is a fault message, let it pass through. if ((faultexception != null) && ((response.getMessage() == null) || (!response.getMessage().isFault()))) { MessageFactory factory = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class); Message message = factory.create(request.getMessage().getProtocol()); response.setLocalException(faultexception); response.setMessage(message); } // This assumes that we are on the ultimate execution thread ThreadContextMigratorUtil.performMigrationToThread( Constants.THREAD_CONTEXT_MIGRATOR_LIST_ID, axisResponseMsgCtx); } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } return response; }