Search in sources :

Example 1 with RequestCacheControlStruct

use of org.ballerinalang.net.http.caching.RequestCacheControlStruct in project ballerina by ballerina-lang.

the class WebSocketServerConnectorListener method onMessage.

@Override
public void onMessage(WebSocketInitMessage webSocketInitMessage) {
    HTTPCarbonMessage msg = new HTTPCarbonMessage(((DefaultWebSocketInitMessage) webSocketInitMessage).getHttpRequest());
    Map<String, String> pathParams = new HashMap<>();
    WebSocketService wsService = WebSocketDispatcher.findService(servicesRegistry, pathParams, webSocketInitMessage, msg);
    BStruct serviceEndpoint = BLangConnectorSPIUtil.createBStruct(wsService.getResources()[0].getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, WEBSOCKET_ENDPOINT);
    BStruct serverConnector = WebSocketUtil.createAndGetBStruct(wsService.getResources()[0]);
    serverConnector.addNativeData(WebSocketConstants.WEBSOCKET_MESSAGE, webSocketInitMessage);
    serverConnector.addNativeData(WebSocketConstants.WEBSOCKET_SERVICE, wsService);
    serviceEndpoint.setRefField(SERVICE_ENDPOINT_CONNECTION_INDEX, serverConnector);
    serviceEndpoint.setRefField(3, new BMap());
    serverConnector.addNativeData(WEBSOCKET_ENDPOINT, serviceEndpoint);
    Map<String, String> upgradeHeaders = webSocketInitMessage.getHeaders();
    BMap<String, BString> bUpgradeHeaders = new BMap<>();
    upgradeHeaders.forEach((key, value) -> bUpgradeHeaders.put(key, new BString(value)));
    serviceEndpoint.setRefField(4, bUpgradeHeaders);
    Resource onUpgradeResource = wsService.getResourceByName(WebSocketConstants.RESOURCE_NAME_ON_UPGRADE);
    if (onUpgradeResource != null) {
        Semaphore semaphore = new Semaphore(0);
        AtomicBoolean isResourceExeSuccessful = new AtomicBoolean(false);
        BStruct inRequest = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), PROTOCOL_PACKAGE_HTTP, HttpConstants.REQUEST);
        BStruct inRequestEntity = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.ENTITY);
        BStruct mediaType = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.MEDIA_TYPE);
        BStruct cacheControlStruct = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), PROTOCOL_PACKAGE_HTTP, REQUEST_CACHE_CONTROL);
        RequestCacheControlStruct requestCacheControl = new RequestCacheControlStruct(cacheControlStruct);
        HttpUtil.populateInboundRequest(inRequest, inRequestEntity, mediaType, msg, requestCacheControl);
        List<ParamDetail> paramDetails = onUpgradeResource.getParamDetails();
        BValue[] bValues = new BValue[paramDetails.size()];
        bValues[0] = serviceEndpoint;
        bValues[1] = inRequest;
        WebSocketDispatcher.setPathParams(bValues, paramDetails, pathParams, 2);
        Tracer tracer = TraceManagerWrapper.newTracer(null, false);
        upgradeHeaders.entrySet().stream().filter(c -> c.getKey().startsWith(TraceConstants.TRACE_PREFIX)).forEach(e -> tracer.addProperty(e.getKey(), e.getValue()));
        Executor.submit(onUpgradeResource, new CallableUnitCallback() {

            @Override
            public void notifySuccess() {
                isResourceExeSuccessful.set(true);
                semaphore.release();
            }

            @Override
            public void notifyFailure(BStruct error) {
                ErrorHandlerUtils.printError("error: " + BLangVMErrors.getPrintableStackTrace(error));
                semaphore.release();
            }
        }, null, tracer, bValues);
        try {
            semaphore.acquire();
            if (isResourceExeSuccessful.get() && !webSocketInitMessage.isCancelled() && !webSocketInitMessage.isHandshakeStarted()) {
                WebSocketUtil.handleHandshake(wsService, null, serverConnector);
            }
        } catch (InterruptedException e) {
            throw new BallerinaConnectorException("Connection interrupted during handshake");
        }
    } else {
        WebSocketUtil.handleHandshake(wsService, null, serverConnector);
    }
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) WebSocketTextMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketTextMessage) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CallableUnitCallback(org.ballerinalang.bre.bvm.CallableUnitCallback) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) HashMap(java.util.HashMap) WebSocketControlMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketControlMessage) WebSocketInitMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketInitMessage) BLangConnectorSPIUtil(org.ballerinalang.connector.api.BLangConnectorSPIUtil) Executor(org.ballerinalang.connector.api.Executor) Resource(org.ballerinalang.connector.api.Resource) WebSocketBinaryMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketBinaryMessage) WebSocketConnectorListener(org.wso2.transport.http.netty.contract.websocket.WebSocketConnectorListener) DefaultWebSocketInitMessage(org.wso2.transport.http.netty.contractimpl.websocket.message.DefaultWebSocketInitMessage) WEBSOCKET_ENDPOINT(org.ballerinalang.net.http.WebSocketConstants.WEBSOCKET_ENDPOINT) BString(org.ballerinalang.model.values.BString) WebSocketCloseMessage(org.wso2.transport.http.netty.contract.websocket.WebSocketCloseMessage) Map(java.util.Map) BStruct(org.ballerinalang.model.values.BStruct) BMap(org.ballerinalang.model.values.BMap) Logger(org.slf4j.Logger) Semaphore(java.util.concurrent.Semaphore) ErrorHandlerUtils(org.ballerinalang.services.ErrorHandlerUtils) BLangVMErrors(org.ballerinalang.bre.bvm.BLangVMErrors) Constants(org.ballerinalang.mime.util.Constants) REQUEST_CACHE_CONTROL(org.ballerinalang.net.http.HttpConstants.REQUEST_CACHE_CONTROL) SERVICE_ENDPOINT_CONNECTION_INDEX(org.ballerinalang.net.http.HttpConstants.SERVICE_ENDPOINT_CONNECTION_INDEX) TraceManagerWrapper(org.ballerinalang.util.tracer.TraceManagerWrapper) TraceConstants(org.ballerinalang.util.tracer.TraceConstants) PROTOCOL_PACKAGE_HTTP(org.ballerinalang.net.http.HttpConstants.PROTOCOL_PACKAGE_HTTP) List(java.util.List) Tracer(org.ballerinalang.util.tracer.Tracer) ParamDetail(org.ballerinalang.connector.api.ParamDetail) BallerinaConnectorException(org.ballerinalang.connector.api.BallerinaConnectorException) BValue(org.ballerinalang.model.values.BValue) BStruct(org.ballerinalang.model.values.BStruct) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BallerinaConnectorException(org.ballerinalang.connector.api.BallerinaConnectorException) HashMap(java.util.HashMap) BMap(org.ballerinalang.model.values.BMap) BString(org.ballerinalang.model.values.BString) BValue(org.ballerinalang.model.values.BValue) Tracer(org.ballerinalang.util.tracer.Tracer) Resource(org.ballerinalang.connector.api.Resource) BString(org.ballerinalang.model.values.BString) Semaphore(java.util.concurrent.Semaphore) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParamDetail(org.ballerinalang.connector.api.ParamDetail) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) CallableUnitCallback(org.ballerinalang.bre.bvm.CallableUnitCallback)

Example 2 with RequestCacheControlStruct

use of org.ballerinalang.net.http.caching.RequestCacheControlStruct in project ballerina by ballerina-lang.

the class HttpCachingClientTest method testIsStaleResponseAccepted.

@Test(description = "Test for the isStaleResponseAccepted() function which determines whether stale responses are" + " acceptable", enabled = false)
public void testIsStaleResponseAccepted() {
    boolean isSharedCache = false;
    RequestCacheControlStruct requestCacheControl = new RequestCacheControlStruct(compileResult.getProgFile().getPackageInfo(PROTOCOL_PACKAGE_HTTP).getStructInfo(REQUEST_CACHE_CONTROL));
    requestCacheControl.setMaxStale(Long.MAX_VALUE);
    BStruct cachedResponse = BCompileUtil.createAndGetStruct(compileResult.getProgFile(), PROTOCOL_PACKAGE_HTTP, RESPONSE);
    ResponseCacheControlStruct responseCacheControl = new ResponseCacheControlStruct(compileResult.getProgFile().getPackageInfo(PROTOCOL_PACKAGE_HTTP).getStructInfo(RESPONSE_CACHE_CONTROL));
    HTTPCarbonMessage cachedResponseMsg = HttpUtil.createHttpCarbonMessage(false);
    cachedResponseMsg.setProperty(HTTP_STATUS_CODE, 200);
    cachedResponseMsg.setHeader(AGE, "10");
    ;
    initInboundResponse(cachedResponse, responseCacheControl, cachedResponseMsg);
    BValue[] inputArgs = { requestCacheControl.getStruct(), cachedResponse, new BBoolean(isSharedCache) };
    BValue[] returns = BRunUtil.invoke(compileResult, "isStaleResponseAccepted", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
    requestCacheControl.setMaxStale(-1);
    returns = BRunUtil.invoke(compileResult, "isStaleResponseAccepted", inputArgs);
    Assert.assertFalse(((BBoolean) returns[0]).booleanValue());
    requestCacheControl.setMaxStale(7);
    responseCacheControl.setMaxAge(5);
    returns = BRunUtil.invoke(compileResult, "isStaleResponseAccepted", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
    requestCacheControl.setMaxStale(7);
    responseCacheControl.setMaxAge(3);
    returns = BRunUtil.invoke(compileResult, "isStaleResponseAccepted", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BValue(org.ballerinalang.model.values.BValue) BBoolean(org.ballerinalang.model.values.BBoolean) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) ResponseCacheControlStruct(org.ballerinalang.net.http.caching.ResponseCacheControlStruct) Test(org.testng.annotations.Test)

Example 3 with RequestCacheControlStruct

use of org.ballerinalang.net.http.caching.RequestCacheControlStruct in project ballerina by ballerina-lang.

the class HttpDispatcher method getSignatureParameters.

public static BValue[] getSignatureParameters(HttpResource httpResource, HTTPCarbonMessage httpCarbonMessage) {
    // TODO Think of keeping struct type globally rather than creating for each request
    BStruct serviceEndpoint = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, SERVICE_ENDPOINT);
    BStruct connection = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, HttpConstants.CONNECTION);
    BStruct inRequest = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, HttpConstants.REQUEST);
    BStruct inRequestEntity = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.ENTITY);
    BStruct mediaType = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.MEDIA_TYPE);
    BStruct cacheControlStruct = BLangConnectorSPIUtil.createBStruct(httpResource.getBalResource().getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, REQUEST_CACHE_CONTROL);
    RequestCacheControlStruct requestCacheControl = new RequestCacheControlStruct(cacheControlStruct);
    HttpUtil.enrichServiceEndpointInfo(serviceEndpoint, httpCarbonMessage, httpResource);
    HttpUtil.enrichConnectionInfo(connection, httpCarbonMessage);
    serviceEndpoint.setRefField(SERVICE_ENDPOINT_CONNECTION_INDEX, connection);
    HttpUtil.enrichConnectionInfo(connection, httpCarbonMessage);
    HttpUtil.populateInboundRequest(inRequest, inRequestEntity, mediaType, httpCarbonMessage, requestCacheControl);
    SignatureParams signatureParams = httpResource.getSignatureParams();
    BValue[] bValues = new BValue[signatureParams.getParamCount()];
    bValues[0] = serviceEndpoint;
    bValues[1] = inRequest;
    if (signatureParams.getParamCount() == 2) {
        return bValues;
    }
    Map<String, String> resourceArgumentValues = (Map<String, String>) httpCarbonMessage.getProperty(HttpConstants.RESOURCE_ARGS);
    for (int i = 0; i < signatureParams.getPathParams().size(); i++) {
        // No need for validation as validation already happened at deployment time,
        // only string parameters can be found here.
        String argumentValue = resourceArgumentValues.get(signatureParams.getPathParams().get(i).getVarName());
        if (argumentValue != null) {
            try {
                argumentValue = URLDecoder.decode(argumentValue, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            // we can simply ignore and send the value to application and let the
            // application deal with the value.
            }
        }
        bValues[i + 2] = new BString(argumentValue);
    }
    if (signatureParams.getEntityBody() == null) {
        return bValues;
    }
    try {
        bValues[bValues.length - 1] = populateAndGetEntityBody(httpResource, inRequest, inRequestEntity, signatureParams.getEntityBody().getVarType());
    } catch (BallerinaException ex) {
        httpCarbonMessage.setProperty(HttpConstants.HTTP_STATUS_CODE, HttpConstants.HTTP_BAD_REQUEST);
        throw new BallerinaConnectorException("data binding failed: " + ex.getMessage());
    } catch (IOException ex) {
        throw new BallerinaException(ex.getMessage());
    }
    return bValues;
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) BallerinaConnectorException(org.ballerinalang.connector.api.BallerinaConnectorException) BValue(org.ballerinalang.model.values.BValue) BString(org.ballerinalang.model.values.BString) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BString(org.ballerinalang.model.values.BString) IOException(java.io.IOException) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) BallerinaException(org.ballerinalang.util.exceptions.BallerinaException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with RequestCacheControlStruct

use of org.ballerinalang.net.http.caching.RequestCacheControlStruct in project ballerina by ballerina-lang.

the class RequestNativeFunctionSuccessTest method testGetHeader.

@Test
public void testGetHeader() {
    BStruct inRequest = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, reqStruct);
    HTTPTestRequest inRequestMsg = MessageUtils.generateHTTPMessage("", HttpConstants.HTTP_METHOD_GET);
    inRequestMsg.setHeader(HttpHeaderNames.CONTENT_TYPE.toString(), APPLICATION_FORM);
    BStruct entity = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, entityStruct);
    BStruct mediaType = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, mediaTypeStruct);
    BStruct cacheControl = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, reqCacheControlStruct);
    RequestCacheControlStruct cacheControlStruct = new RequestCacheControlStruct(cacheControl);
    HttpUtil.populateInboundRequest(inRequest, entity, mediaType, inRequestMsg, cacheControlStruct);
    BString key = new BString(HttpHeaderNames.CONTENT_TYPE.toString());
    BValue[] inputArg = { inRequest, key };
    BValue[] returnVals = BRunUtil.invoke(result, "testGetHeader", inputArg);
    Assert.assertFalse(returnVals == null || returnVals.length == 0 || returnVals[0] == null, "Invalid Return Values.");
    Assert.assertEquals(returnVals[0].stringValue(), APPLICATION_FORM);
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) BString(org.ballerinalang.model.values.BString) BValue(org.ballerinalang.model.values.BValue) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Example 5 with RequestCacheControlStruct

use of org.ballerinalang.net.http.caching.RequestCacheControlStruct in project ballerina by ballerina-lang.

the class RequestNativeFunctionSuccessTest method testGetHeaders.

@Test(description = "Test GetHeaders function within a function")
public void testGetHeaders() {
    BStruct inRequest = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, reqStruct);
    HTTPTestRequest inRequestMsg = MessageUtils.generateHTTPMessage("", HttpConstants.HTTP_METHOD_GET);
    HttpHeaders headers = inRequestMsg.getHeaders();
    headers.set("test-header", APPLICATION_FORM);
    headers.add("test-header", TEXT_PLAIN);
    BStruct entity = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, entityStruct);
    BStruct mediaType = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, mediaTypeStruct);
    BStruct cacheControl = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, reqCacheControlStruct);
    RequestCacheControlStruct cacheControlStruct = new RequestCacheControlStruct(cacheControl);
    HttpUtil.populateInboundRequest(inRequest, entity, mediaType, inRequestMsg, cacheControlStruct);
    BString key = new BString("test-header");
    BValue[] inputArg = { inRequest, key };
    BValue[] returnVals = BRunUtil.invoke(result, "testGetHeaders", inputArg);
    Assert.assertFalse(returnVals == null || returnVals.length == 0 || returnVals[0] == null, "Invalid Return Values.");
    Assert.assertEquals(((BStringArray) returnVals[0]).get(0), APPLICATION_FORM);
    Assert.assertEquals(((BStringArray) returnVals[0]).get(1), TEXT_PLAIN);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) BStruct(org.ballerinalang.model.values.BStruct) BString(org.ballerinalang.model.values.BString) BValue(org.ballerinalang.model.values.BValue) RequestCacheControlStruct(org.ballerinalang.net.http.caching.RequestCacheControlStruct) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Aggregations

BValue (org.ballerinalang.model.values.BValue)6 RequestCacheControlStruct (org.ballerinalang.net.http.caching.RequestCacheControlStruct)6 BStruct (org.ballerinalang.model.values.BStruct)5 BString (org.ballerinalang.model.values.BString)4 Test (org.testng.annotations.Test)4 HashMap (java.util.HashMap)2 Map (java.util.Map)2 BallerinaConnectorException (org.ballerinalang.connector.api.BallerinaConnectorException)2 ResponseCacheControlStruct (org.ballerinalang.net.http.caching.ResponseCacheControlStruct)2 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)2 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 List (java.util.List)1 Semaphore (java.util.concurrent.Semaphore)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 BLangVMErrors (org.ballerinalang.bre.bvm.BLangVMErrors)1 CallableUnitCallback (org.ballerinalang.bre.bvm.CallableUnitCallback)1