org.apache.axis2.wsdl.WSDLConstants Java Examples

The following examples show how to use org.apache.axis2.wsdl.WSDLConstants. 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: CBServiceClient.java    From garoon-google with MIT License 5 votes vote down vote up
public Integer getApiVersion() throws Exception {
	String header = this.serviceClient.getLastOperationContext()
		.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope().getHeader().toString();

	InputStream stream = new ByteArrayInputStream(header.toString().getBytes());
	Document document= DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);
	NodeList nodes = document.getElementsByTagName("apiversion");
	String apiVersion = nodes.item(0).getTextContent();

	// 特定バージョン以降で分岐させたいのでif文で使える形式で返す
	String apiNumber = apiVersion.replace(".", "");
	return Integer.parseInt(apiNumber);
}
 
Example #2
Source File: TopicMapService.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
public void setOutputType(String outputType){
    if(outputType!=null){
        try{
            MessageContext outMsgCtx = MessageContext.getCurrentMessageContext().getOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            outMsgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE, outputType);
        }catch(Exception e){e.printStackTrace();}
    }
}
 
Example #3
Source File: ProxyMessageReceiver.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private SOAPEnvelope getResponseEnvelope(ServiceClient client) throws AxisFault {
    OperationContext operationContext = client.getLastOperationContext();
    MessageContext messageContext =
            operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    if (messageContext != null) {
        return messageContext.getEnvelope();
    }
    return null;
}
 
Example #4
Source File: ParallelRequestHelper.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to send begin boxcar request and return the session
 *
 * @return cookie
 * @throws org.apache.axis2.AxisFault
 */
public String beginBoxcarReturningSession() throws AxisFault {
    sender.sendReceive(payload);
    MessageContext msgCtx = sender.getLastOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

    CommonsTransportHeaders commonsTransportHeaders = (CommonsTransportHeaders) msgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String cookie = (String) commonsTransportHeaders.get("Set-Cookie");
    return cookie;
}
 
Example #5
Source File: DataServiceDocLitWrappedSchemaGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Process the given request's output types.
 * @param cparams The common parameters used in the schema generator
 * @param request The request used to process the output
 */
private static void processRequestOutput(CommonParams cparams, CallableRequest request)
           throws DataServiceFault {
	CallQuery callQuery = request.getCallQuery();
	if (!(callQuery.getQuery().hasResult() || request.isReturnRequestStatus())) {
		return;
	}
	
	AxisOperation axisOp = cparams.getAxisService().getOperation(
			new QName(request.getRequestName()));
	AxisMessage outMessage = axisOp.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
	outMessage.setName(request.getRequestName() + Java2WSDLConstants.RESPONSE);
	
	if (request.isReturnRequestStatus() && !callQuery.getQuery().hasResult()) {
		outMessage.setElementQName(new QName(DBConstants.WSO2_DS_NAMESPACE,
				DBConstants.REQUEST_STATUS_WRAPPER_ELEMENT));
		return;
	}
	
	Result result = callQuery.getQuery().getResult();
	if (result.isXsAny() || result.getResultType() == ResultTypes.RDF) {
		outMessage.setElementQName(new QName(DBConstants.WSO2_DS_NAMESPACE,
				DBConstants.DATA_SERVICE_RESPONSE_WRAPPER_ELEMENT));
		return;
	}
	
	/* create dummy element to contain the result element */
	XmlSchemaElement dummyParentElement = new XmlSchemaElement();
	dummyParentElement.setQName(new QName(result.getNamespace(), DUMMY_NAME));
	XmlSchema dummySchema = retrieveSchema(cparams, result.getNamespace());
	XmlSchemaComplexType dummyType = new XmlSchemaComplexType(dummySchema);
	dummyType.setName(DUMMY_NAME);
	dummyParentElement.setType(dummyType);
	/* lets do it */
	processCallQuery(cparams, dummyParentElement, callQuery);
	/* extract the element and set it to the message */
	XmlSchemaElement resultEl = (XmlSchemaElement) ((XmlSchemaSequence) dummyType.getParticle())
			.getItems().getItem(0);
	outMessage.setElementQName(resultEl.getRefName());
}
 
Example #6
Source File: ParallelRequestHelper.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to send begin boxcar request and return the session
 *
 * @return cookie
 * @throws org.apache.axis2.AxisFault
 */
public String beginBoxcarReturningSession() throws AxisFault {
    sender.sendReceive(payload);
    MessageContext msgCtx = sender.getLastOperationContext()
            .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

    CommonsTransportHeaders commonsTransportHeaders = (CommonsTransportHeaders) msgCtx
            .getProperty(MessageContext.TRANSPORT_HEADERS);
    String cookie = (String) commonsTransportHeaders.get("Set-Cookie");
    return cookie;
}
 
Example #7
Source File: DataServiceDocLitWrappedSchemaGenerator.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Process the given request's input parameters.
 * @param cparams The common parameters used in the schema generator
 * @param request The request used to process the input
 */
private static void processRequestInput(CommonParams cparams, CallableRequest request)
           throws DataServiceFault {
	String requestName = request.getRequestName(); 
	AxisOperation axisOp = cparams.getAxisService().getOperation(new QName(requestName));
	CallQuery callQuery = request.getCallQuery();
	Query query = callQuery.getQuery();
	boolean optional = false;
	AxisMessage inMessage = axisOp.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
	if (inMessage != null) {
               inMessage.setName(requestName + Java2WSDLConstants.MESSAGE_SUFFIX);
               /* create input message element */
               XmlSchemaElement inputElement = createElement(cparams, query.getInputNamespace(),
                       requestName, true);
               /* complex type for input message element */
               XmlSchemaComplexType inputComplexType = createComplexType(cparams,
                       query.getInputNamespace(), requestName, false);
               /* set element type */
               inputElement.setType(inputComplexType);
               /* batch requests */
               if (request.isBatchRequest()) {
                   XmlSchemaElement nestedEl = new XmlSchemaElement();
                   CallableRequest parentReq = request.getParentRequest();
                   if (parentReq != null) {
                       nestedEl.setRefName(cparams.getRequestInputElementMap().get(
                               parentReq.getRequestName()));
                       nestedEl.setMaxOccurs(Long.MAX_VALUE);
                       addElementToComplexTypeSequence(cparams, inputComplexType,
                               query.getInputNamespace(),
                               nestedEl, false, false, false);
                   } else {
                       throw new DataServiceFault("No parent operation for batch request: "
                               + request.getRequestName());
                   }
               } else {
                   /* normal requests */
                   XmlSchemaElement tmpEl;
                   Map<String, WithParam> withParams = callQuery.getWithParams();
                   WithParam tmpWithParam;
                   /* create elements for individual parameters */
                   if (callQuery.getWithParams().size() > 0) {
                       for (QueryParam queryParam : query.getQueryParams()) {
                           if (DBConstants.QueryTypes.IN.equals(queryParam.getType())
                                   || DBConstants.QueryTypes.INOUT.equals(queryParam.getType())) {
                               tmpWithParam = withParams.get(queryParam.getName());
                               if (tmpWithParam == null) {
                                   /* this query param's value must be coming from an export, not
                                    * from the operation's parameter */
                                   continue;
                               }
                               tmpEl = createInputEntryElement(cparams, query, queryParam,
                                       tmpWithParam);
                               /* checking if query is SQL update query and for optional parameters*/
                               optional = callQuery.getQuery() instanceof SQLQuery
                                       && ((SQLQuery) query).getSqlQueryType() == SQLQuery.QueryType.UPDATE
                                       && queryParam.isOptional();
                               /* add to input element complex type */
                               addElementToComplexTypeSequence(cparams, inputComplexType, query.getInputNamespace(),
                                    tmpEl, false, false, optional);
                           }
                       }
                   } else {
                       /* Adds the operation name to the SOAP body when used with OUT_ONLY requests
                        * and further creates a complex type corresponds to the IN-MESSAGE with
                        * an empty sequence */
                       XmlSchemaSequence emptySeq = new XmlSchemaSequence();
                       inputComplexType.setParticle(emptySeq);
                   }
               }
               /* set the input element qname in message */
               inMessage.setElementQName(inputElement.getQName());
               /* store request name and element qname mapping */
               cparams.getRequestInputElementMap().put(request.getRequestName(),
                       inMessage.getElementQName());

           }
}
 
Example #8
Source File: DataServiceDocLitWrappedSchemaGenerator.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
     * Process the given request's input parameters. //todo complete
     * @param cparams The common parameters used in the schema generator
     * @param request The request used to process the input
     */
    private static void processRequestBoxInput(CommonParams cparams, CallableRequest request, List<List<CallableRequest>> allOps)
            throws DataServiceFault {
        String requestName = request.getRequestName();
        AxisOperation axisOp = cparams.getAxisService().getOperation(new QName(requestName));
        CallQuery callQuery = request.getCallQuery();
        Query query = callQuery.getQuery();
        AxisMessage inMessage = axisOp.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMessage != null) {
            inMessage.setName(requestName + Java2WSDLConstants.MESSAGE_SUFFIX);
                /* create input message element */
            XmlSchemaElement inputElement = createElement(cparams, query.getInputNamespace(),
                                                          requestName, true);
                /* complex type for input message element */
            XmlSchemaComplexType inputComplexType = createComplexType(cparams,
                                                                      query.getInputNamespace(), requestName, false);
                /* set element type */
            inputElement.setType(inputComplexType);
                /* batch requests */
            for (List<CallableRequest> callableRequests : allOps) {
                for (CallableRequest callableRequest : callableRequests) {
                    XmlSchemaElement nestedEl = new XmlSchemaElement();
                    if (callableRequest != null) {
                        if (!isBoxcarringOp(callableRequest.getRequestName())) {
                            nestedEl.setRefName(cparams.getRequestInputElementMap().get(
                                    callableRequest.getRequestName()));
//                            nestedEl.setMaxOccurs(Long.MAX_VALUE);
                            addElementToComplexTypeAll(cparams, inputComplexType,
                                                       query.getInputNamespace(),
                                                       nestedEl, false, false, true);
                        }
                    } else {
                        throw new DataServiceFault("No parent operation for batch request: "
                                                   + request.getRequestName());
                    }
                }
            }
                /* set the input element qname in message */
            inMessage.setElementQName(inputElement.getQName());
                /* store request name and element qname mapping */
            cparams.getRequestInputElementMap().put(request.getRequestName(),
                                                    inMessage.getElementQName());

        }
    }
 
Example #9
Source File: DataServiceDocLitWrappedSchemaGenerator.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Process the given request's output types.
 * @param cparams The common parameters used in the schema generator
 * @param request The request used to process the output
 */
private static void processRequestBoxOutput(CommonParams cparams, CallableRequest request,
		List<List<CallableRequest>> allOps) throws DataServiceFault {
	AxisOperation axisOp = cparams.getAxisService().getOperation(new QName(request.getRequestName()));
	AxisMessage outMessage = axisOp.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
	outMessage.setName(request.getRequestName() + Java2WSDLConstants.RESPONSE);

	XmlSchemaElement parentElement = createElement(cparams, request.getCallQuery().getNamespace() , DBConstants.DATA_SERVICE_REQUEST_BOX_RESPONSE_WRAPPER_ELEMENT,true);
	XmlSchemaComplexType outputComplexType = createComplexType(cparams,
			request.getCallQuery().getQuery().getInputNamespace(), request.getRequestName(), false);
	parentElement.setType(outputComplexType);
	for (List<CallableRequest> callableRequests : allOps) {
		for (CallableRequest callableRequest : callableRequests) {
			if (callableRequest != null) {
				CallQuery callQuery = callableRequest.getCallQuery();
                   Result result = callQuery.getQuery().getResult();
                   if (!isBoxcarringOp(callableRequest.getRequestName()) && result != null) {
					Query query = callQuery.getQuery();
					XmlSchemaElement dummyParentElement = new XmlSchemaElement();
					dummyParentElement.setQName(new QName(result.getNamespace(), DUMMY_NAME));
					XmlSchema dummySchema = retrieveSchema(cparams, result.getNamespace());
					XmlSchemaComplexType dummyType = new XmlSchemaComplexType(dummySchema);
					dummyType.setName(DUMMY_NAME);
					dummyParentElement.setType(dummyType);
					/* lets do it */
					processCallQuery(cparams, dummyParentElement, callQuery);
                    /* extract the element and set it to the message */
					XmlSchemaElement resultEl = (XmlSchemaElement) ((XmlSchemaSequence) dummyType.getParticle())
							.getItems().getItem(0);
					addElementToComplexTypeAll(cparams, outputComplexType, query.getInputNamespace(), resultEl,
							false, false, true);
				}
			} else {
				throw new DataServiceFault("No parent operation for batch request: " + request.getRequestName());
			}
		}
	}

	/* create dummy element to contain the result element */
	outMessage.setElementQName(parentElement.getQName());
}
 
Example #10
Source File: DBDeployer.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method for creating AxisOperation objects.
 */
private AxisOperation createAxisOperation(String operationName, String httpLocation,
		String method, boolean hasResult,
		AxisBinding soap11Binding, AxisBinding soap12Binding, AxisBinding httpBinding,
		String description) {
	AxisOperation axisOperation;
	if (hasResult) {
		axisOperation = new InOutAxisOperation(new QName(operationName));
		DBInOutMessageReceiver inoutMsgReceiver = new DBInOutMessageReceiver();
		axisOperation.setMessageReceiver(inoutMsgReceiver);
		axisOperation.setMessageExchangePattern(WSDL2Constants.MEP_URI_IN_OUT);
	} else {
		axisOperation = new InOnlyAxisOperation(new QName(operationName));
		DBInOnlyMessageReceiver inonlyMsgReceiver = new DBInOnlyMessageReceiver();
		axisOperation.setMessageReceiver(inonlyMsgReceiver);
		axisOperation.setMessageExchangePattern(WSDL2Constants.MEP_URI_ROBUST_IN_ONLY);
	}

	axisOperation.setStyle(WSDLConstants.STYLE_DOC);

	String opName = axisOperation.getName().getLocalPart();
	// Create a default SOAP 1.1 Binding operation
	AxisBindingOperation soap11BindingOperation = createDefaultSOAP11BindingOperation(
			axisOperation, httpLocation, "urn:" + opName, soap11Binding);

	// Create a default SOAP 1.2 Binding operation
	AxisBindingOperation soap12BindingOperation = createDefaultSOAP12BindingOperation(
			axisOperation, httpLocation, "urn:" + opName, soap12Binding);

	// Create a default HTTP Binding operation
	AxisBindingOperation httpBindingOperation = createDefaultHTTPBindingOperation(
			axisOperation, httpLocation, method, httpBinding);

       if(httpLocation.startsWith("/")){
           httpLocation = httpLocation.substring(1);
       }

       Pattern httpLocationPattern = WSDLUtil.getConstantFromHTTPLocationForResource(httpLocation, method);
       this.httpLocationTableForResource.put(httpLocationPattern, axisOperation);

	// Create the in and out axis messages for this operation
	AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
	if (inMessage != null) {
		inMessage.setName(operationName + Java2WSDLConstants.MESSAGE_SUFFIX);
		createAxisBindingMessage(soap11BindingOperation, inMessage,
                   WSDLConstants.MESSAGE_LABEL_IN_VALUE, false);
		createAxisBindingMessage(soap12BindingOperation, inMessage,
                   WSDLConstants.MESSAGE_LABEL_IN_VALUE, false);
		createAxisBindingMessage(httpBindingOperation, inMessage,
                   WSDLConstants.MESSAGE_LABEL_IN_VALUE, false);
	}

	if (axisOperation instanceof InOutAxisOperation) {
		AxisMessage outMessage =
                   axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
		if (outMessage != null) {
			outMessage.setName(operationName + Java2WSDLConstants.RESPONSE_MESSAGE);
			createAxisBindingMessage(soap11BindingOperation, outMessage,
                       WSDLConstants.MESSAGE_LABEL_OUT_VALUE, false);
			createAxisBindingMessage(soap12BindingOperation, outMessage,
                       WSDLConstants.MESSAGE_LABEL_OUT_VALUE, false);
			createAxisBindingMessage(httpBindingOperation, outMessage,
                       WSDLConstants.MESSAGE_LABEL_OUT_VALUE, false);
		}
	}
	/* Set the fault message, only if operation returns a result*/
	if (hasResult) {
		AxisMessage faultMessage = new AxisMessage();
		faultMessage.setName(DBConstants.DS_FAULT_ELEMENT);
		faultMessage.setElementQName(new QName(DBConstants.WSO2_DS_NAMESPACE,
                DBConstants.DS_FAULT_ELEMENT));
		axisOperation.setFaultMessages(faultMessage);
		createAxisBindingMessage(soap11BindingOperation, faultMessage,
                WSDLConstants.MESSAGE_LABEL_FAULT_VALUE, true);
		createAxisBindingMessage(soap12BindingOperation, faultMessage,
                WSDLConstants.MESSAGE_LABEL_FAULT_VALUE, true);
		createAxisBindingMessage(httpBindingOperation, faultMessage,
                WSDLConstants.MESSAGE_LABEL_FAULT_VALUE, true);
	}

	axisOperation.setDocumentation(description);
	return axisOperation;
}
 
Example #11
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 #12
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 #13
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 #14
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;
    }
 
Example #15
Source File: XdsRaw.java    From openxds with Apache License 2.0 4 votes vote down vote up
public void setOperationContext(OperationContext opCtx)
throws AxisFault {
	inMesasgeContext = opCtx.getMessageContext(
			WSDLConstants.MESSAGE_LABEL_IN_VALUE);
}
 
Example #16
Source File: Xds.java    From openxds with Apache License 2.0 4 votes vote down vote up
public void setOperationContext(OperationContext opCtx)
throws AxisFault {
	inMesasgeContext = opCtx.getMessageContext(
			WSDLConstants.MESSAGE_LABEL_IN_VALUE);
}
 
Example #17
Source File: APIKeyValidationServiceTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Before
public void Init() throws Exception {

    System.setProperty(CARBON_HOME, "");
    privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    metricService = Mockito.mock(MetricService.class);
    org.wso2.carbon.metrics.manager.ServiceReferenceHolder serviceReferenceHolder1 = Mockito
            .mock(org.wso2.carbon.metrics.manager.ServiceReferenceHolder.class);
    Timer timer = Mockito.mock(Timer.class);
    Timer.Context timerContext = Mockito.mock(Timer.Context.class);
    MessageContext messageContext = Mockito.mock(MessageContext.class);
    OperationContext operationContext = Mockito.mock(OperationContext.class);
    MessageContext responseMessageContext = Mockito.mock(MessageContext.class);

    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(org.wso2.carbon.metrics.manager.ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIKeyMgtUtil.class);
    PowerMockito.mockStatic(MessageContext.class);
    PowerMockito.mockStatic(APIKeyMgtDataHolder.class);

    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.when(privilegedCarbonContext.getUsername()).thenReturn(USER_NAME);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(MessageContext.getCurrentMessageContext()).thenReturn(messageContext);
    PowerMockito.when(APIKeyMgtDataHolder.isJwtGenerationEnabled()).thenReturn(true);

    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService())
            .thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_MANGER_VALIDATIONHANDLER_CLASS_NAME))
            .thenReturn(API_KEY_MANGER_VALIDATION_HANDLER_CLASS_NAME);
    Mockito.when(org.wso2.carbon.metrics.manager.ServiceReferenceHolder.getInstance())
            .thenReturn(serviceReferenceHolder1);
    Mockito.when(serviceReferenceHolder1.getMetricService()).thenReturn(metricService);
    Mockito.when(timer.start()).thenReturn(timerContext);
    Mockito.when(metricService.timer(Mockito.anyString(), Mockito.any(org.wso2.carbon.metrics.manager.Level.class)))
            .thenReturn(timer);

    Mockito.when(messageContext.getOperationContext()).thenReturn(operationContext);
    Mockito.when(operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE))
            .thenReturn(responseMessageContext);
    Map headers = new HashMap();
    headers.put("activityID", "1s2f2g4g5");
    Mockito.when(messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(headers);

    String cacheKey = APIUtil.getAccessTokenCacheKey(ACCESS_TOKEN, API_CONTEXT, API_VERSION, "/*", "GET",
            REQUIRED_AUTHENTICATION_LEVEL);
    org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO infoDTO =
            new org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO();
    infoDTO.setApiPublisher(USER_NAME);
    infoDTO.setEndUserName(USER_NAME);
    PowerMockito.when(APIKeyMgtUtil.getFromKeyManagerCache(cacheKey)).thenReturn(infoDTO);

}
 
Example #18
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;
    }