Search in sources :

Example 31 with BType

use of org.ballerinalang.model.types.BType in project ballerina by ballerina-lang.

the class MessageUtils method generateRequestStruct.

public static BValue generateRequestStruct(Message request, String fieldName, BType structType, Context context) {
    BValue bValue = null;
    int stringIndex = 0;
    int intIndex = 0;
    int floatIndex = 0;
    int boolIndex = 0;
    int refIndex = 0;
    if (structType instanceof BStructType) {
        BStruct requestStruct = createStruct(context, fieldName);
        for (BStructType.StructField structField : ((BStructType) structType).getStructFields()) {
            String structFieldName = structField.getFieldName();
            if (structField.getFieldType() instanceof BRefType) {
                BType bType = structField.getFieldType();
                if (MessageRegistry.getInstance().getMessageDescriptorMap().containsKey(bType.getName())) {
                    Message message = (Message) request.getFields().get(structFieldName);
                    requestStruct.setRefField(refIndex++, (BRefType) generateRequestStruct(message, structFieldName, structField.getFieldType(), context));
                }
            } else {
                if (request.getFields().containsKey(structFieldName)) {
                    String fieldType = structField.getFieldType().getName();
                    switch(fieldType) {
                        case STRING:
                            {
                                requestStruct.setStringField(stringIndex++, (String) request.getFields().get(structFieldName));
                                break;
                            }
                        case INT:
                            {
                                requestStruct.setIntField(intIndex++, (Long) request.getFields().get(structFieldName));
                                break;
                            }
                        case FLOAT:
                            {
                                Float value = (Float) request.getFields().get(structFieldName);
                                if (value != null) {
                                    requestStruct.setFloatField(floatIndex++, Double.parseDouble(value.toString()));
                                }
                                break;
                            }
                        case DOUBLE:
                            {
                                Double value = (Double) request.getFields().get(structFieldName);
                                if (value != null) {
                                    requestStruct.setFloatField(floatIndex++, Double.parseDouble(value.toString()));
                                }
                                break;
                            }
                        case BOOLEAN:
                            {
                                requestStruct.setBooleanField(boolIndex++, (Integer) request.getFields().get(structFieldName));
                                break;
                            }
                        default:
                            {
                                throw new UnsupportedFieldTypeException("Error while generating request struct. Field" + " type is not supported : " + fieldType);
                            }
                    }
                }
            }
        }
        bValue = requestStruct;
    } else {
        Map<String, Object> fields = request.getFields();
        if (fields.size() == 1 && fields.containsKey("value")) {
            fieldName = "value";
        }
        if (request.getFields().containsKey(fieldName)) {
            String fieldType = structType.getName();
            switch(fieldType) {
                case STRING:
                    {
                        bValue = new BString((String) request.getFields().get(fieldName));
                        break;
                    }
                case INT:
                    {
                        bValue = new BInteger((Long) request.getFields().get(fieldName));
                        break;
                    }
                case FLOAT:
                    {
                        Float value = (Float) request.getFields().get(fieldName);
                        if (value != null) {
                            bValue = new BFloat(Double.parseDouble(value.toString()));
                        }
                        break;
                    }
                case DOUBLE:
                    {
                        Double value = (Double) request.getFields().get(fieldName);
                        if (value != null) {
                            bValue = new BFloat(Double.parseDouble(value.toString()));
                        }
                        break;
                    }
                case BOOLEAN:
                    {
                        bValue = new BBoolean((Boolean) request.getFields().get(fieldName));
                        break;
                    }
                default:
                    {
                        throw new UnsupportedFieldTypeException("Error while generating request struct. Field " + "type is not supported : " + fieldType);
                    }
            }
        }
    }
    return bValue;
}
Also used : BRefType(org.ballerinalang.model.values.BRefType) BStruct(org.ballerinalang.model.values.BStruct) BValue(org.ballerinalang.model.values.BValue) BString(org.ballerinalang.model.values.BString) BInteger(org.ballerinalang.model.values.BInteger) BBoolean(org.ballerinalang.model.values.BBoolean) UnsupportedFieldTypeException(org.ballerinalang.net.grpc.exception.UnsupportedFieldTypeException) BString(org.ballerinalang.model.values.BString) BStructType(org.ballerinalang.model.types.BStructType) BInteger(org.ballerinalang.model.values.BInteger) BFloat(org.ballerinalang.model.values.BFloat) BType(org.ballerinalang.model.types.BType) BFloat(org.ballerinalang.model.values.BFloat)

Example 32 with BType

use of org.ballerinalang.model.types.BType in project ballerina by ballerina-lang.

the class BidirectionalStreamingListener method invoke.

@Override
public StreamObserver<Message> invoke(StreamObserver<Message> responseObserver) {
    Resource onOpen = resourceMap.get(MessageConstants.ON_OPEN_RESOURCE);
    List<ParamDetail> paramDetails = onOpen.getParamDetails();
    BValue[] signatureParams = new BValue[paramDetails.size()];
    signatureParams[0] = getConnectionParameter(onOpen, responseObserver);
    CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
    Executor.submit(onOpen, callback, null, null, signatureParams);
    return new StreamObserver<Message>() {

        @Override
        public void onNext(Message value) {
            Resource onMessage = resourceMap.get(MessageConstants.ON_MESSAGE_RESOURCE);
            List<ParamDetail> paramDetails = onMessage.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onMessage, responseObserver);
            BValue requestParam = getRequestParameter(onMessage, value);
            if (requestParam != null) {
                signatureParams[1] = requestParam;
            }
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, isEmptyResponse());
            Executor.submit(onMessage, callback, null, null, signatureParams);
        }

        @Override
        public void onError(Throwable t) {
            Resource onError = resourceMap.get(MessageConstants.ON_ERROR_RESOURCE);
            if (onError == null) {
                String message = "Error in listener service definition. onError resource does not exists";
                LOG.error(message);
                throw new RuntimeException(message);
            }
            List<ParamDetail> paramDetails = onError.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onError, responseObserver);
            if (paramDetails.size() != 2) {
                String message = "Error in onError resource definition. It must have two input params, but have " + paramDetails.size();
                LOG.error(message);
                throw new RuntimeException(message);
            }
            BType errorType = paramDetails.get(1).getVarType();
            BStruct errorStruct = MessageUtils.getConnectorError((BStructType) errorType, t);
            signatureParams[1] = errorStruct;
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
            Executor.submit(onError, callback, null, null, signatureParams);
        }

        @Override
        public void onCompleted() {
            Resource onCompleted = resourceMap.get(MessageConstants.ON_COMPLETE_RESOURCE);
            if (onCompleted == null) {
                String message = "Error in listener service definition. onError resource does not exists";
                LOG.error(message);
                throw new RuntimeException(message);
            }
            List<ParamDetail> paramDetails = onCompleted.getParamDetails();
            BValue[] signatureParams = new BValue[paramDetails.size()];
            signatureParams[0] = getConnectionParameter(onCompleted, responseObserver);
            CallableUnitCallback callback = new GrpcCallableUnitCallBack(responseObserver, Boolean.FALSE);
            Executor.submit(onCompleted, callback, null, null, signatureParams);
        }
    };
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) GrpcCallableUnitCallBack(org.ballerinalang.net.grpc.GrpcCallableUnitCallBack) BStruct(org.ballerinalang.model.values.BStruct) Message(org.ballerinalang.net.grpc.Message) BValue(org.ballerinalang.model.values.BValue) Resource(org.ballerinalang.connector.api.Resource) ParamDetail(org.ballerinalang.connector.api.ParamDetail) BType(org.ballerinalang.model.types.BType) CallableUnitCallback(org.ballerinalang.bre.bvm.CallableUnitCallback)

Example 33 with BType

use of org.ballerinalang.model.types.BType in project ballerina by ballerina-lang.

the class JSONUtils method jsonNodeToBArray.

/**
 * Convert a JSON node to an array.
 *
 * @param arrayNode JSON to convert
 * @param targetArrayType Type of the target array
 * @return If the provided JSON is of array type, this method will return a {@link BArrayType} containing the values
 *         of the JSON array. Otherwise the method will throw a {@link BallerinaException}.
 */
@SuppressWarnings("rawtypes")
private static BNewArray jsonNodeToBArray(JsonNode arrayNode, BArrayType targetArrayType) {
    if (!arrayNode.isArray()) {
        throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_TYPE_FOR_CASTING, getComplexObjectTypeName(Type.ARRAY), getTypeName(arrayNode));
    }
    BType elementType = targetArrayType.getElementType();
    BRefValueArray refValueArray;
    switch(elementType.getTag()) {
        case TypeTags.INT_TAG:
            return jsonNodeToBIntArray(arrayNode);
        case TypeTags.FLOAT_TAG:
            return jsonNodeToBFloatArray(arrayNode);
        case TypeTags.STRING_TAG:
            return jsonNodeToBStringArray(arrayNode);
        case TypeTags.BOOLEAN_TAG:
            return jsonNodeToBBooleanArray(arrayNode);
        case TypeTags.ANY_TAG:
            refValueArray = new BRefValueArray(elementType);
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode element = arrayNode.get(i);
                refValueArray.add(i, (BRefType) getBValue(element));
            }
            return refValueArray;
        default:
            refValueArray = new BRefValueArray(elementType);
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode element = arrayNode.get(i);
                if (elementType.getTag() == TypeTags.MAP_TAG) {
                    refValueArray.add(i, jsonNodeToBMap(element, (BMapType) elementType));
                } else if (elementType instanceof BStructType) {
                    refValueArray.add(i, convertJSONNodeToStruct(element, (BStructType) elementType));
                } else if (elementType instanceof BArrayType) {
                    refValueArray.add(i, jsonNodeToBArray(element, (BArrayType) elementType));
                } else {
                    throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_TYPE_FOR_CASTING, elementType, getTypeName(element));
                }
            }
            return refValueArray;
    }
}
Also used : BStructType(org.ballerinalang.model.types.BStructType) BMapType(org.ballerinalang.model.types.BMapType) BArrayType(org.ballerinalang.model.types.BArrayType) BType(org.ballerinalang.model.types.BType) BRefValueArray(org.ballerinalang.model.values.BRefValueArray)

Example 34 with BType

use of org.ballerinalang.model.types.BType in project ballerina by ballerina-lang.

the class JSONUtils method convertStructToJSON.

/**
 * Convert {@link BStruct} to {@link BJSON}.
 *
 * @param struct {@link BStruct} to be converted to {@link BJSON}
 * @return JSON representation of the provided array
 */
@SuppressWarnings("unchecked")
public static BJSON convertStructToJSON(BStruct struct) {
    BJSON bjson = new BJSON(new JsonNode(Type.OBJECT));
    JsonNode jsonNode = bjson.value();
    BStructType structType = (BStructType) struct.getType();
    int longRegIndex = -1;
    int doubleRegIndex = -1;
    int stringRegIndex = -1;
    int booleanRegIndex = -1;
    int refRegIndex = -1;
    for (BStructType.StructField structField : structType.getStructFields()) {
        String key = structField.getFieldName();
        BType fieldType = structField.getFieldType();
        try {
            switch(fieldType.getTag()) {
                case TypeTags.INT_TAG:
                    jsonNode.set(key, struct.getIntField(++longRegIndex));
                    break;
                case TypeTags.FLOAT_TAG:
                    jsonNode.set(key, struct.getFloatField(++doubleRegIndex));
                    break;
                case TypeTags.STRING_TAG:
                    jsonNode.set(key, struct.getStringField(++stringRegIndex));
                    break;
                case TypeTags.BOOLEAN_TAG:
                    jsonNode.set(key, struct.getBooleanField(++booleanRegIndex) == 1);
                    break;
                case TypeTags.BLOB_TAG:
                    throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_TYPE_FOR_CASTING, BTypes.typeJSON, BTypes.typeBlob);
                default:
                    BValue value = struct.getRefField(++refRegIndex);
                    if (value == null) {
                        jsonNode.set(key, new BJSON(NULL).value());
                    } else if (value.getType().getTag() == TypeTags.MAP_TAG) {
                        jsonNode.set(key, convertMapToJSON((BMap<String, BValue>) value).value());
                    } else if (value instanceof BJSON) {
                        jsonNode.set(key, ((BJSON) value).value());
                    } else if (value instanceof BNewArray) {
                        jsonNode.set(key, convertArrayToJSON((BNewArray) value).value());
                    } else if (value instanceof BStruct) {
                        jsonNode.set(key, convertStructToJSON((BStruct) value).value());
                    } else {
                        throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_TYPE_FOR_CASTING, BTypes.typeJSON, value.getType());
                    }
            }
        } catch (Exception e) {
            handleError(e, key);
        }
    }
    return bjson;
}
Also used : BStructType(org.ballerinalang.model.types.BStructType) BStruct(org.ballerinalang.model.values.BStruct) BNewArray(org.ballerinalang.model.values.BNewArray) BMap(org.ballerinalang.model.values.BMap) BType(org.ballerinalang.model.types.BType) BValue(org.ballerinalang.model.values.BValue) BString(org.ballerinalang.model.values.BString) BJSON(org.ballerinalang.model.values.BJSON) BallerinaException(org.ballerinalang.util.exceptions.BallerinaException)

Example 35 with BType

use of org.ballerinalang.model.types.BType in project ballerina by ballerina-lang.

the class ProgramFileReader method getBTypeFromDescriptor.

private BType getBTypeFromDescriptor(String desc) {
    char ch = desc.charAt(0);
    switch(ch) {
        case 'I':
            return BTypes.typeInt;
        case 'F':
            return BTypes.typeFloat;
        case 'S':
            return BTypes.typeString;
        case 'B':
            return BTypes.typeBoolean;
        case 'Y':
            return BTypes.typeDesc;
        case 'L':
            return BTypes.typeBlob;
        case 'A':
            return BTypes.typeAny;
        case 'R':
            return BTypes.getTypeFromName(desc.substring(1, desc.length() - 1));
        case 'M':
            BType constrainedType = getBTypeFromDescriptor(desc.substring(1));
            if (constrainedType == BTypes.typeAny) {
                return BTypes.typeMap;
            } else {
                return new BMapType(constrainedType);
            }
        case 'C':
        case 'X':
        case 'J':
        case 'T':
        case 'E':
        case 'H':
        case 'Z':
        case 'D':
            String typeName = desc.substring(1, desc.length() - 1);
            String[] parts = typeName.split(":");
            if (parts.length == 1) {
                if (ch == 'J') {
                    return BTypes.typeJSON;
                } else if (ch == 'D') {
                    return BTypes.typeTable;
                } else if (ch == 'H') {
                    // TODO:CHECK
                    return BTypes.typeStream;
                }
            }
            String pkgPath = parts[0];
            String name = parts[1];
            PackageInfo packageInfoOfType = programFile.getPackageInfo(pkgPath);
            if (ch == 'J') {
                return new BJSONType(packageInfoOfType.getStructInfo(name).getType());
            } else if (ch == 'C') {
                return packageInfoOfType.getConnectorInfo(name).getType();
            } else if (ch == 'X') {
                return packageInfoOfType.getServiceInfo(name).getType();
            } else if (ch == 'D') {
                return new BTableType(packageInfoOfType.getStructInfo(name).getType());
            } else if (ch == 'H') {
                return new BStreamType(packageInfoOfType.getStructInfo(name).getType());
            } else if (ch == 'E') {
                return packageInfoOfType.getEnumInfo(name).getType();
            } else {
                return packageInfoOfType.getStructInfo(name).getType();
            }
        case '[':
            BType elemType = getBTypeFromDescriptor(desc.substring(1));
            return new BArrayType(elemType);
        case 'U':
            // TODO : Fix this for type casting.
            return new BFunctionType();
        case 'O':
        case 'P':
            Stack<BType> typeStack = new Stack<BType>();
            createBTypeFromSig(desc.toCharArray(), 0, typeStack, null);
            return typeStack.pop();
        case 'N':
            return BTypes.typeNull;
        default:
            throw new ProgramFileFormatException("unsupported base type char: " + ch);
    }
}
Also used : BArrayType(org.ballerinalang.model.types.BArrayType) BJSONType(org.ballerinalang.model.types.BJSONType) BFunctionType(org.ballerinalang.model.types.BFunctionType) ProgramFileFormatException(org.ballerinalang.util.exceptions.ProgramFileFormatException) BStreamType(org.ballerinalang.model.types.BStreamType) Stack(java.util.Stack) BMapType(org.ballerinalang.model.types.BMapType) BType(org.ballerinalang.model.types.BType) BTableType(org.ballerinalang.model.types.BTableType)

Aggregations

BType (org.ballerinalang.model.types.BType)48 BStructType (org.ballerinalang.model.types.BStructType)16 BString (org.ballerinalang.model.values.BString)16 BStruct (org.ballerinalang.model.values.BStruct)15 BValue (org.ballerinalang.model.values.BValue)13 BallerinaException (org.ballerinalang.util.exceptions.BallerinaException)12 BBoolean (org.ballerinalang.model.values.BBoolean)11 BArrayType (org.ballerinalang.model.types.BArrayType)7 BFloat (org.ballerinalang.model.values.BFloat)6 BInteger (org.ballerinalang.model.values.BInteger)6 BMapType (org.ballerinalang.model.types.BMapType)4 BRefType (org.ballerinalang.model.values.BRefType)4 SQLException (java.sql.SQLException)3 Struct (java.sql.Struct)3 ArrayList (java.util.ArrayList)3 CallableUnitCallback (org.ballerinalang.bre.bvm.CallableUnitCallback)3 BBlob (org.ballerinalang.model.values.BBlob)3 Message (org.ballerinalang.net.grpc.Message)3 StructFieldInfo (org.ballerinalang.util.codegen.StructFieldInfo)3 StructInfo (org.ballerinalang.util.codegen.StructInfo)3