Search in sources :

Example 36 with BString

use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.

the class CPU method convertMapToStruct.

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void convertMapToStruct(WorkerExecutionContext ctx, int[] operands, WorkerData sf) {
    int i = operands[0];
    int cpIndex = operands[1];
    int j = operands[2];
    TypeRefCPEntry typeRefCPEntry = (TypeRefCPEntry) ctx.constPool[cpIndex];
    BMap<String, BValue> bMap = (BMap<String, BValue>) sf.refRegs[i];
    if (bMap == null) {
        handleNullRefError(ctx);
        return;
    }
    int longRegIndex = -1;
    int doubleRegIndex = -1;
    int stringRegIndex = -1;
    int booleanRegIndex = -1;
    int blobRegIndex = -1;
    int refRegIndex = -1;
    BStructType structType = (BStructType) typeRefCPEntry.getType();
    BStruct bStruct = new BStruct(structType);
    StructInfo structInfo = ctx.callableUnitInfo.getPackageInfo().getStructInfo(structType.getName());
    Set<String> keys = bMap.keySet();
    for (StructFieldInfo fieldInfo : structInfo.getFieldInfoEntries()) {
        String key = fieldInfo.getName();
        BType fieldType = fieldInfo.getFieldType();
        BValue mapVal = null;
        try {
            boolean containsField = keys.contains(key);
            DefaultValueAttributeInfo defaultValAttrInfo = null;
            if (containsField) {
                mapVal = bMap.get(key);
                if (mapVal == null && BTypes.isValueType(fieldType)) {
                    throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_FIELD_TYPE_FOR_CASTING, key, fieldType, null);
                }
                if (mapVal != null && !checkCast(mapVal, fieldType)) {
                    throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_FIELD_TYPE_FOR_CASTING, key, fieldType, mapVal.getType());
                }
            } else {
                defaultValAttrInfo = (DefaultValueAttributeInfo) getAttributeInfo(fieldInfo, AttributeInfo.Kind.DEFAULT_VALUE_ATTRIBUTE);
            }
            switch(fieldType.getTag()) {
                case TypeTags.INT_TAG:
                    longRegIndex++;
                    if (containsField) {
                        bStruct.setIntField(longRegIndex, ((BInteger) mapVal).intValue());
                    } else if (defaultValAttrInfo != null) {
                        bStruct.setIntField(longRegIndex, defaultValAttrInfo.getDefaultValue().getIntValue());
                    }
                    break;
                case TypeTags.FLOAT_TAG:
                    doubleRegIndex++;
                    if (containsField) {
                        bStruct.setFloatField(doubleRegIndex, ((BFloat) mapVal).floatValue());
                    } else if (defaultValAttrInfo != null) {
                        bStruct.setFloatField(doubleRegIndex, defaultValAttrInfo.getDefaultValue().getFloatValue());
                    }
                    break;
                case TypeTags.STRING_TAG:
                    stringRegIndex++;
                    if (containsField) {
                        bStruct.setStringField(stringRegIndex, ((BString) mapVal).stringValue());
                    } else if (defaultValAttrInfo != null) {
                        bStruct.setStringField(stringRegIndex, defaultValAttrInfo.getDefaultValue().getStringValue());
                    }
                    break;
                case TypeTags.BOOLEAN_TAG:
                    booleanRegIndex++;
                    if (containsField) {
                        bStruct.setBooleanField(booleanRegIndex, ((BBoolean) mapVal).booleanValue() ? 1 : 0);
                    } else if (defaultValAttrInfo != null) {
                        bStruct.setBooleanField(booleanRegIndex, defaultValAttrInfo.getDefaultValue().getBooleanValue() ? 1 : 0);
                    }
                    break;
                case TypeTags.BLOB_TAG:
                    blobRegIndex++;
                    if (containsField && mapVal != null) {
                        bStruct.setBlobField(blobRegIndex, ((BBlob) mapVal).blobValue());
                    }
                    break;
                default:
                    bStruct.setRefField(++refRegIndex, (BRefType) mapVal);
            }
        } catch (BallerinaException e) {
            sf.refRegs[j] = null;
            String errorMsg = "cannot convert '" + bMap.getType() + "' to type '" + structType + ": " + e.getMessage();
            handleTypeConversionError(ctx, sf, j, errorMsg);
            return;
        }
    }
    sf.refRegs[j] = bStruct;
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) BMap(org.ballerinalang.model.values.BMap) StructInfo(org.ballerinalang.util.codegen.StructInfo) TypeRefCPEntry(org.ballerinalang.util.codegen.cpentries.TypeRefCPEntry) BValue(org.ballerinalang.model.values.BValue) BBoolean(org.ballerinalang.model.values.BBoolean) StructFieldInfo(org.ballerinalang.util.codegen.StructFieldInfo) BString(org.ballerinalang.model.values.BString) BStructType(org.ballerinalang.model.types.BStructType) DefaultValueAttributeInfo(org.ballerinalang.util.codegen.attributes.DefaultValueAttributeInfo) BType(org.ballerinalang.model.types.BType) BallerinaException(org.ballerinalang.util.exceptions.BallerinaException)

Example 37 with BString

use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.

the class BLangVMUtils method populateArgAndReturnData.

@SuppressWarnings("rawtypes")
public static int[][] populateArgAndReturnData(WorkerExecutionContext ctx, CallableUnitInfo callableUnitInfo, BValue[] args) {
    WorkerDataIndex wdi1 = callableUnitInfo.paramWorkerIndex;
    WorkerDataIndex wdi2 = callableUnitInfo.retWorkerIndex;
    WorkerData local = createWorkerData(wdi1, wdi2);
    BType[] types = callableUnitInfo.getParamTypes();
    int longParamCount = 0, doubleParamCount = 0, stringParamCount = 0, intParamCount = 0, byteParamCount = 0, refParamCount = 0;
    for (int i = 0; i < types.length; i++) {
        switch(types[i].getTag()) {
            case TypeTags.INT_TAG:
                if (args[i] instanceof BString) {
                    local.longRegs[longParamCount] = ((BString) args[i]).intValue();
                } else {
                    local.longRegs[longParamCount] = ((BInteger) args[i]).intValue();
                }
                longParamCount++;
                break;
            case TypeTags.FLOAT_TAG:
                if (args[i] instanceof BString) {
                    local.doubleRegs[doubleParamCount] = ((BString) args[i]).floatValue();
                } else {
                    local.doubleRegs[doubleParamCount] = ((BFloat) args[i]).floatValue();
                }
                doubleParamCount++;
                break;
            case TypeTags.STRING_TAG:
                local.stringRegs[stringParamCount] = args[i].stringValue();
                stringParamCount++;
                break;
            case TypeTags.BOOLEAN_TAG:
                if (args[i] instanceof BString) {
                    local.intRegs[intParamCount] = ((BString) args[i]).value().toLowerCase().equals("true") ? 1 : 0;
                } else {
                    local.intRegs[intParamCount] = ((BBoolean) args[i]).booleanValue() ? 1 : 0;
                }
                intParamCount++;
                break;
            case TypeTags.BLOB_TAG:
                local.byteRegs[byteParamCount] = ((BBlob) args[i]).blobValue();
                byteParamCount++;
                break;
            default:
                local.refRegs[refParamCount] = (BRefType) args[i];
                refParamCount++;
                break;
        }
    }
    ctx.workerLocal = local;
    return new int[][] { wdi1.retRegs, BLangVMUtils.createReturnRegValues(wdi1, wdi2, callableUnitInfo.getRetParamTypes()) };
}
Also used : BType(org.ballerinalang.model.types.BType) BString(org.ballerinalang.model.values.BString) BBoolean(org.ballerinalang.model.values.BBoolean) WorkerData(org.ballerinalang.bre.bvm.WorkerData)

Example 38 with BString

use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.

the class BLangVMUtils method populateReturnData.

public static BValue[] populateReturnData(WorkerExecutionContext ctx, CallableUnitInfo callableUnitInfo, int[] retRegs) {
    WorkerData data = ctx.workerLocal;
    BType[] retTypes = callableUnitInfo.getRetParamTypes();
    BValue[] returnValues = new BValue[retTypes.length];
    for (int i = 0; i < returnValues.length; i++) {
        BType retType = retTypes[i];
        switch(retType.getTag()) {
            case TypeTags.INT_TAG:
                returnValues[i] = new BInteger(data.longRegs[retRegs[i]]);
                break;
            case TypeTags.FLOAT_TAG:
                returnValues[i] = new BFloat(data.doubleRegs[retRegs[i]]);
                break;
            case TypeTags.STRING_TAG:
                returnValues[i] = new BString(data.stringRegs[retRegs[i]]);
                break;
            case TypeTags.BOOLEAN_TAG:
                boolean boolValue = data.intRegs[retRegs[i]] == 1;
                returnValues[i] = new BBoolean(boolValue);
                break;
            case TypeTags.BLOB_TAG:
                returnValues[i] = new BBlob(data.byteRegs[retRegs[i]]);
                break;
            default:
                returnValues[i] = data.refRegs[retRegs[i]];
                break;
        }
    }
    return returnValues;
}
Also used : BType(org.ballerinalang.model.types.BType) BValue(org.ballerinalang.model.values.BValue) BString(org.ballerinalang.model.values.BString) BInteger(org.ballerinalang.model.values.BInteger) BFloat(org.ballerinalang.model.values.BFloat) BBoolean(org.ballerinalang.model.values.BBoolean) WorkerData(org.ballerinalang.bre.bvm.WorkerData) BBlob(org.ballerinalang.model.values.BBlob)

Example 39 with BString

use of org.ballerinalang.model.values.BString 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 40 with BString

use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.

the class UpgradeToWebSocket method execute.

@Override
public void execute(Context context) {
    BStruct serverConnector = (BStruct) context.getRefArgument(0);
    WebSocketService webSocketService = (WebSocketService) serverConnector.getNativeData(WebSocketConstants.WEBSOCKET_SERVICE);
    BMap<String, BString> headers = (BMap<String, BString>) context.getRefArgument(1);
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    Set<String> keys = headers.keySet();
    for (String key : keys) {
        httpHeaders.add(key, headers.get(key));
    }
    WebSocketUtil.handleHandshake(webSocketService, httpHeaders, serverConnector);
    context.setReturnValues();
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) BMap(org.ballerinalang.model.values.BMap) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) BString(org.ballerinalang.model.values.BString) WebSocketService(org.ballerinalang.net.http.WebSocketService) BString(org.ballerinalang.model.values.BString)

Aggregations

BString (org.ballerinalang.model.values.BString)418 BValue (org.ballerinalang.model.values.BValue)339 Test (org.testng.annotations.Test)321 BInteger (org.ballerinalang.model.values.BInteger)77 BStruct (org.ballerinalang.model.values.BStruct)76 BMap (org.ballerinalang.model.values.BMap)37 BBoolean (org.ballerinalang.model.values.BBoolean)36 BFloat (org.ballerinalang.model.values.BFloat)34 BJSON (org.ballerinalang.model.values.BJSON)28 BallerinaException (org.ballerinalang.util.exceptions.BallerinaException)21 BRefValueArray (org.ballerinalang.model.values.BRefValueArray)18 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)11 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)11 CompileResult (org.ballerinalang.launcher.util.CompileResult)11 BBlob (org.ballerinalang.model.values.BBlob)11 BStringArray (org.ballerinalang.model.values.BStringArray)11 BType (org.ballerinalang.model.types.BType)10 BIntArray (org.ballerinalang.model.values.BIntArray)9 BRefType (org.ballerinalang.model.values.BRefType)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7