Java Code Examples for org.apache.axis2.context.MessageContext

The following examples show how to use org.apache.axis2.context.MessageContext. These examples are extracted from open source projects. 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 Project: openxds   Source File: SubmitObjectsRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Audit Logging of Register Document Set message.
 */
private void auditLog(String patientId, String submissionSetUid, AuditCodeMappings.AuditTypeCodes typeCode) {
	if (auditLog == null)
		return;
	String replyto = getMessageContext().getReplyTo().getAddress();
	String remoteIP = (String)getMessageContext().getProperty(MessageContext.REMOTE_ADDR);
	String localIP = (String)getMessageContext().getProperty(MessageContext.TRANSPORT_ADDR);
	
	ParticipantObject set = new ParticipantObject("SubmissionSet", submissionSetUid);
	ParticipantObject patientObj = new ParticipantObject("PatientIdentifier", patientId);
	
	ActiveParticipant source = new ActiveParticipant();
	source.setUserId(replyto);
	source.setAccessPointId(remoteIP);
	//TODO: Needs to be improved
	String userid = "http://"+connection.getHostname()+":"+connection.getPort()+"/axis2/services/xdsregistryb"; 
	ActiveParticipant dest = new ActiveParticipant();
	dest.setUserId(userid);
	// the Alternative User ID should be set to our Process ID, see
	// section TF-2b section 3.42.7.1.2
	dest.setAltUserId(PidHelper.getPid());
	
	dest.setAccessPointId(localIP);
	auditLog.logDocumentImport(source, dest, patientObj, set, typeCode);		
}
 
Example 2
Source Project: carbon-apimgt   Source File: GatewayUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method handles threat violations. If the request propagates a threat, this method generates
 * an custom exception.
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @param errorCode      It depends on status of the error message.
 * @param desc           Description of the error message.It describes the vulnerable type and where it happens.
 * @return here return true to continue the sequence. No need to return any value from this method.
 */
public static boolean handleThreat(org.apache.synapse.MessageContext messageContext,
                                   String errorCode, String desc) {

    messageContext.setProperty(APIMgtGatewayConstants.THREAT_FOUND, true);
    messageContext.setProperty(APIMgtGatewayConstants.THREAT_CODE, errorCode);
    if (messageContext.isResponse()) {
        messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_RESPONSE);
    } else {
        messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_REQUEST);
    }
    messageContext.setProperty(APIMgtGatewayConstants.THREAT_DESC, desc);
    Mediator sequence = messageContext.getSequence(APIMgtGatewayConstants.THREAT_FAULT);
    // Invoke the custom error handler specified by the user
    if (sequence != null && !sequence.mediate(messageContext)) {
        // If needed user should be able to prevent the rest of the fault handling
        // logic from getting executed
    }
    return true;
}
 
Example 3
Source Project: carbon-apimgt   Source File: DataPublisherUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String getClientIp( MessageContext axis2MsgContext){
    String clientIp;
    Map headers =
            (Map) (axis2MsgContext).getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String xForwardForHeader = (String) headers.get(HEADER_X_FORWARDED_FOR);
    if (!StringUtils.isEmpty(xForwardForHeader)){
        clientIp = xForwardForHeader;
        int idx = xForwardForHeader.indexOf(',');
        if (idx > -1) {
            clientIp = clientIp.substring(0, idx);
        }
    }else{
     clientIp = (String) axis2MsgContext.getProperty(MessageContext.REMOTE_ADDR);
    }
    return clientIp;
}
 
Example 4
Source Project: carbon-apimgt   Source File: ThrottleConditionEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isConditionGroupApplicable(org.apache.synapse.MessageContext synapseContext,
                                           AuthenticationContext authenticationContext,
                                           ConditionGroupDTO conditionGroup) {

    ConditionDTO[] conditions = conditionGroup.getConditions();

    boolean evaluationState = true;

    if (conditions.length == 0) {
        evaluationState = false;
    }

    // When multiple conditions have been specified, all the conditions should occur.
    for (ConditionDTO condition : conditions) {
        evaluationState = evaluationState & isConditionApplicable(synapseContext, authenticationContext, condition);

        // If one of the conditions are false, rest will evaluate to false. So no need to check the rest.
        if (!evaluationState) {
            return false;
        }
    }
    return evaluationState;
}
 
Example 5
protected String extractSessionID(MessageContext axis2MessageContext) {

        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

        if (o != null && o instanceof Map) {
            Map headerMap = (Map) o;
            String cookie = (String) headerMap.get(SET_COOKIE);
            if (cookie == null) {
                cookie = (String) headerMap.get(COOKIE);
            } else {
                cookie = cookie.split(";")[0];
            }
            return cookie;
        }
        return null;
    }
 
Example 6
Source Project: product-ei   Source File: LoadBalanceSessionFullClient.java    License: Apache License 2.0 6 votes vote down vote up
protected String extractSessionID(MessageContext axis2MessageContext) {

        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

        if (o instanceof Map) {
            Map headerMap = (Map) o;
            String cookie = (String) headerMap.get(SET_COOKIE);
            if (cookie == null) {
                cookie = (String) headerMap.get(COOKIE);
            } else {
                cookie = cookie.split(";")[0];
            }
            return cookie;
        }
        return null;
    }
 
Example 7
Source Project: openxds   Source File: AppendixV.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkSOAP12() throws XdsWSException {
	
	if (MessageContext.getCurrentMessageContext().isSOAP11()) {
		throwFault("SOAP 1.1 not supported");
	}
	SOAPEnvelope env = MessageContext.getCurrentMessageContext().getEnvelope();
	if (env == null)
		throwFault("No SOAP envelope found");
	SOAPHeader hdr = env.getHeader();
	if (hdr == null)
		throwFault("No SOAP header found");
	if ( !hdr.getChildrenWithName(new QName("http://www.w3.org/2005/08/addressing","Action")).hasNext()) {
		throwFault("WS-Action required in header");
	}

}
 
Example 8
/**
 * Finds axis Service and the Operation for DSS requests
 *
 * @param msgContext request message context
 * @throws AxisFault if any exception occurs while finding axis service or operation
 */
private static void dispatchAndVerify(MessageContext msgContext) throws AxisFault {
    requestDispatcher.invoke(msgContext);
    AxisService axisService = msgContext.getAxisService();
    if (axisService != null) {
        httpLocationBasedDispatcher.invoke(msgContext);
        if (msgContext.getAxisOperation() == null) {
            requestURIOperationDispatcher.invoke(msgContext);
        }

        AxisOperation axisOperation;
        if ((axisOperation = msgContext.getAxisOperation()) != null) {
            AxisEndpoint axisEndpoint =
                    (AxisEndpoint) msgContext.getProperty(WSDL2Constants.ENDPOINT_LOCAL_NAME);
            if (axisEndpoint != null) {
                AxisBindingOperation axisBindingOperation = (AxisBindingOperation) axisEndpoint
                        .getBinding().getChild(axisOperation.getName());
                msgContext.setProperty(Constants.AXIS_BINDING_OPERATION, axisBindingOperation);
            }
            msgContext.setAxisOperation(axisOperation);
        }
    }
}
 
Example 9
Source Project: carbon-apimgt   Source File: GatewayUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * return existing correlation ID in the message context or set new correlation ID to the message context.
 *
 * @param messageContext synapse message context
 * @return correlation ID
 */
public static String getAndSetCorrelationID(org.apache.synapse.MessageContext messageContext) {

    Object correlationObj = messageContext.getProperty(APIMgtGatewayConstants.AM_CORRELATION_ID);
    String correlationID;
    if (correlationObj != null) {
        correlationID = (String) correlationObj;
    } else {
        correlationID = UUID.randomUUID().toString();
        messageContext.setProperty(APIMgtGatewayConstants.AM_CORRELATION_ID, correlationID);
        if (log.isDebugEnabled()) {
            log.debug("Setting correlation ID to message context.");
        }
    }
    return correlationID;
}
 
Example 10
Source Project: carbon-apimgt   Source File: ThrottleConditionEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isWithinIP(MessageContext messageContext, ConditionDto.IPCondition ipCondition) {

        String currentIpString = GatewayUtils.getIp(messageContext);
        boolean status;
        if (StringUtils.isNotEmpty(currentIpString)) {
            BigInteger currentIp = APIUtil.ipToBigInteger(currentIpString);
            status = ipCondition.getStartingIp().compareTo(currentIp) <= 0
                    && ipCondition.getEndingIp().compareTo(currentIp) >= 0;
        } else {
            return false;
        }
        if (ipCondition.isInvert()) {
            return !status;
        } else {
            return status;
        }
    }
 
Example 11
Source Project: carbon-identity   Source File: XMPPConfigurationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 * @param operation
 * @throws IdentityProviderException
 */
private void checkUserAuthorization(String username, String operation)
        throws IdentityProviderException {
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        if (!username.equals(userName)) {
            throw new IdentityProviderException("Unauthorised action by user " + username
                                                + " to access " + operation);
        }
        return;
    }
    throw new IdentityProviderException("Unauthorised action by user " + username
                                        + " to access " + operation);
}
 
Example 12
Source Project: micro-integrator   Source File: REQUESTHASHGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is the implementation of the getDigest method and will implement the Extended DOMHASH algorithm based HTTP
 * request identifications. This will consider To address of the request, HTTP headers and XML Payload in generating
 * the digets. So, in effect this will uniquely identify the HTTP request with the same To address, Headers and
 * Payload.
 *
 * @param msgContext - MessageContext on which the XML node identifier will be generated
 * @return Object representing the DOMHASH value of the normalized XML node
 * @throws CachingException if there is an error in generating the digest key
 * @see org.wso2.caching.digest.DigestGenerator #getDigest(org.apache.axis2.context.MessageContext)
 */
public String getDigest(MessageContext msgContext) throws CachingException {
    OMNode body = msgContext.getEnvelope().getBody();
    String toAddress = null;
    if (msgContext.getTo() != null) {
        toAddress = msgContext.getTo().getAddress();
    }
    Map<String, String> headers = (Map) msgContext.getProperty(
            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (body != null) {
        byte[] digest = null;
        if (toAddress != null) {
            digest = getDigest(body, toAddress, headers, MD5_DIGEST_ALGORITHM);
        } else {
            digest = getDigest(body, MD5_DIGEST_ALGORITHM);
        }
        return digest != null ? getStringRepresentation(digest) : null;
    } else {
        return null;
    }
}
 
Example 13
Source Project: carbon-apimgt   Source File: APIKeyValidationService.java    License: Apache License 2.0 6 votes vote down vote up
private void logMessageDetails(MessageContext messageContext, APIKeyValidationInfoDTO apiKeyValidationInfoDTO) {
    String applicationName = apiKeyValidationInfoDTO.getApplicationName();
    String endUserName = apiKeyValidationInfoDTO.getEndUserName();
    String consumerKey = apiKeyValidationInfoDTO.getConsumerKey();
    Boolean isAuthorize = apiKeyValidationInfoDTO.isAuthorized();
    //Do not change this log format since its using by some external apps
    String logMessage = "";
    if (applicationName != null) {
        logMessage = " , appName=" + applicationName;
    }
    if (endUserName != null) {
        logMessage = logMessage + " , userName=" + endUserName;
    }
    Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String logID = (String) headers.get("activityID");
    if (logID != null) {
        logMessage = logMessage + " , transactionId=" + logID;
    }
    if (consumerKey != null) {
        logMessage = logMessage + " , consumerKey=" + consumerKey;
    }
    logMessage = logMessage + " , isAuthorized=" + isAuthorize;
    logMessage = logMessage + " , responseTime=" + new Date(System.currentTimeMillis());

    log.debug("OAuth token response from keyManager to gateway: " + logMessage);
}
 
Example 14
Source Project: carbon-commons   Source File: InOnlyMEPHandler.java    License: Apache License 2.0 6 votes vote down vote up
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    if (msgContext.getEnvelope() == null) {
        return InvocationResponse.CONTINUE;
    }
    if (msgContext.getFLOW() != MessageContext.IN_FLOW &&
        msgContext.getFLOW() != MessageContext.IN_FAULT_FLOW) {
        log.error("InOnlyMEPHandler not deployed in IN/IN_FAULT flow. Flow: " +
                  msgContext.getFLOW());
        return InvocationResponse.CONTINUE;
    }
    try {
        msgContext.setProperty(StatisticsConstants.REQUEST_RECEIVED_TIME,
                               "" + System.currentTimeMillis());
    } catch (Throwable e) { // Catching Throwable since exceptions here should not be propagated up
        log.error("Could not call InOnlyMEPHandler.invoke", e);
    }
    return InvocationResponse.CONTINUE;
}
 
Example 15
Source Project: carbon-identity   Source File: IdentityProviderService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 * @param operation
 * @throws IdentityProviderException
 */
private void checkUserAuthorization(String username, String operation) throws IdentityProviderException {
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);

    String tenantFreeUsername = MultitenantUtils.getTenantAwareUsername(username);

    if (httpSession != null) {
        String loggedInUsername = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        if (!tenantFreeUsername.equals(loggedInUsername)) {
            throw new IdentityProviderException("Unauthorised action by user " + username
                                                + " to access " + operation);
        }
    } else {
        throw new IdentityProviderException("Unauthorised action by user " + tenantFreeUsername
                                            + " to access " + operation);
    }
}
 
Example 16
Source Project: carbon-commons   Source File: TracerUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a prettified XML string from the SOAPEnvelope
 *
 * @param env        The SOAPEnvelope to be prettified
 * @param msgContext The MessageContext
 * @return prettified XML string from the SOAPEnvelope
 */
public static String getPrettyString(OMElement env, MessageContext msgContext) {
    String xml;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        env.serialize(baos);
        InputStream xmlIn = new ByteArrayInputStream(baos.toByteArray());
        String encoding =
                (String) msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
        XMLPrettyPrinter xmlPrettyPrinter = new XMLPrettyPrinter(xmlIn, encoding);
        xml = xmlPrettyPrinter.xmlFormat();
    } catch (Throwable e) {
        String error = "Error occurred while pretty printing message. " + e.getMessage();
        log.error(error, e);
        xml = error;
    }
    return xml;
}
 
Example 17
Source Project: micro-integrator   Source File: AxisOperationClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param trpUrl
 * @param addUrl
 * @param payload
 * @param action
 * @return soap envelop
 * @throws org.apache.axis2.AxisFault
 */

public OMElement send(String trpUrl, String addUrl, OMElement payload, String action) throws AxisFault {
    operationClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
    setMessageContext(addUrl, trpUrl, action);
    outMsgCtx.setEnvelope(createSOAPEnvelope(payload));
    operationClient.addMessageContext(outMsgCtx);
    operationClient.execute(true);
    MessageContext inMsgtCtx = operationClient.getMessageContext("In");
    SOAPEnvelope response = inMsgtCtx.getEnvelope();
    return response;
}
 
Example 18
Source Project: carbon-device-mgt   Source File: OauthAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Authenticates the user using the provided OAuth token and returns the status as a boolean.
 * Sets the tenant domain and tenant friendly username to the session as attributes.
 *
 * @param messageContext containing the request need to be authenticated.
 * @return boolean indicating the authentication status.
 */
public boolean isAuthenticated(MessageContext messageContext) {
    HttpServletRequest httpServletRequest = getHttpRequest(messageContext);
    String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
    String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR);
    String accessToken = headerPart[ACCESS_TOKEN_INDEX];
    OAuthValidationResponse response = null;
    try {
        response = tokenValidator.validateToken(accessToken);
    } catch (RemoteException e) {
        log.error("Failed to validate the OAuth token provided.", e);
    }
    if (response != null && response.isValid()) {
        HttpSession session;
        if ((session = httpServletRequest.getSession(false)) != null) {
            session.setAttribute(MultitenantConstants.TENANT_DOMAIN, response.getTenantDomain());
            session.setAttribute(ServerConstants.USER_LOGGED_IN, response.getUserName());
            if (log.isDebugEnabled()) {
                log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN));
            }
        }
        return true;
    }
    if (log.isDebugEnabled()) {
        log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId());
    }
    return false;
}
 
Example 19
Source Project: micro-integrator   Source File: RabbitMQInjectHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determine the message builder to use, set the message payload to the message context and
 * inject the message.
 *
 * @param properties  the AMQP basic properties
 * @param body        the message body
 * @param inboundName Inbound Name
 * @return delivery status of the message
 */
public boolean onMessage(AMQP.BasicProperties properties, byte[] body, String inboundName) {
    org.apache.synapse.MessageContext msgCtx = createMessageContext();
    try {
        MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        RabbitMQUtils.buildMessage(properties, body, axis2MsgCtx);
        axis2MsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, RabbitMQUtils.getTransportHeaders(properties));

        if (seq != null) {
            if (log.isDebugEnabled()) {
                log.debug("injecting message to sequence : " + injectingSeq);
            }
            seq.setErrorHandler(onErrorSeq);
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            msgCtx.setProperty(SynapseConstants.INBOUND_ENDPOINT_NAME, inboundName);
            msgCtx.setProperty(SynapseConstants.ARTIFACT_NAME,
                               SynapseConstants.FAIL_SAFE_MODE_INBOUND_ENDPOINT + inboundName);
            synapseEnvironment.injectInbound(msgCtx, seq, sequential);
        } else {
            log.error("Sequence: " + injectingSeq + " not found");
        }

        Object rollbackProperty = msgCtx.getProperty(RabbitMQConstants.SET_ROLLBACK_ONLY);
        if ((rollbackProperty instanceof Boolean && ((Boolean) rollbackProperty)) ||
            (rollbackProperty instanceof String && Boolean.parseBoolean((String) rollbackProperty))) {
            return false;
        }

    } catch (AxisFault axisFault) {
        log.error("Error when trying to read incoming message ...", axisFault);
        return false;
    }
    return true;
}
 
Example 20
@Test(groups = { "wso2.esb" }, description = "having 'Content-Encoding = gzip' within outsequence")
public void gzipCompressionInsideOutSequenceTest() throws Exception {
    ServiceClient client = getServiceClient(getProxyServiceURLHttp("sendingGZIPCompressedPayloadToClient"));
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_ACCEPT_GZIP, true);
    OMElement response = client.sendReceive(Utils.getStockQuoteRequest("GZIP"));
    OperationContext operationContext = client.getLastOperationContext();
    MessageContext inMessageContext = operationContext.getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
    CommonsTransportHeaders transportHeaders = (CommonsTransportHeaders) inMessageContext
            .getProperty(TRANSPORT_HEADERS);
    Assert.assertTrue(transportHeaders.containsKey(CONTENT_ENCODING), "Response Message not encoded");
    Assert.assertEquals(transportHeaders.get(CONTENT_ENCODING), "gzip", "Response Message not gzip encoded");
    Assert.assertTrue(response.toString().contains("GZIP"));
    Assert.assertTrue(response.toString().contains("GZIP Company"));

}
 
Example 21
@Test(groups = {"wso2.esb"}, description = "having 'Accept-Encoding = gzip' within both in and out sequences")
public void sendingAndReceivingGzipCompressedPayloadTest() throws Exception {
    ServiceClient client = getServiceClient(getProxyServiceURLHttp("sendingGZIPCompressedPayloadToClient"));
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_GZIP_REQUEST, true);
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_ACCEPT_GZIP, true);
    OMElement response = client.sendReceive(Utils.getStockQuoteRequest("GZIP"));
    OperationContext operationContext = client.getLastOperationContext();
    MessageContext inMessageContext = operationContext.getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
    CommonsTransportHeaders transportHeaders = (CommonsTransportHeaders) inMessageContext.getProperty(TRANSPORT_HEADERS);
    Assert.assertTrue(transportHeaders.containsKey(CONTENT_ENCODING), "Response Message not encoded");
    Assert.assertEquals(transportHeaders.get(CONTENT_ENCODING), "gzip", "Response Message not gzip encoded");
    Assert.assertTrue(response.toString().contains("GZIP"));
    Assert.assertTrue(response.toString().contains("GZIP Company"));
}
 
Example 22
@Test(groups = { "wso2.esb" }, description = "having 'Accept-Encoding = gzip' within both in and out sequences")
public void sendingAndReceivingGzipCompressedPayloadTest() throws Exception {
    ServiceClient client = getServiceClient(getProxyServiceURLHttp("sendingGZIPCompressedPayloadToClient"));
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_GZIP_REQUEST, true);
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_ACCEPT_GZIP, true);
    OMElement response = client.sendReceive(Utils.getStockQuoteRequest("GZIP"));
    OperationContext operationContext = client.getLastOperationContext();
    MessageContext inMessageContext = operationContext.getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
    CommonsTransportHeaders transportHeaders = (CommonsTransportHeaders) inMessageContext
            .getProperty(TRANSPORT_HEADERS);
    Assert.assertTrue(transportHeaders.containsKey(CONTENT_ENCODING), "Response Message not encoded");
    Assert.assertEquals(transportHeaders.get(CONTENT_ENCODING), "gzip", "Response Message not gzip encoded");
    Assert.assertTrue(response.toString().contains("GZIP"));
    Assert.assertTrue(response.toString().contains("GZIP Company"));
}
 
Example 23
@Test(groups = { "wso2.esb" }, description = "sending and accepting gzip compressed payload")
public void sendingAndReceivingGzipCompressedRequestInAllPathTest() throws Exception {
    ServiceClient client = getServiceClient(getProxyServiceURLHttp("sendAndReceiveGZIPCompressedPayload"));
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_GZIP_REQUEST, true);
    client.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.MC_ACCEPT_GZIP, true);
    OMElement response = client.sendReceive(Utils.getStockQuoteRequest("GZIP"));
    OperationContext operationContext = client.getLastOperationContext();
    MessageContext inMessageContext = operationContext.getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
    CommonsTransportHeaders transportHeaders = (CommonsTransportHeaders) inMessageContext
            .getProperty(TRANSPORT_HEADERS);
    Assert.assertTrue(transportHeaders.containsKey(CONTENT_ENCODING), "Response Message not encoded");
    Assert.assertEquals(transportHeaders.get(CONTENT_ENCODING), "gzip", "Response Message not gzip encoded");
    Assert.assertTrue(response.toString().contains("GZIP"));
    Assert.assertTrue(response.toString().contains("GZIP Company"));
}
 
Example 24
Source Project: openxds   Source File: ProvideAndRegisterDocumentSet.java    License: Apache License 2.0 5 votes vote down vote up
public ProvideAndRegisterDocumentSet(LogMessage log_message, short xds_version, MessageContext messageContext) {
	this.log_message = log_message;
	this.messageContext = messageContext;
	this.xds_version = xds_version;
	transaction_type = PR_transaction;

	try {
		if (messageContext == null) {
			throw new XdsInternalException("Cannot find MessageContext");
		}
		IheHTTPServer httpServer = (IheHTTPServer)messageContext.getTransportIn().getReceiver();
		
		IheActor actor = httpServer.getIheActor();
		if (actor == null) {
			throw new XdsInternalException("Cannot find XdsRepository actor configuration.");			
		}
		connection = actor.getConnection();
		if (connection == null) {
			throw new XdsInternalException("Cannot find Server connection configuration.");			
		}
		registryClientConnection = ((XdsRepository)actor).getRegistryClientConnection();
		if (registryClientConnection == null) {
			throw new XdsInternalException("Cannot find XdsRepository Registry connection configuration.");			
		}
		auditLog = actor.getAuditTrail();	
		init(new RegistryResponse( (xds_version == xds_a) ?	Response.version_2 : Response.version_3), xds_version, messageContext);
	} catch (XdsInternalException e) {
		logger.fatal("Internal Error creating RegistryResponse: " + e.getMessage());
	}
}
 
Example 25
Source Project: carbon-apimgt   Source File: GatewayUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static JWTInfoDto generateJWTInfoDto(JWTValidationInfo jwtValidationInfo, JSONObject subscribedAPI,
                                            APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
                                            org.apache.synapse.MessageContext synCtx)
        throws java.text.ParseException {
    JWTInfoDto jwtInfoDto = new JWTInfoDto();
    jwtInfoDto.setJwtValidationInfo(jwtValidationInfo);
    jwtInfoDto.setMessageContext(synCtx);
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    jwtInfoDto.setApicontext(apiContext);
    jwtInfoDto.setVersion(apiVersion);
    constructJWTContent(subscribedAPI, apiKeyValidationInfoDTO, jwtInfoDto);
    return jwtInfoDto;
}
 
Example 26
Source Project: carbon-commons   Source File: MemoryBasedTracePersister.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized String[] getMessages(String serviceName,
                                         String operationName,
                                         long messageSequence,
                                         MessageContext msgContext) {
    String[] responses = new String[2];
    List<MessagePair> messagePairList = msgBuffer.get(TracerConstants.MSG_BUFFER_SZ);
    MessagePair tmp = new MessagePair(serviceName, operationName, messageSequence);
    for (MessagePair msgPair : messagePairList) {
        if (msgPair.equals(tmp)) {
            TraceMessage inMessage = msgPair.getInMessage();
            if (inMessage != null && inMessage.getSoapEnvelope() != null) {
                responses[0] = TracerUtils.getPrettyString(inMessage.getSoapEnvelope(),
                        msgContext);
            } else {
                responses[0] = "No request found";
            }
            TraceMessage outMessage = msgPair.getOutMessage();
            if (outMessage != null && outMessage.getSoapEnvelope() != null) {
                responses[1] = TracerUtils.getPrettyString(outMessage.getSoapEnvelope(),
                        msgContext);
            } else {
                responses[1] = "No response found";
            }
        }
    }
    return responses;
}
 
Example 27
Source Project: micro-integrator   Source File: DBUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getCurrentContextUsername(DataService dataService) {
    MessageContext ctx = MessageContext.getCurrentMessageContext();
    if (ctx != null) {
        try {
            return dataService.getAuthorizationProvider().getUsername(ctx);
        } catch (DataServiceFault dataServiceFault) {
            return null;
        }
    } else {
        return null;
    }
}
 
Example 28
Source Project: product-ei   Source File: LoadbalanceFailoverClient.java    License: Apache License 2.0 5 votes vote down vote up
protected String getSetCookieHeader(MessageContext axis2MessageContext) {

        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

        if (o != null && o instanceof Map) {
            Map headerMap = (Map) o;
            return (String) headerMap.get(SET_COOKIE);
        }
        return null;
    }
 
Example 29
Source Project: carbon-apimgt   Source File: OIDCAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isAuthenticated(MessageContext messageContext) {
    HttpServletRequest request = (HttpServletRequest) messageContext
            .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession();
    String loginStatus = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);

    return (loginStatus != null);
}
 
Example 30
Source Project: product-ei   Source File: LoadBalanceSessionFullClient.java    License: Apache License 2.0 5 votes vote down vote up
protected String getSetCookieHeader(MessageContext axis2MessageContext) {

        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

        if (o instanceof Map) {
            Map headerMap = (Map) o;
            return (String) headerMap.get(SET_COOKIE);
        }
        return null;
    }