Java Code Examples for org.apache.axis2.context.MessageContext#setEnvelope()

The following examples show how to use org.apache.axis2.context.MessageContext#setEnvelope() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EventBrokerUtils.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static MessageContext createMessageContext(OMElement payload,
                                                  OMElement topic,
                                                  int tenantId) throws EventBrokerException {
    MessageContext mc = new MessageContext();
    mc.setConfigurationContext(new ConfigurationContext(new AxisConfiguration()));
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
    SOAPFactory soapFactory = new SOAP12Factory();
    SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(payload);
    if (topic != null) {
        envelope.getHeader().addChild(topic);
    }
    try {
        mc.setEnvelope(envelope);
    } catch (Exception e) {

        throw new EventBrokerException("Unable to generate event.", e);
    }
    return mc;
}
 
Example 2
Source File: CarbonEventingMessageReceiver.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatch the message to the target endpoint
 *
 * @param soapEnvelope   Soap Enevlop with message
 * @param responseAction WSE action for the response
 * @param mc             Message Context
 * @param isFault        Whether a Fault message must be sent
 * @throws AxisFault Thrown by the axis2 engine.
 */
private void dispatchResponse(SOAPEnvelope soapEnvelope, String responseAction,
                              MessageContext mc, boolean isFault) throws AxisFault {
    MessageContext rmc = MessageContextBuilder.createOutMessageContext(mc);
    rmc.getOperationContext().addMessageContext(rmc);
    replicateState(mc);
    rmc.setEnvelope(soapEnvelope);
    rmc.setWSAAction(responseAction);
    rmc.setSoapAction(responseAction);
    if (isFault) {
        AxisEngine.sendFault(rmc);
    } else {
        AxisEngine.send(rmc);
    }
}
 
Example 3
Source File: PublishOnlyMessageReceiver.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatch the message to the target endpoint
 *
 * @param soapEnvelope   Soap Enevlop with message
 * @param responseAction WSE action for the response
 * @param mc             Message Context
 * @param isFault        Whether a Fault message must be sent
 * @throws AxisFault Thrown by the axis2 engine.
 */
private void dispatchResponse(SOAPEnvelope soapEnvelope, String responseAction,
                              MessageContext mc, boolean isFault) throws AxisFault {
    MessageContext rmc = MessageContextBuilder.createOutMessageContext(mc);
    rmc.getOperationContext().addMessageContext(rmc);
    replicateState(mc);
    rmc.setEnvelope(soapEnvelope);
    rmc.setWSAAction(responseAction);
    rmc.setSoapAction(responseAction);
    if (isFault) {
        AxisEngine.sendFault(rmc);
    } else {
        AxisEngine.send(rmc);
    }
}
 
Example 4
Source File: CommandBuilderTestUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static MessageContext getMCWithSOAP11Envelope() throws AxisFault {
    MessageContext messageContext = new MessageContext();
    SOAPFactory factory = new SOAP11Factory();
    SOAPEnvelope envelope = factory.createSOAPEnvelope();
    messageContext.setEnvelope(envelope);
    return messageContext;
}
 
Example 5
Source File: CommandBuilderTestUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static MessageContext getMCWithSOAP12Envelope() throws AxisFault {
    MessageContext messageContext = new MessageContext();
    SOAPFactory factory = new SOAP12Factory();
    SOAPEnvelope envelope = factory.createSOAPEnvelope();
    messageContext.setEnvelope(envelope);
    return messageContext;
}
 
Example 6
Source File: LoadBalanceSessionFullClient.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
private List<ResponseData> makeRequest(String session, int iterations, long sleepTime, SOAPEnvelope[] envelopes,
                                       ServiceClient client) throws AxisFault {
    List<ResponseData> responseList = new ArrayList<ResponseData>();

    int i = 0;
    int sessionNumber;
    String[] cookies = new String[3];
    boolean httpSession = session != null && "http".equals(session);
    int cookieNumber;

    while (i < iterations) {

        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"));
            if (log.isDebugEnabled()) {
                log.debug("Request: " + i + " with Session ID: " + (httpSession ? cookie : sessionNumber) + " ---- "
                                  + "Response : with  " + (httpSession && receivedCookie != null ?
                        (receivedSetCookie != null ? receivedSetCookie : receivedCookie) :
                        " ") + " " + vElement.getText());
            }

            responseList
                    .add(new ResponseData(true, "" + (httpSession ? cookie : sessionNumber), vElement.getText()));

        } catch (AxisFault axisFault) {
            if (log.isDebugEnabled()) {
                log.debug("Request with session id " + (httpSession ? cookie : sessionNumber), axisFault);
            }

            responseList.add(new ResponseData(false, "" + (httpSession ? cookie : sessionNumber),
                                              axisFault.getMessage()));
        }
    }

    return responseList;
}
 
Example 7
Source File: MTOMSwAClient.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
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 = createServiceClient();
        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", "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", "uploadFileUsingSwAResponse")).
                getFirstChildWithName(new QName("http://services.samples", "response")).
                getFirstChildWithName(new QName("http://services.samples", "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;
    }
 
Example 8
Source File: MTOMSwAClient.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
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 = createServiceClient();
        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", "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", "uploadFileUsingSwAResponse")).
                getFirstChildWithName(new QName("http://services.samples", "response")).
                getFirstChildWithName(new QName("http://services.samples", "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;
    }
 
Example 9
Source File: DBInOutMessageReceiver.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Invokes the business logic invocation on the service implementation class
 * 
 * @param msgContext
 *            the incoming message context
 * @param newMsgContext
 *            the response message context
 * @throws AxisFault
 *             on invalid method (wrong signature) or behavior (return null)
 */
public void invokeBusinessLogic(MessageContext msgContext,
		MessageContext newMsgContext) throws AxisFault {
	try {
		if (log.isDebugEnabled()) {
			log.debug("Request received to DSS:  Data Service - " + msgContext.getServiceContext().getName() +
			          ", Operation - " + msgContext.getSoapAction() + ", Request body - " +
			          msgContext.getEnvelope().getText() + ", ThreadID - " + Thread.currentThread().getId());
		}
		boolean isAcceptJson = false;
		Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
		if (transportHeaders != null) {
			String acceptHeader = (String) transportHeaders.get(HTTPConstants.HEADER_ACCEPT);
			if (acceptHeader != null) {
				int index = acceptHeader.indexOf(";");
				if (index > 0) {
					acceptHeader = acceptHeader.substring(0, index);
				}
				String[] strings = acceptHeader.split(",");
				for (String string : strings) {
					String accept = string.trim();
					AxisConfiguration configuration = msgContext.getConfigurationContext().getAxisConfiguration();
					if (HTTPConstants.MEDIA_TYPE_APPLICATION_JSON.equals(accept)
							&& configuration.getMessageFormatter(accept) != null) {
						isAcceptJson = true;
						break;
					}
				}
			}
		}
		OMElement result = DataServiceProcessor.dispatch(msgContext);
		SOAPFactory fac = getSOAPFactory(msgContext);
		SOAPEnvelope envelope = fac.getDefaultEnvelope();
		if (result != null) {
			envelope.getBody().addChild(result);
		}
		newMsgContext.setEnvelope(envelope);
		if (isAcceptJson) {
			newMsgContext.setProperty(Constants.Configuration.MESSAGE_TYPE,
					HTTPConstants.MEDIA_TYPE_APPLICATION_JSON);
		}
	} catch (Exception e) {
		log.error("Error in in-out message receiver", e);
		msgContext.setProperty(Constants.FAULT_NAME, DBConstants.DS_FAULT_NAME);
		throw DBUtils.createAxisFault(e);
	} finally {
		if (log.isDebugEnabled()) {
			String response;
			if (msgContext.getProperty(Constants.FAULT_NAME) != null &&
			    msgContext.getProperty(Constants.FAULT_NAME).equals(DBConstants.DS_FAULT_NAME)) {
				response = "Error in Response";
			} else {
				response = newMsgContext.getEnvelope().getText();
			}
			log.debug("Response send from DSS:  Data Service - " + msgContext.getServiceContext().getName() +
			          ", Operation - " + msgContext.getSoapAction() + ", Response body - " + response +
			          ", ThreadID - " + Thread.currentThread().getId());
		}
	}
}
 
Example 10
Source File: LoadBalanceSessionFullClient.java    From product-ei with Apache License 2.0 4 votes vote down vote up
private List<ResponseData> makeRequest(String session, int iterations, long sleepTime, SOAPEnvelope[] envelopes,
                                       ServiceClient client) throws AxisFault {
    List<ResponseData> responseList = new ArrayList<ResponseData>();

    int i = 0;
    int sessionNumber;
    String[] cookies = new String[3];
    boolean httpSession = session != null && "http".equals(session);
    int cookieNumber;

    while (i < iterations) {

        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"));
            if (log.isDebugEnabled()) {
                log.debug(
                    "Request: " + i + " with Session ID: " + (httpSession ? cookie : sessionNumber) + " ---- " +
                    "Response : with  " + (httpSession && receivedCookie != null ?
                                           (receivedSetCookie != null ? receivedSetCookie : receivedCookie) :
                                           " ") + " " + vElement.getText());
            }

            responseList
                .add(new ResponseData(true, "" + (httpSession ? cookie : sessionNumber), vElement.getText()));

        } catch (AxisFault axisFault) {
            if (log.isDebugEnabled()) {
                log.debug("Request with session id " + (httpSession ? cookie : sessionNumber), axisFault);
            }

            responseList.add(
                new ResponseData(false, "" + (httpSession ? cookie : sessionNumber), axisFault.getMessage()));
        }
    }

    return responseList;
}
 
Example 11
Source File: MTOMSwAClient.java    From product-ei with Apache License 2.0 4 votes vote down vote up
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 = createServiceClient();
        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", "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", "uploadFileUsingSwAResponse")).
                getFirstChildWithName(new QName("http://services.samples", "response")).
                getFirstChildWithName(new QName("http://services.samples", "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;
    }