diff --git a/bvm/ballerina-core/src/main/resources/MessagesBundle.properties b/bvm/ballerina-core/src/main/resources/MessagesBundle.properties index 68b934a4fc33..3b5a8987fd1d 100644 --- a/bvm/ballerina-core/src/main/resources/MessagesBundle.properties +++ b/bvm/ballerina-core/src/main/resources/MessagesBundle.properties @@ -152,8 +152,8 @@ illegal.format.conversion = illegal format conversion ''{0}'' incompatible.stamp.operation = incompatible stamp operation: ''{0}'' value cannot be stamped as ''{1}'' cannot.stamp.null = cannot stamp ''null'' value to type ''{0}'' cannot.convert.null = cannot convert ''null'' value to type ''{0}'' -incompatible.convert.operation = incompatible convert operation: ''{0}'' value cannot be converted as ''{1}'' -incompatible.simple.type.convert.operation = incompatible convert operation: ''{0}'' value ''{1}'' cannot be converted as ''{2}'' +incompatible.convert.operation = ''{0}'' value cannot be converted to ''{1}'' +incompatible.simple.type.convert.operation = ''{0}'' value ''{1}'' cannot be converted to ''{2}'' unsupported.clone.operation = ''clone()'' not allowed on ''{0}'' invalid.record.field.access = invalid field access: field ''{0}'' not found in record type ''{1}'' invalid.record.field.addition = invalid value for record field ''{0}'': expected value of type ''{1}'', found ''{2}'' diff --git a/bvm/ballerina-core/src/main/resources/MessagesBundle_en_US.properties b/bvm/ballerina-core/src/main/resources/MessagesBundle_en_US.properties index 3f1a6803c453..dbfec157fcb9 100644 --- a/bvm/ballerina-core/src/main/resources/MessagesBundle_en_US.properties +++ b/bvm/ballerina-core/src/main/resources/MessagesBundle_en_US.properties @@ -149,8 +149,8 @@ illegal.format.conversion = illegal format conversion ''{0}'' incompatible.stamp.operation = incompatible stamp operation: ''{0}'' value cannot be stamped as ''{1}'' cannot.stamp.null = cannot stamp ''null'' value to type ''{0}'' cannot.convert.null = cannot convert ''null'' value to type ''{0}'' -incompatible.convert.operation = incompatible convert operation: ''{0}'' value cannot be converted as ''{1}'' -incompatible.simple.type.convert.operation = incompatible convert operation: ''{0}'' value ''{1}'' cannot be converted as ''{2}'' +incompatible.convert.operation = ''{0}'' value cannot be converted to ''{1}'' +incompatible.simple.type.convert.operation = ''{0}'' value ''{1}'' cannot be converted to ''{2}'' unsupported.clone.operation = ''clone()'' not allowed on ''{0}'' invalid.record.field.access = invalid field access: field ''{0}'' not found in record type ''{1}'' invalid.record.field.addition = invalid value for record field ''{0}'': expected value of type ''{1}'', found ''{2}'' diff --git a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/BallerinaErrors.java b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/BallerinaErrors.java index 00b4ed2ed4cc..b9292829aa10 100644 --- a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/BallerinaErrors.java +++ b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/BallerinaErrors.java @@ -72,20 +72,25 @@ public static ErrorValue createConversionError(Object inputValue, BType targetTy TypeChecker.getType(inputValue), targetType)); } - static ErrorValue createTypeCastError(Object sourceVal, BType targetType) { + public static ErrorValue createTypeCastError(Object sourceVal, BType targetType) { throw createError(BallerinaErrorReasons.TYPE_CAST_ERROR, BLangExceptionHelper.getErrorMessage(RuntimeErrors.TYPE_CAST_ERROR, TypeChecker.getType(sourceVal), targetType)); } - static ErrorValue createNumericConversionError(Object inputValue, BType targetType) { + public static ErrorValue createNumericConversionError(Object inputValue, BType targetType) { throw createError(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, BLangExceptionHelper.getErrorMessage( RuntimeErrors.INCOMPATIBLE_SIMPLE_TYPE_CONVERT_OPERATION, TypeChecker.getType(inputValue), inputValue, targetType)); } + public static ErrorValue createNumericConversionError(Object inputValue, BType inputType, BType targetType) { + throw createError(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, BLangExceptionHelper.getErrorMessage( + RuntimeErrors.INCOMPATIBLE_SIMPLE_TYPE_CONVERT_OPERATION, inputType, inputValue, targetType)); + } + static String getErrorMessageFromDetail(MapValueImpl detailMap) { return (String) detailMap.get(ERROR_MESSAGE_FIELD); } diff --git a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeChecker.java b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeChecker.java index 1f5653847a2e..5a4b1be11880 100644 --- a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeChecker.java +++ b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeChecker.java @@ -78,25 +78,43 @@ public static Object checkCast(Object sourceVal, BType targetType) { return sourceVal; } + BType sourceType = getType(sourceVal); + if (sourceType.getTag() <= TypeTags.BOOLEAN_TAG && targetType.getTag() <= TypeTags.BOOLEAN_TAG) { + return TypeConverter.castValues(targetType, sourceVal); + } + + // if the source is a numeric value and the target type is a union, try to find a matching + // member. + if (sourceType.getTag() <= TypeTags.BOOLEAN_TAG && targetType.getTag() == TypeTags.UNION_TAG) { + for (BType memberType : ((BUnionType) targetType).getMemberTypes()) { + try { + return TypeConverter.castValues(memberType, sourceVal); + } catch (Exception e) { + continue; + } + } + } + throw BallerinaErrors.createTypeCastError(sourceVal, targetType); } public static long anyToInt(Object sourceVal) { - return TypeConverter.anyToInt(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, BTypes.typeInt)); + return TypeConverter.anyToIntCast(sourceVal, + () -> BallerinaErrors.createTypeCastError(sourceVal, BTypes.typeInt)); } public static double anyToFloat(Object sourceVal) { - return TypeConverter.anyToFloat(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, + return TypeConverter.anyToFloatCast(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, BTypes.typeFloat)); } public static boolean anyToBoolean(Object sourceVal) { - return TypeConverter.anyToBoolean(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, + return TypeConverter.anyToBooleanCast(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, BTypes.typeBoolean)); } public static int anyToByte(Object sourceVal) { - return TypeConverter.anyToByte(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, + return TypeConverter.anyToByteCast(sourceVal, () -> BallerinaErrors.createTypeCastError(sourceVal, BTypes.typeByte)); } @@ -1122,20 +1140,57 @@ private static boolean isEqual(Object lhsValue, Object rhsValue, List switch (lhsValTypeTag) { case TypeTags.STRING_TAG: + return lhsValue.equals(rhsValue); case TypeTags.FLOAT_TAG: + if (rhsValTypeTag <= TypeTags.FLOAT_TAG) { + return lhsValue.equals(((Number) rhsValue).doubleValue()); + } + + if (rhsValTypeTag == TypeTags.DECIMAL_TAG) { + return DecimalValue.valueOf((double) lhsValue).equals(rhsValue); + } + + return false; case TypeTags.DECIMAL_TAG: - case TypeTags.BOOLEAN_TAG: - return lhsValue.equals(rhsValue); + if (rhsValTypeTag <= TypeTags.FLOAT_TAG) { + return DecimalValue.valueOf(((Number) rhsValue).doubleValue()).equals(lhsValue); + } + + if (rhsValTypeTag == TypeTags.DECIMAL_TAG) { + return ((DecimalValue) rhsValue).equals(lhsValue); + } + + return false; case TypeTags.INT_TAG: - if (rhsValTypeTag != TypeTags.BYTE_TAG && rhsValTypeTag != TypeTags.INT_TAG) { - return false; + if (rhsValTypeTag <= TypeTags.FLOAT_TAG) { + return lhsValue.equals(((Number) rhsValue).longValue()); } - return lhsValue.equals(((Number) rhsValue).longValue()); + + if (rhsValTypeTag == TypeTags.DECIMAL_TAG) { + return DecimalValue.valueOf((long) lhsValue).equals(rhsValue); + } + + return false; case TypeTags.BYTE_TAG: - if (rhsValTypeTag != TypeTags.BYTE_TAG && rhsValTypeTag != TypeTags.INT_TAG) { - return false; + if (rhsValTypeTag <= TypeTags.FLOAT_TAG) { + return ((Number) lhsValue).byteValue() == ((Number) rhsValue).byteValue(); + } + + if (rhsValTypeTag == TypeTags.DECIMAL_TAG) { + return DecimalValue.valueOf((int) lhsValue).equals(rhsValue); } - return ((Number) lhsValue).byteValue() == ((Number) rhsValue).byteValue(); + + return false; + case TypeTags.BOOLEAN_TAG: + if (rhsValTypeTag <= TypeTags.FLOAT_TAG) { + return ((boolean) lhsValue) == (((Number) rhsValue).longValue() == 1); + } + + if (rhsValTypeTag == TypeTags.DECIMAL_TAG) { + return ((boolean) lhsValue) == ((DecimalValue) rhsValue).booleanValue(); + } + + return false; case TypeTags.XML_TAG: return XMLFactory.isEqual((XMLValue) lhsValue, (XMLValue) rhsValue); case TypeTags.TABLE_TAG: diff --git a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeConverter.java b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeConverter.java index 2d553fdea844..a33683ded68f 100644 --- a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeConverter.java +++ b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/TypeConverter.java @@ -45,6 +45,10 @@ */ public class TypeConverter { + private static final String NaN = "NaN"; + private static final String POSITIVE_INFINITY = "Infinity"; + private static final String NEGATIVE_INFINITY = "-Infinity"; + public static Object convertValues(BType targetType, Object inputValue) { BType inputType = TypeChecker.getType(inputValue); switch (targetType.getTag()) { @@ -73,25 +77,41 @@ public static Object convertValues(BType targetType, Object inputValue) { } } + public static Object castValues(BType targetType, Object inputValue) { + switch (targetType.getTag()) { + case TypeTags.INT_TAG: + return anyToIntCast(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeInt)); + case TypeTags.DECIMAL_TAG: + return anyToDecimal(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeDecimal)); + case TypeTags.FLOAT_TAG: + return anyToFloatCast(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeFloat)); + case TypeTags.STRING_TAG: + return anyToStringCast(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeString)); + case TypeTags.BOOLEAN_TAG: + return anyToBooleanCast(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeBoolean)); + case TypeTags.BYTE_TAG: + return anyToByteCast(inputValue, () -> + BallerinaErrors.createTypeCastError(inputValue, BTypes.typeByte)); + default: + throw BallerinaErrors.createTypeCastError(inputValue, targetType); + } + } + static long anyToInt(Object sourceVal, Supplier errorFunc) { if (sourceVal instanceof Long) { return (Long) sourceVal; } else if (sourceVal instanceof Double) { - if (Double.isNaN((Double) sourceVal) || Double.isInfinite((Double) sourceVal)) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeInt); - } - if (!isFloatWithinIntRange((Double) sourceVal)) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeInt); - } - return Math.round((Double) sourceVal); + return floatToInt((double) sourceVal); } else if (sourceVal instanceof Integer) { return ((Integer) sourceVal).longValue(); } else if (sourceVal instanceof Boolean) { return (Boolean) sourceVal ? 1 : 0; } else if (sourceVal instanceof DecimalValue) { - if (!isFloatWithinIntRange(((DecimalValue) sourceVal).floatValue())) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeInt); - } return ((DecimalValue) sourceVal).intValue(); } else if (sourceVal instanceof String) { try { @@ -104,6 +124,22 @@ static long anyToInt(Object sourceVal, Supplier errorFunc) { throw errorFunc.get(); } + static long anyToIntCast(Object sourceVal, Supplier errorFunc) { + if (sourceVal instanceof Long) { + return (Long) sourceVal; + } else if (sourceVal instanceof Double) { + return floatToInt((double) sourceVal); + } else if (sourceVal instanceof Integer) { + return ((Integer) sourceVal).longValue(); + } else if (sourceVal instanceof Boolean) { + return (Boolean) sourceVal ? 1 : 0; + } else if (sourceVal instanceof DecimalValue) { + return ((DecimalValue) sourceVal).intValue(); + } else { + throw errorFunc.get(); + } + } + static double anyToFloat(Object sourceVal, Supplier errorFunc) { if (sourceVal instanceof Long) { return ((Long) sourceVal).doubleValue(); @@ -114,9 +150,6 @@ static double anyToFloat(Object sourceVal, Supplier errorFunc) { } else if (sourceVal instanceof Boolean) { return (Boolean) sourceVal ? 1.0 : 0.0; } else if (sourceVal instanceof DecimalValue) { - if (!isFloatWithinIntRange(((DecimalValue) sourceVal).floatValue())) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeFloat); - } return ((DecimalValue) sourceVal).floatValue(); } else if (sourceVal instanceof String) { try { @@ -129,25 +162,29 @@ static double anyToFloat(Object sourceVal, Supplier errorFunc) { throw errorFunc.get(); } + static double anyToFloatCast(Object sourceVal, Supplier errorFunc) { + if (sourceVal instanceof Long) { + return ((Long) sourceVal).doubleValue(); + } else if (sourceVal instanceof Double) { + return (Double) sourceVal; + } else if (sourceVal instanceof Integer) { + return ((Integer) sourceVal).floatValue(); + } else if (sourceVal instanceof Boolean) { + return (Boolean) sourceVal ? 1.0 : 0.0; + } else if (sourceVal instanceof DecimalValue) { + return ((DecimalValue) sourceVal).floatValue(); + } else { + throw errorFunc.get(); + } + } + static boolean anyToBoolean(Object sourceVal, Supplier errorFunc) { if (sourceVal instanceof Long) { - long val = (Long) sourceVal; - if (val != 1 && val != 0) { - throw errorFunc.get(); - } - return val != 0; + return (long) sourceVal != 0; } else if (sourceVal instanceof Double) { - double val = (Double) sourceVal; - if (val != 1.0 && val != 0.0) { - throw errorFunc.get(); - } return (Double) sourceVal != 0.0; } else if (sourceVal instanceof Integer) { - int val = (int) sourceVal; - if (val != 1 && val != 0) { - throw errorFunc.get(); - } - return val != 0; + return (int) sourceVal != 0; } else if (sourceVal instanceof Boolean) { return (boolean) sourceVal; } else if (sourceVal instanceof DecimalValue) { @@ -163,6 +200,14 @@ static boolean anyToBoolean(Object sourceVal, Supplier errorFunc) { throw errorFunc.get(); } + static boolean anyToBooleanCast(Object sourceVal, Supplier errorFunc) { + if (sourceVal instanceof Boolean) { + return (boolean) sourceVal; + } + + throw errorFunc.get(); + } + public static int intToByte(long sourceVal) { if (!isByteLiteral(sourceVal)) { throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeByte); @@ -170,27 +215,48 @@ public static int intToByte(long sourceVal) { return ((Long) sourceVal).intValue(); } + public static int floatToByte(double sourceVal) { + checkIsValidFloat(sourceVal, BTypes.typeByte); + + long intVal = Math.round(sourceVal); + if (!isByteLiteral(intVal)) { + throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeByte); + } + + return (int) intVal; + } + + public static long floatToInt(double sourceVal) { + checkIsValidFloat(sourceVal, BTypes.typeInt); + + if (!isFloatWithinIntRange(sourceVal)) { + throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeInt); + } + + return Math.round(sourceVal); + } + + private static void checkIsValidFloat(double sourceVal, BType targetType) { + if (Double.isNaN(sourceVal)) { + throw BallerinaErrors.createNumericConversionError(NaN, BTypes.typeFloat, targetType); + } + + if (Double.isInfinite(sourceVal)) { + String value = sourceVal > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY; + throw BallerinaErrors.createNumericConversionError(value, BTypes.typeFloat, targetType); + } + } + static int anyToByte(Object sourceVal, Supplier errorFunc) { if (sourceVal instanceof Long) { return intToByte((Long) sourceVal); } else if (sourceVal instanceof Double) { - Double value = (Double) sourceVal; - if (Double.isNaN(value) || Double.isInfinite(value)) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeByte); - } - long intVal = Math.round(value); - if (!isByteLiteral(intVal)) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeByte); - } - return (int) intVal; + return floatToByte((Double) sourceVal); } else if (sourceVal instanceof Integer) { return (int) sourceVal; } else if (sourceVal instanceof Boolean) { return ((Boolean) sourceVal ? 1 : 0); } else if (sourceVal instanceof DecimalValue) { - if (!isByteLiteral(((DecimalValue) sourceVal).intValue())) { - throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeByte); - } return ((DecimalValue) sourceVal).byteValue(); } else if (sourceVal instanceof String) { try { @@ -203,6 +269,23 @@ static int anyToByte(Object sourceVal, Supplier errorFunc) { throw errorFunc.get(); } + static int anyToByteCast(Object sourceVal, Supplier errorFunc) { + if (sourceVal instanceof Long) { + return intToByte((Long) sourceVal); + } else if (sourceVal instanceof Double) { + return floatToByte((Double) sourceVal); + } else if (sourceVal instanceof Integer) { + return (int) sourceVal; + } else if (sourceVal instanceof Boolean) { + return ((Boolean) sourceVal ? 1 : 0); + } else if (sourceVal instanceof DecimalValue) { + return ((DecimalValue) sourceVal).byteValue(); + } else { + throw errorFunc.get(); + } + + } + private static String anyToString(Object sourceVal) { if (sourceVal instanceof Long) { return Long.toString((Long) sourceVal); @@ -216,11 +299,21 @@ private static String anyToString(Object sourceVal) { return ((DecimalValue) sourceVal).stringValue(); } else if (sourceVal instanceof String) { return (String) sourceVal; + } else if (sourceVal == null) { + return "()"; } throw BallerinaErrors.createNumericConversionError(sourceVal, BTypes.typeString); } + private static String anyToStringCast(Object sourceVal, Supplier errorFunc) { + if (sourceVal instanceof String) { + return (String) sourceVal; + } + + throw errorFunc.get(); + } + static DecimalValue anyToDecimal(Object sourceVal, Supplier errorFunc) { if (sourceVal instanceof Long) { return DecimalValue.valueOf((Long) sourceVal); diff --git a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/values/DecimalValue.java b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/values/DecimalValue.java index b8ad7d28b6ff..4014cb2ef36b 100644 --- a/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/values/DecimalValue.java +++ b/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/values/DecimalValue.java @@ -18,12 +18,11 @@ package org.ballerinalang.jvm.values; +import org.ballerinalang.jvm.BallerinaErrors; import org.ballerinalang.jvm.DecimalValueKind; import org.ballerinalang.jvm.types.BType; import org.ballerinalang.jvm.types.BTypes; import org.ballerinalang.jvm.util.BLangConstants; -import org.ballerinalang.jvm.util.exceptions.BallerinaErrorReasons; -import org.ballerinalang.jvm.util.exceptions.BallerinaException; import java.math.BigDecimal; import java.math.BigInteger; @@ -137,19 +136,15 @@ public BigDecimal decimalValue() { public long intValue() { switch (valueKind) { case NOT_A_NUMBER: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + NaN + "' cannot be converted to 'int'"); + throw BallerinaErrors.createNumericConversionError(NaN, BTypes.typeInt); case NEGATIVE_INFINITY: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + NEGATIVE_INF + "' cannot be converted to 'int'"); + throw BallerinaErrors.createNumericConversionError(NEGATIVE_INF, BTypes.typeInt); case POSITIVE_INFINITY: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + POSITIVE_INF + "' cannot be converted to 'int'"); + throw BallerinaErrors.createNumericConversionError(POSITIVE_INF, BTypes.typeInt); } if (!isDecimalWithinIntRange(value)) { - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "out of range 'decimal' value '" + this.stringValue() + "' cannot be converted to 'int'"); + throw BallerinaErrors.createNumericConversionError(this.stringValue(), BTypes.typeDecimal, BTypes.typeInt); } return Math.round(value.doubleValue()); } @@ -162,20 +157,16 @@ private static boolean isDecimalWithinIntRange(BigDecimal decimalValue) { public int byteValue() { switch (valueKind) { case NOT_A_NUMBER: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + NaN + "' cannot be converted to 'byte'"); + throw BallerinaErrors.createNumericConversionError(NaN, BTypes.typeByte); case NEGATIVE_INFINITY: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + NEGATIVE_INF + "' cannot be converted to 'byte'"); + throw BallerinaErrors.createNumericConversionError(NEGATIVE_INF, BTypes.typeByte); case POSITIVE_INFINITY: - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + POSITIVE_INF + "' cannot be converted to 'byte'"); + throw BallerinaErrors.createNumericConversionError(POSITIVE_INF, BTypes.typeByte); } long intVal = Math.round(this.value.doubleValue()); if (!isByteLiteral(intVal)) { - throw new BallerinaException(BallerinaErrorReasons.NUMBER_CONVERSION_ERROR, - "'decimal' value '" + value + "' cannot be converted to 'byte'"); + throw BallerinaErrors.createNumericConversionError(value, BTypes.typeDecimal, BTypes.typeByte); } return (int) intVal; } diff --git a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_cast_gen.bal b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_cast_gen.bal index db374e8dc39d..9abce5f81564 100644 --- a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_cast_gen.bal +++ b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_cast_gen.bal @@ -78,7 +78,7 @@ function generateCheckCastToInt(jvm:MethodVisitor mv, bir:BType sourceType) { } else if (sourceType is bir:BTypeByte) { mv.visitInsn(I2L); } else if (sourceType is bir:BTypeFloat) { - mv.visitInsn(D2L); + mv.visitMethodInsn(INVOKESTATIC, TYPE_CONVERTER, "floatToInt", "(D)J", false); } else if (sourceType is bir:BTypeAny || sourceType is bir:BTypeAnyData || sourceType is bir:BUnionType || @@ -97,6 +97,8 @@ function generateCheckCastToFloat(jvm:MethodVisitor mv, bir:BType sourceType) { // do nothing } else if (sourceType is bir:BTypeInt) { mv.visitInsn(L2D); + } else if (sourceType is bir:BTypeByte) { + mv.visitInsn(I2D); } else if (sourceType is bir:BTypeAny || sourceType is bir:BTypeAnyData || sourceType is bir:BUnionType || @@ -124,6 +126,8 @@ function generateCheckCastToDecimal(jvm:MethodVisitor mv, bir:BType sourceType) mv.visitMethodInsn(INVOKESTATIC, DECIMAL_VALUE, "valueOf", io:sprintf("(J)L%s;", DECIMAL_VALUE), false); } else if (sourceType is bir:BTypeFloat) { mv.visitMethodInsn(INVOKESTATIC, DECIMAL_VALUE, "valueOf", io:sprintf("(D)L%s;", DECIMAL_VALUE), false); + } else if (sourceType is bir:BTypeByte) { + mv.visitMethodInsn(INVOKESTATIC, DECIMAL_VALUE, "valueOf", io:sprintf("(I)L%s;", DECIMAL_VALUE), false); } else { error err = error(io:sprintf("Casting is not supported from '%s' to 'decimal'", sourceType)); panic err; @@ -173,12 +177,17 @@ function generateCheckCastToBoolean(jvm:MethodVisitor mv, bir:BType sourceType) function generateCheckCastToByte(jvm:MethodVisitor mv, bir:BType sourceType) { if (sourceType is bir:BTypeInt) { mv.visitMethodInsn(INVOKESTATIC, TYPE_CONVERTER, "intToByte", "(J)I", false); + } else if (sourceType is bir:BTypeFloat) { + mv.visitMethodInsn(INVOKESTATIC, TYPE_CONVERTER, "floatToByte", "(D)I", false); + } else if (sourceType is bir:BTypeDecimal) { + mv.visitMethodInsn(INVOKESTATIC, TYPE_CHECKER, "anyToByte", io:sprintf("(L%s;)I", OBJECT), false); } else if (sourceType is bir:BTypeByte) { // do nothing } else if (sourceType is bir:BTypeAny || - sourceType is bir:BTypeAnyData || - sourceType is bir:BUnionType || - sourceType is bir:BFiniteType) { + sourceType is bir:BTypeAnyData || + sourceType is bir:BUnionType || + sourceType is bir:BFiniteType || + sourceType is bir:BJSONType) { mv.visitMethodInsn(INVOKESTATIC, TYPE_CHECKER, "anyToByte", io:sprintf("(L%s;)I", OBJECT), false); } else { error err = error(io:sprintf("Casting is not supported from '%s' to 'byte'", sourceType)); @@ -207,15 +216,8 @@ function generateCheckCastToJSON(jvm:MethodVisitor mv, bir:BType sourceType) { } function generateCheckCastToUnionType(jvm:MethodVisitor mv, bir:BType sourceType, bir:BUnionType targetType) { - if (sourceType is bir:BTypeAny || - sourceType is bir:BTypeAnyData || - sourceType is bir:BUnionType|| - sourceType is bir:BJSONType) { - checkCast(mv, targetType); - } else { - // if value types, then ad box instruction - generateCastToAny(mv, sourceType); - } + generateCastToAny(mv, sourceType); + checkCast(mv, targetType); } function checkCast(jvm:MethodVisitor mv, bir:BType targetType) { @@ -256,21 +258,15 @@ function getTargetClass(bir:BType sourceType, bir:BType targetType) returns stri } function generateCheckCastToFiniteType(jvm:MethodVisitor mv, bir:BType sourceType, bir:BFiniteType targetType) { - if (sourceType is bir:BTypeAny || - sourceType is bir:BTypeAnyData || - sourceType is bir:BUnionType|| - sourceType is bir:BJSONType) { - checkCast(mv, targetType); - } else { - // if value types, then add box instruction - generateCastToAny(mv, sourceType); - } + generateCastToAny(mv, sourceType); + checkCast(mv, targetType); } // ------------------------------------------------------------------ // Generate Cast Methods - Performs cast without type checking // ------------------------------------------------------------------ + function generateCast(jvm:MethodVisitor mv, bir:BType sourceType, bir:BType targetType) { if (targetType is bir:BTypeInt) { generateCastToInt(mv, sourceType); @@ -403,8 +399,9 @@ function generateCastToByte(jvm:MethodVisitor mv, bir:BType sourceType) { } else if (sourceType is bir:BTypeByte) { // do nothing } else if (sourceType is bir:BTypeAny || - sourceType is bir:BTypeAnyData || - sourceType is bir:BUnionType) { + sourceType is bir:BTypeAnyData || + sourceType is bir:BUnionType || + sourceType is bir:BJSONType) { mv.visitMethodInsn(INVOKESTATIC, TYPE_CHECKER, "anyToByte", io:sprintf("(L%s;)I", OBJECT), false); } else { error err = error(io:sprintf("Casting is not supported from '%s' to 'byte'", sourceType)); diff --git a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_constants.bal b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_constants.bal index 81309c6c5ef5..913396c3d90b 100644 --- a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_constants.bal +++ b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_constants.bal @@ -219,7 +219,6 @@ const string LONG_VALUE = "java/lang/Long"; const string BOOLEAN_VALUE = "java/lang/Boolean"; const string DOUBLE_VALUE = "java/lang/Double"; const string DECIMAL_VALUE = "org/ballerinalang/jvm/values/DecimalValue"; -const string BYTE_VALUE = "java/lang/Byte"; const string INT_VALUE = "java/lang/Integer"; const string XML_VALUE = "org/ballerinalang/jvm/values/XMLValue"; const string XML_QNAME = "org/ballerinalang/jvm/values/XMLQName"; diff --git a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_type_gen.bal b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_type_gen.bal index db00bb6e8b21..387b752bef0c 100644 --- a/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_type_gen.bal +++ b/compiler/ballerina-backend-jvm/src/main/ballerina/compiler_backend_jvm/jvm_type_gen.bal @@ -951,6 +951,8 @@ function loadFiniteType(jvm:MethodVisitor mv, bir:BFiniteType finiteType) { if (value is ()) { mv.visitInsn(ACONST_NULL); + } else if (value is bir:Decimal) { + // do nothing } else { mv.visitLdcInsn(value); } @@ -962,7 +964,12 @@ function loadFiniteType(jvm:MethodVisitor mv, bir:BFiniteType finiteType) { } else if (value is float) { mv.visitMethodInsn(INVOKESTATIC, DOUBLE_VALUE, "valueOf", io:sprintf("(D)L%s;", DOUBLE_VALUE), false); } else if (value is byte) { - mv.visitMethodInsn(INVOKESTATIC, BYTE_VALUE, "valueOf", io:sprintf("(B)L%s;", BYTE_VALUE), false); + mv.visitMethodInsn(INVOKESTATIC, INT_VALUE, "valueOf", io:sprintf("(I)L%s;", INT_VALUE), false); + } else if (value is bir:Decimal) { + mv.visitTypeInsn(NEW, DECIMAL_VALUE); + mv.visitInsn(DUP); + mv.visitLdcInsn(value.value); + mv.visitMethodInsn(INVOKESPECIAL, DECIMAL_VALUE, "", io:sprintf("(L%s;)V", STRING_VALUE), false); } else { // if value is string or (), then do nothing } diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java index 342f7cd6b056..63f9aabb964c 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/desugar/Desugar.java @@ -2941,9 +2941,7 @@ public void visit(BLangFunctionVarRef functionVarRef) { @Override public void visit(BLangStructFieldAccessExpr fieldAccessExpr) { - BType expType = fieldAccessExpr.type; - fieldAccessExpr.type = symTable.anyType; - result = addConversionExprIfRequired(fieldAccessExpr, expType); + result = fieldAccessExpr; } @Override diff --git a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java index 63ca40047155..4baa0c52aeed 100644 --- a/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java +++ b/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/TypeChecker.java @@ -2186,7 +2186,11 @@ public void visit(BLangXMLAttributeAccess xmlAttributeAccessExpr) { checkExpr(indexExpr, env, symTable.stringType); if (indexExpr.type.tag == TypeTags.STRING) { - actualType = BUnionType.create(null, symTable.stringType, symTable.nilType); + if (xmlAttributeAccessExpr.lhsVar) { + actualType = symTable.stringType; + } else { + actualType = BUnionType.create(null, symTable.stringType, symTable.nilType); + } } xmlAttributeAccessExpr.namespaces.putAll(symResolver.resolveAllNamespaces(env)); diff --git a/distribution/zip/jballerina/build.gradle b/distribution/zip/jballerina/build.gradle index 31da6c54a8d0..92fbee5e978d 100644 --- a/distribution/zip/jballerina/build.gradle +++ b/distribution/zip/jballerina/build.gradle @@ -105,8 +105,8 @@ dependencies { dist 'org.wso2.staxon:staxon-core:1.2.0.wso2v2' dist 'com.rabbitmq:amqp-client:5.6.0' dist 'com.jcraft:jzlib:1.1.3' - dist 'org.apache.activemq:artemis-core-client:2.6.3' - dist 'org.apache.activemq:artemis-commons:2.6.3' + dist 'org.apache.activemq:artemis-core-client:2.7.0' + dist 'org.apache.activemq:artemis-commons:2.7.0' dist 'io.nats:java-nats-streaming:2.1.0' dist 'io.nats:jnats:2.1.0' dist 'commons-beanutils:commons-beanutils:1.9.3' diff --git a/language-server/modules/langserver-core/src/test/resources/testng.xml b/language-server/modules/langserver-core/src/test/resources/testng.xml index 59c60dfbb665..52c2db5c406a 100644 --- a/language-server/modules/langserver-core/src/test/resources/testng.xml +++ b/language-server/modules/langserver-core/src/test/resources/testng.xml @@ -27,7 +27,7 @@ under the License. - + diff --git a/stdlib/bir/src/main/ballerina/bir/bir_model.bal b/stdlib/bir/src/main/ballerina/bir/bir_model.bal index db51b14f5dfe..efb60157d155 100644 --- a/stdlib/bir/src/main/ballerina/bir/bir_model.bal +++ b/stdlib/bir/src/main/ballerina/bir/bir_model.bal @@ -394,7 +394,7 @@ public type BFutureType record {| public type BFiniteType record {| Name name = {}; int flags; - (int | string | boolean | float | byte| ()) [] values; + (int | string | boolean | float | byte| () | Decimal) [] values; |}; public type BType BTypeInt | BTypeBoolean | BTypeAny | BTypeNil | BTypeByte | BTypeFloat | BTypeString | BUnionType | @@ -440,7 +440,7 @@ public type ConstantLoad record {| InstructionKind kind; VarRef lhsOp; BType typeValue; - int | string | boolean | float | byte | () value; + int | string | boolean | float | byte | () | Decimal value; |}; public type NewMap record {| @@ -739,3 +739,7 @@ public type WaitAll record {| string[] keys; BasicBlock thenBB; |}; + +public type Decimal record {| + string value; +|}; diff --git a/stdlib/bir/src/main/ballerina/bir/bir_pkg_parser.bal b/stdlib/bir/src/main/ballerina/bir/bir_pkg_parser.bal index bd2a3990c9c0..6d6b99d08974 100644 --- a/stdlib/bir/src/main/ballerina/bir/bir_pkg_parser.bal +++ b/stdlib/bir/src/main/ballerina/bir/bir_pkg_parser.bal @@ -438,7 +438,8 @@ function parseLiteralValue(BirChannelReader reader, BType bType) returns anydata } else if (bType is BTypeString) { value = reader.readStringCpRef(); } else if (bType is BTypeDecimal) { - value = reader.readStringCpRef(); + Decimal d = {value : reader.readStringCpRef()}; + value = d; } else if (bType is BTypeBoolean) { value = reader.readBoolean(); } else if (bType is BTypeFloat) { diff --git a/stdlib/bir/src/main/ballerina/bir/type_parser.bal b/stdlib/bir/src/main/ballerina/bir/type_parser.bal index a491298aeec1..84a85e0ac85d 100644 --- a/stdlib/bir/src/main/ballerina/bir/type_parser.bal +++ b/stdlib/bir/src/main/ballerina/bir/type_parser.bal @@ -365,13 +365,15 @@ public type TypeParser object { return finiteType; } - private function getValue(BType valueType) returns (int | string | boolean | float | byte| ()) { + private function getValue(BType valueType) returns (int | string | boolean | float | byte| () | Decimal) { if (valueType is BTypeInt) { return self.readIntCpRef(); } else if (valueType is BTypeByte) { return self.readByteCpRef(); - } else if (valueType is BTypeString || valueType is BTypeDecimal) { + } else if (valueType is BTypeString) { return self.readStringCpRef(); + } else if (valueType is BTypeDecimal) { + return {value: self.readStringCpRef()}; } else if (valueType is BTypeBoolean) { return self.readInt8() == 1; } else if (valueType is BTypeFloat) { diff --git a/stdlib/config-api/src/test/java/org/ballerinalang/stdlib/config/EnvVarConfigTest.java b/stdlib/config-api/src/test/java/org/ballerinalang/stdlib/config/EnvVarConfigTest.java index 76b9cf3e2dc6..f2b19bb8ffc8 100644 --- a/stdlib/config-api/src/test/java/org/ballerinalang/stdlib/config/EnvVarConfigTest.java +++ b/stdlib/config-api/src/test/java/org/ballerinalang/stdlib/config/EnvVarConfigTest.java @@ -171,16 +171,14 @@ public void testNonExistentEnvVarLookupForBoolean() { } @Test(expectedExceptions = BLangRuntimeException.class, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'string' value 'b7auser' cannot be " - + "converted as 'int'.*") + expectedExceptionsMessageRegExp = ".*'string' value 'b7auser' cannot be converted to 'int'.*") public void testInvalidIntEnvVarLookup() { BString key = new BString("user.name"); BRunUtil.invoke(compileResult, "testGetAsInt", new BValue[]{key}); } @Test(expectedExceptions = BLangRuntimeException.class, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'string' value 'b7auser' cannot be " - + "converted as 'float'.*") + expectedExceptionsMessageRegExp = ".*'string' value 'b7auser' cannot be converted to 'float'.*") public void testInvalidFloatEnvVarLookup() { BString key = new BString("user.name"); BRunUtil.invoke(compileResult, "testGetAsFloat", new BValue[]{key}); diff --git a/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BasicAuthHandlerTest.java b/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BasicAuthHandlerTest.java index 79c515efeaf1..0476dff218ca 100644 --- a/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BasicAuthHandlerTest.java +++ b/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BasicAuthHandlerTest.java @@ -18,11 +18,11 @@ package org.ballerinalang.stdlib.auth; -import org.ballerinalang.launcher.util.BCompileUtil; -import org.ballerinalang.launcher.util.BRunUtil; -import org.ballerinalang.launcher.util.CompileResult; import org.ballerinalang.model.values.BBoolean; import org.ballerinalang.model.values.BValue; +import org.ballerinalang.test.util.BCompileUtil; +import org.ballerinalang.test.util.BRunUtil; +import org.ballerinalang.test.util.CompileResult; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BearerAuthHandlerTest.java b/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BearerAuthHandlerTest.java index 73ffbdec1417..caf87a88c5c9 100644 --- a/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BearerAuthHandlerTest.java +++ b/stdlib/http/src/test/java/org/ballerinalang/stdlib/auth/BearerAuthHandlerTest.java @@ -18,11 +18,11 @@ package org.ballerinalang.stdlib.auth; -import org.ballerinalang.launcher.util.BCompileUtil; -import org.ballerinalang.launcher.util.BRunUtil; -import org.ballerinalang.launcher.util.CompileResult; import org.ballerinalang.model.values.BBoolean; import org.ballerinalang.model.values.BValue; +import org.ballerinalang.test.util.BCompileUtil; +import org.ballerinalang.test.util.BRunUtil; +import org.ballerinalang.test.util.CompileResult; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/stdlib/http/src/test/resources/testng.xml b/stdlib/http/src/test/resources/testng.xml index f065c04ea47d..1662fe4168b9 100644 --- a/stdlib/http/src/test/resources/testng.xml +++ b/stdlib/http/src/test/resources/testng.xml @@ -51,11 +51,7 @@ under the License. - - diff --git a/stdlib/messaging/activemq-artemis/build.gradle b/stdlib/messaging/activemq-artemis/build.gradle index 7f0bec6e7d68..0018d97515c6 100644 --- a/stdlib/messaging/activemq-artemis/build.gradle +++ b/stdlib/messaging/activemq-artemis/build.gradle @@ -17,6 +17,12 @@ apply from: "$rootDir/gradle/balNativeLibProject.gradle" +configurations.testCompileClasspath { + resolutionStrategy { + preferProjectModules() + } +} + configurations.all { resolutionStrategy.preferProjectModules() } @@ -35,6 +41,7 @@ dependencies { implementation project(':ballerina-runtime-api') implementation project(':ballerina-utils') implementation project(':ballerina-launcher') + implementation project(':ballerina-runtime') implementation 'org.apache.activemq:artemis-core-client' baloImplementation project(path: ':ballerina-io', configuration: 'baloImplementation') @@ -48,6 +55,18 @@ dependencies { baloImplementation project(path: ':ballerina-utils', configuration: 'baloImplementation') testCompile 'org.testng:testng' + testCompile project(':ballerina-encoding') + testCompile project(':ballerina-internal') + testCompile project(':ballerina-reflect') + testCompile project(':ballerina-jvm') + testCompile project(path: ':ballerina-test-utils', configuration: 'shadow')} + +createBalo { + jvmTarget = 'true' +} + +configurations.all { + resolutionStrategy.preferProjectModules() } description = 'Ballerina - ActiveMQ Artemis' diff --git a/stdlib/messaging/activemq-artemis/src/main/ballerina/artemis/listener.bal b/stdlib/messaging/activemq-artemis/src/main/ballerina/artemis/listener.bal index b0c327bb1440..e7dfd3b57bc8 100644 --- a/stdlib/messaging/activemq-artemis/src/main/ballerina/artemis/listener.bal +++ b/stdlib/messaging/activemq-artemis/src/main/ballerina/artemis/listener.bal @@ -115,7 +115,7 @@ public type Consumer client object { check self.createConsumer(sessObj, config, autoAck, filter); } - private function createConsumer(Session sessObj, QueueConfiguration config, boolean autoAck, string? filter) - returns error? = external; - public remote function receive(int timeoutInMilliSeconds = 0) returns @tainted Message | error = external; + private function createConsumer(Session sessionObj, QueueConfiguration queueConfig, boolean autoAck, + string? consumerFilter) returns error? = external; + public remote function receive(int timeoutInMilliSeconds = 0) returns @tainted Message | error = external; }; diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisConnectorException.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisConnectorException.java index dded3c5ded95..97d684e2d0d1 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisConnectorException.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisConnectorException.java @@ -18,8 +18,7 @@ package org.ballerinalang.messaging.artemis; -import org.ballerinalang.bre.Context; -import org.ballerinalang.util.exceptions.BallerinaException; +import org.ballerinalang.jvm.util.exceptions.BallerinaException; /** * BallerinaException that could occur in Artemis connector. @@ -38,16 +37,6 @@ public ArtemisConnectorException(String message) { super(message); } - /** - * Constructs a new {@link ArtemisConnectorException} with error message and ballerina context. - * - * @param message Error message - * @param context Ballerina context - */ - public ArtemisConnectorException(String message, Context context) { - super(message, context); - } - /** * Constructs a new {@link ArtemisConnectorException} with the specified detail message and cause. * @@ -58,18 +47,6 @@ public ArtemisConnectorException(String message, Throwable cause) { super(message, cause); } - /** - * Constructs a new {@link ArtemisConnectorException} with the specified detail message, - * cause and ballerina context. - * - * @param message Error message - * @param cause Cause - * @param context Ballerina context - */ - public ArtemisConnectorException(String message, Throwable cause, Context context) { - super(message, cause, context); - } - /** * Constructs a new {@link ArtemisConnectorException} with the cause. * @@ -78,13 +55,4 @@ public ArtemisConnectorException(String message, Throwable cause, Context contex public ArtemisConnectorException(Throwable cause) { super(cause); } - - /** - * Constructs a new {@link ArtemisConnectorException} with ballerina context. - * - * @param stack Ballerina context - */ - public ArtemisConnectorException(Context stack) { - super(stack); - } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisTransactionContext.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisTransactionContext.java index a9c587a6e5ed..bb82f76f91f4 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisTransactionContext.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisTransactionContext.java @@ -21,49 +21,34 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.client.ClientSession; -import org.ballerinalang.bre.Context; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.util.exceptions.BallerinaException; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.util.transactions.BallerinaTransactionContext; -import org.ballerinalang.util.transactions.TransactionLocalContext; -import org.ballerinalang.util.transactions.TransactionResourceManager; - -import java.util.Objects; -import java.util.UUID; import javax.transaction.xa.XAResource; +//Todo: fix this class when transaction supported + /** * Session wrapper class with Ballerina transaction logic. */ public class ArtemisTransactionContext implements BallerinaTransactionContext { - private final String connectorId; +// private final String connectorId; private ClientSession session; - private BMap sessionObj; + private ObjectValue sessionObj; - public ArtemisTransactionContext(BMap sessionObj) { + public ArtemisTransactionContext(ObjectValue sessionObj) { this.sessionObj = sessionObj; session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); - connectorId = UUID.randomUUID().toString(); +// connectorId = UUID.randomUUID().toString(); } @Override public void commit() { - try { - session.commit(); - } catch (ActiveMQException e) { - throw new BallerinaException("Transaction commit failed: " + e.getMessage(), e); - } + } @Override public void rollback() { - try { - session.rollback(); - } catch (ActiveMQException e) { - throw new BallerinaException("Transaction rollback failed: " + e.getMessage(), e); - } } @Override @@ -77,30 +62,30 @@ public XAResource getXAResource() { return null; } - public void handleTransactionBlock(Context context, String objectType) { - if (!context.isInTransaction()) { + public void handleTransactionBlock(String objectType) { +// if (!context.isInTransaction()) { if (ArtemisUtils.isAnonymousSession(sessionObj)) { try { session.commit(); return; } catch (ActiveMQException e) { - throw new ArtemisConnectorException("Session commit failed: " + e.getMessage(), e, context); + throw new ArtemisConnectorException("Session commit failed: " + e.getMessage(), e); } - } else { + /* } else { throw new ArtemisConnectorException("The Session used by the Artemis " + objectType + " object is transacted. Hence " + objectType + - " transacted actions cannot be used outside a transaction" + - " block", context); - } + " transacted actions cannot be used outside a transaction block"); + }*/ } - TransactionLocalContext transactionLocalContext = context.getLocalTransactionInfo(); + //Todo: fix after transaction becomes available + /*TransactionLocalContext transactionLocalContext = context.getLocalTransactionInfo(); BallerinaTransactionContext txContext = transactionLocalContext.getTransactionContext(connectorId); if (Objects.isNull(txContext)) { transactionLocalContext.registerTransactionContext(connectorId, this); String globalTxId = transactionLocalContext.getGlobalTransactionId(); String currentTxBlockId = transactionLocalContext.getCurrentTransactionBlockId(); TransactionResourceManager.getInstance().register(globalTxId, currentTxBlockId, this); - } + }*/ } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisUtils.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisUtils.java index fbad311964cb..1024d2ed7ba8 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisUtils.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/ArtemisUtils.java @@ -27,19 +27,12 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.reader.BytesMessageUtil; -import org.ballerinalang.bre.Context; -import org.ballerinalang.bre.bvm.BLangVMErrors; -import org.ballerinalang.connector.api.BLangConnectorSPIUtil; -import org.ballerinalang.model.types.BTypes; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BByte; -import org.ballerinalang.model.values.BError; -import org.ballerinalang.model.values.BFloat; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.model.values.BValueArray; +import org.ballerinalang.jvm.BallerinaErrors; +import org.ballerinalang.jvm.BallerinaValues; +import org.ballerinalang.jvm.values.ArrayValue; +import org.ballerinalang.jvm.values.ErrorValue; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.util.exceptions.BallerinaException; import org.slf4j.Logger; @@ -54,59 +47,55 @@ public class ArtemisUtils { * Util function to throw a {@link BallerinaException}. * * @param message the error message - * @param context the Ballerina context * @param exception the exception to be propagated * @param logger the logger to log errors */ - public static void throwException(String message, Context context, Exception exception, Logger logger) { + public static void throwException(String message, Exception exception, Logger logger) { logger.error(message, exception); - throw new ArtemisConnectorException(message, exception, context); + throw new ArtemisConnectorException(message, exception); } /** * Get error struct. * - * @param context Represent ballerina context - * @param errMsg Error message + * @param errMsg Error message * @return Error struct */ - public static BError getError(Context context, String errMsg) { - BMap artemisErrorRecord = createArtemisErrorRecord(context); - artemisErrorRecord.put(ArtemisConstants.ARTEMIS_ERROR_MESSAGE, new BString(errMsg)); - return BLangVMErrors.createError(context, true, BTypes.typeError, ArtemisConstants.ARTEMIS_ERROR_CODE, - artemisErrorRecord); + public static ErrorValue getError(String errMsg) { + MapValue artemisErrorRecord = createArtemisErrorRecord(); + artemisErrorRecord.put(ArtemisConstants.ARTEMIS_ERROR_MESSAGE, errMsg); + return BallerinaErrors.createError(ArtemisConstants.ARTEMIS_ERROR_CODE, artemisErrorRecord); } - private static BMap createArtemisErrorRecord(Context context) { - return BLangConnectorSPIUtil.createBStruct(context, ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, - ArtemisConstants.ARTEMIS_ERROR_RECORD); + private static MapValue createArtemisErrorRecord() { + return BallerinaValues.createRecordValue(ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, + ArtemisConstants.ARTEMIS_ERROR_RECORD); } /** * Get error struct from throwable. * - * @param context Represent ballerina context * @param exception Throwable representing the error. * @return Error struct */ - public static BError getError(Context context, Exception exception) { + public static ErrorValue getError(Exception exception) { if (exception.getMessage() == null) { - return getError(context, "Artemis connector error"); + return getError("Artemis connector error"); } else { - return getError(context, exception.getMessage()); + return getError(exception.getMessage()); } } /** - * Gets an int from the {@link BMap} config. + * Gets an int from the {@link MapValue} config. * - * @param config the BMap config + * @param config the config * @param key the key that has an integer value * @param logger the logger to log errors * @return the relevant int value from the config */ - public static int getIntFromConfig(BMap config, String key, Logger logger) { - return getIntFromLong(((BInteger) config.get(key)).intValue(), key, logger); + public static int getIntFromConfig(MapValue config, String key, Logger logger) { + return getIntFromLong(config.getIntValue(key), key, logger); } /** @@ -133,33 +122,19 @@ public static int getIntFromLong(long longVal, String name, Logger logger) { /** * Get the relevant BValure for an Object. * - * @param obj the Object - * @param context the Ballerina context to to be used in case of errors + * @param obj the Object * @return the relevant BValue for the object or error */ - public static BValue getBValueFromObj(Object obj, Context context) { - if (obj instanceof String) { - return new BString((String) obj); + public static Object getValidObj(Object obj) { + if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Short || + obj instanceof Float || obj instanceof Double || obj instanceof Boolean || obj instanceof Byte) { + return obj; } else if (obj instanceof SimpleString) { - return new BString(((SimpleString) obj).toString()); - } else if (obj instanceof Integer) { - return new BInteger((int) obj); - } else if (obj instanceof Long) { - return new BInteger((long) obj); - } else if (obj instanceof Short) { - return new BInteger((short) obj); - } else if (obj instanceof Float) { - return new BFloat((float) obj); - } else if (obj instanceof Double) { - return new BFloat((double) obj); - } else if (obj instanceof Boolean) { - return new BBoolean((boolean) obj); - } else if (obj instanceof Byte) { - return new BByte((byte) obj); + return obj.toString(); } else if (obj instanceof byte[]) { - return new BValueArray((byte[]) obj); + return new ArrayValue((byte[]) obj); } else { - return ArtemisUtils.getError(context, "Unsupported type"); + return ArtemisUtils.getError("Unsupported type"); } } @@ -179,9 +154,8 @@ public static RoutingType getRoutingTypeFromString(String routingType) { * @param obj the Ballerina object as a BMap * @return the natively stored {@link ClientSession} */ - public static ClientSession getClientSessionFromBMap(BMap obj) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) obj.get(ArtemisConstants.SESSION); + public static ClientSession getClientSessionFromBMap(ObjectValue obj) { + ObjectValue sessionObj = obj.getObjectValue(ArtemisConstants.SESSION); return (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); } @@ -192,10 +166,10 @@ public static ClientSession getClientSessionFromBMap(BMap obj) { * @param obj the Ballerina object as a BMap * @throws ActiveMQException on session closure failure */ - public static void closeIfAnonymousSession(BMap obj) throws ActiveMQException { + public static void closeIfAnonymousSession(ObjectValue obj) throws ActiveMQException { @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) obj.get(ArtemisConstants.SESSION); - boolean anonymousSession = ((BBoolean) sessionObj.get("anonymousSession")).booleanValue(); + ObjectValue sessionObj = obj.getObjectValue(ArtemisConstants.SESSION); + boolean anonymousSession = sessionObj.getBooleanValue("anonymousSession"); if (anonymousSession) { ClientSession session = ArtemisUtils.getClientSessionFromBMap(obj); if (!session.isClosed()) { @@ -208,14 +182,14 @@ public static void closeIfAnonymousSession(BMap obj) throws Acti * Get only the required bytes data from the BValueArray. This utility function is required because the byte array * can have 100 elements if it is unbounded in the Ballerina code. * - * @param bytesArray The {@link BValue} with the bytes array + * @param bytesArray The {@link ArrayValue} with the bytes array * @return the bytes from the BValue object */ - public static byte[] getBytesData(BValueArray bytesArray) { - return Arrays.copyOf(bytesArray.getBytes(), (int) bytesArray.size()); + public static byte[] getBytesData(ArrayValue bytesArray) { + return Arrays.copyOf(bytesArray.getBytes(), bytesArray.size()); } - public static ClientConsumer getClientConsumer(BMap bObj, ClientSession session, + public static ClientConsumer getClientConsumer(ObjectValue bObj, ClientSession session, String consumerFilter, String queueName, SimpleString addressName, boolean autoCreated, String routingType, boolean temporary, String queueFilter, boolean durable, @@ -251,55 +225,65 @@ public static ClientConsumer getClientConsumer(BMap bObj, Client return consumer; } - public static boolean isAnonymousSession(BMap sessionObj) { - return ((BBoolean) sessionObj.get("anonymousSession")).booleanValue(); + public static boolean isAnonymousSession(ObjectValue sessionObj) { + return sessionObj.getBooleanValue("anonymousSession"); } - public static BValue getBArrayValue(ClientMessage message) { + public static ArrayValue getArrayValue(ClientMessage message) { ActiveMQBuffer msgBuffer = message.getBodyBuffer(); byte[] bytes = new byte[msgBuffer.readableBytes()]; BytesMessageUtil.bytesReadBytes(msgBuffer, bytes); - return new BValueArray(bytes); + return new ArrayValue(bytes); } public static void populateMessageObj(ClientMessage clientMessage, Object transactionContext, - BMap messageObj) { + ObjectValue messageObj) { @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageConfigObj = (BMap) messageObj.get(ArtemisConstants.MESSAGE_CONFIG); + MapValue messageConfigObj = (MapValue) messageObj.get( + ArtemisConstants.MESSAGE_CONFIG); populateMessageConfigObj(clientMessage, messageConfigObj); messageObj.addNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT, transactionContext); messageObj.addNativeData(ArtemisConstants.ARTEMIS_MESSAGE, clientMessage); } - private static void populateMessageConfigObj(ClientMessage clientMessage, BMap messageConfigObj) { - messageConfigObj.put(ArtemisConstants.EXPIRATION, new BInteger(clientMessage.getExpiration())); - messageConfigObj.put(ArtemisConstants.TIME_STAMP, new BInteger(clientMessage.getTimestamp())); - messageConfigObj.put(ArtemisConstants.PRIORITY, new BByte(clientMessage.getPriority())); - messageConfigObj.put(ArtemisConstants.DURABLE, new BBoolean(clientMessage.isDurable())); + private static void populateMessageConfigObj(ClientMessage clientMessage, + MapValue messageConfigObj) { + messageConfigObj.put(ArtemisConstants.EXPIRATION, clientMessage.getExpiration()); + messageConfigObj.put(ArtemisConstants.TIME_STAMP, clientMessage.getTimestamp()); + messageConfigObj.put(ArtemisConstants.PRIORITY, clientMessage.getPriority()); + messageConfigObj.put(ArtemisConstants.DURABLE, clientMessage.isDurable()); setRoutingTypeToConfig(messageConfigObj, clientMessage); if (clientMessage.getGroupID() != null) { - messageConfigObj.put(ArtemisConstants.GROUP_ID, new BString(clientMessage.getGroupID().toString())); + messageConfigObj.put(ArtemisConstants.GROUP_ID, clientMessage.getGroupID().toString()); } - messageConfigObj.put(ArtemisConstants.GROUP_SEQUENCE, new BInteger(clientMessage.getGroupSequence())); + messageConfigObj.put(ArtemisConstants.GROUP_SEQUENCE, clientMessage.getGroupSequence()); if (clientMessage.getCorrelationID() != null) { - messageConfigObj.put(ArtemisConstants.CORRELATION_ID, - new BString(clientMessage.getCorrelationID().toString())); + messageConfigObj.put(ArtemisConstants.CORRELATION_ID, clientMessage.getCorrelationID().toString()); } if (clientMessage.getReplyTo() != null) { - messageConfigObj.put(ArtemisConstants.REPLY_TO, new BString(clientMessage.getReplyTo().toString())); + messageConfigObj.put(ArtemisConstants.REPLY_TO, clientMessage.getReplyTo().toString()); } } - public static void setRoutingTypeToConfig(BMap msgConfigObj, ClientMessage message) { + private static void setRoutingTypeToConfig(MapValue msgConfigObj, ClientMessage message) { byte routingType = message.getType(); if (routingType == RoutingType.MULTICAST.getType()) { - msgConfigObj.put(ArtemisConstants.ROUTING_TYPE, new BString(ArtemisConstants.MULTICAST)); + msgConfigObj.put(ArtemisConstants.ROUTING_TYPE, ArtemisConstants.MULTICAST); } else if (routingType == RoutingType.ANYCAST.getType()) { - msgConfigObj.put(ArtemisConstants.ROUTING_TYPE, new BString(ArtemisConstants.ANYCAST)); + msgConfigObj.put(ArtemisConstants.ROUTING_TYPE, ArtemisConstants.ANYCAST); } } + public static String getStringFromObjOrNull(Object value) { + return value != null ? (String) value : null; + } + + public static String getAddressName(MapValue queueConfig, String queueName) { + Object addressName = queueConfig.get(ArtemisConstants.ADDRESS_NAME); + return addressName != null ? (String) addressName : queueName; + } + private ArtemisUtils() { } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/Close.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/Close.java index d9bb78b1d4eb..f8bde8af34d5 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/Close.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/Close.java @@ -23,10 +23,10 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -49,10 +49,11 @@ ) public class Close extends BlockingNativeCallableUnit { - @Override public void execute(Context context) { + } + + public static void close(Strand strand, ObjectValue connection) { @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap connection = (BMap) context.getRefArgument(0); ServerLocator connectionPool = (ServerLocator) connection.getNativeData( ArtemisConstants.ARTEMIS_CONNECTION_POOL); ClientSessionFactory sessionFactory = diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/CreateConnection.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/CreateConnection.java index ea6cfb07f775..f7ea6dca47cd 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/CreateConnection.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/CreateConnection.java @@ -24,14 +24,12 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BFloat; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.slf4j.Logger; @@ -47,41 +45,31 @@ orgName = ArtemisConstants.BALLERINA, packageName = ArtemisConstants.ARTEMIS, functionName = "createConnection", receiver = @Receiver(type = TypeKind.OBJECT, structType = ArtemisConstants.CONNECTION_OBJ, - structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS), - args = { - @Argument(name = "url", type = TypeKind.STRING), - @Argument(name = "config", type = TypeKind.RECORD, structType = "ConnectionConfiguration") - } + structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS) ) public class CreateConnection extends BlockingNativeCallableUnit { private static final Logger logger = LoggerFactory.getLogger(CreateConnection.class); @Override public void execute(Context context) { - try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap connection = (BMap) context.getRefArgument(0); - - String url = context.getStringArgument(0); + } - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap configObj = (BMap) context.getRefArgument(1); - long connectionTTL = ((BInteger) configObj.get(ArtemisConstants.TIME_TO_LIVE)).intValue(); - long callTimeout = ((BInteger) configObj.get(ArtemisConstants.CALL_TIMEOUT)).intValue(); + public static void createConnection(Strand strand, ObjectValue connection, String url, MapValue config) { + try { + long connectionTTL = config.getIntValue(ArtemisConstants.TIME_TO_LIVE); + long callTimeout = config.getIntValue(ArtemisConstants.CALL_TIMEOUT); int consumerWindowSize = ArtemisUtils.getIntFromConfig( - configObj, ArtemisConstants.CONSUMER_WINDOW_SIZE, logger); - int consumerMaxRate = ArtemisUtils.getIntFromConfig(configObj, ArtemisConstants.CONSUMER_MAX_RATE, logger); + config, ArtemisConstants.CONSUMER_WINDOW_SIZE, logger); + int consumerMaxRate = ArtemisUtils.getIntFromConfig(config, ArtemisConstants.CONSUMER_MAX_RATE, logger); int producerWindowSize = ArtemisUtils.getIntFromConfig( - configObj, ArtemisConstants.PRODUCER_WINDOW_SIZE, logger); - int producerMaxRate = ArtemisUtils.getIntFromConfig(configObj, ArtemisConstants.PRODUCER_MAX_RATE, logger); - long retryInterval = ((BInteger) configObj.get(ArtemisConstants.RETRY_INTERVAL)).intValue(); - double retryIntervalMultiplier = ((BFloat) configObj.get( - ArtemisConstants.RETRY_INTERVAL_MULTIPLIER)).floatValue(); - long maxRetryInterval = ((BInteger) configObj.get(ArtemisConstants.MAX_RETRY_INTERVAL)).intValue(); - int reconnectAttempts = ArtemisUtils.getIntFromConfig( - configObj, ArtemisConstants.RECONNECT_ATTEMPTS, logger); + config, ArtemisConstants.PRODUCER_WINDOW_SIZE, logger); + int producerMaxRate = ArtemisUtils.getIntFromConfig(config, ArtemisConstants.PRODUCER_MAX_RATE, logger); + long retryInterval = config.getIntValue(ArtemisConstants.RETRY_INTERVAL); + double retryIntervalMultiplier = config.getFloatValue(ArtemisConstants.RETRY_INTERVAL_MULTIPLIER); + long maxRetryInterval = config.getIntValue(ArtemisConstants.MAX_RETRY_INTERVAL); + int reconnectAttempts = ArtemisUtils.getIntFromConfig(config, ArtemisConstants.RECONNECT_ATTEMPTS, logger); int initialConnectAttempts = ArtemisUtils.getIntFromConfig( - configObj, ArtemisConstants.INITIAL_CONNECT_ATTEMPTS, logger); + config, ArtemisConstants.INITIAL_CONNECT_ATTEMPTS, logger); ServerLocator connectionPool = ActiveMQClient.createServerLocator(url); @@ -105,7 +93,8 @@ public void execute(Context context) { connection.addNativeData(ArtemisConstants.ARTEMIS_SESSION_FACTORY, factory); } catch (Exception e) { //catching Exception as it is thrown by the createSessionFactory method - ArtemisUtils.throwException("Error occurred while starting connection.", context, e, logger); + ArtemisUtils.throwException("Error occurred while starting connection.", e, logger); } } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/IsClosed.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/IsClosed.java index 92a23646bcbb..81a508bdeb22 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/IsClosed.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/connection/IsClosed.java @@ -22,11 +22,10 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -47,10 +46,11 @@ public class IsClosed extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap connection = (BMap) context.getRefArgument(0); + } + + public static boolean isClosed(Strand strand, ObjectValue connection) { ClientSessionFactory sessionFactory = (ClientSessionFactory) connection.getNativeData(ArtemisConstants.ARTEMIS_SESSION_FACTORY); - context.setReturnValues(new BBoolean(sessionFactory.isClosed())); + return sessionFactory.isClosed(); } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisMessageHandler.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisMessageHandler.java index d61be787a9a1..83bbffb23cd5 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisMessageHandler.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisMessageHandler.java @@ -25,38 +25,32 @@ import org.apache.activemq.artemis.api.core.client.MessageHandler; import org.apache.activemq.artemis.reader.MapMessageUtil; import org.apache.activemq.artemis.reader.TextMessageUtil; -import org.ballerinalang.connector.api.BLangConnectorSPIUtil; -import org.ballerinalang.connector.api.Executor; -import org.ballerinalang.connector.api.ParamDetail; -import org.ballerinalang.connector.api.Resource; +import org.ballerinalang.jvm.BallerinaValues; +import org.ballerinalang.jvm.JSONParser; +import org.ballerinalang.jvm.JSONUtils; +import org.ballerinalang.jvm.Scheduler; +import org.ballerinalang.jvm.XMLFactory; +import org.ballerinalang.jvm.XMLNodeType; +import org.ballerinalang.jvm.types.AttachedFunction; +import org.ballerinalang.jvm.types.BArrayType; +import org.ballerinalang.jvm.types.BMapType; +import org.ballerinalang.jvm.types.BStructureType; +import org.ballerinalang.jvm.types.BType; +import org.ballerinalang.jvm.types.BTypes; +import org.ballerinalang.jvm.types.TypeTags; +import org.ballerinalang.jvm.values.ArrayValue; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.MapValueImpl; +import org.ballerinalang.jvm.values.ObjectValue; +import org.ballerinalang.jvm.values.XMLValue; +import org.ballerinalang.jvm.values.connector.Executor; import org.ballerinalang.messaging.artemis.ArtemisConnectorException; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; -import org.ballerinalang.model.types.BArrayType; -import org.ballerinalang.model.types.BMapType; -import org.ballerinalang.model.types.BStructureType; -import org.ballerinalang.model.types.BType; -import org.ballerinalang.model.types.BTypes; -import org.ballerinalang.model.types.TypeTags; -import org.ballerinalang.model.util.JSONUtils; -import org.ballerinalang.model.util.JsonParser; -import org.ballerinalang.model.util.XMLNodeType; -import org.ballerinalang.model.util.XMLUtils; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BByte; -import org.ballerinalang.model.values.BFloat; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.model.values.BValueArray; -import org.ballerinalang.model.values.BXML; -import org.ballerinalang.util.codegen.ProgramFile; import org.ballerinalang.util.exceptions.BallerinaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -68,45 +62,54 @@ class ArtemisMessageHandler implements MessageHandler { private static final Logger logger = LoggerFactory.getLogger(ArtemisMessageHandler.class); - private Resource onMessageResource; - private BMap sessionObj; + private AttachedFunction onMessageResource; + private ObjectValue sessionObj; private boolean autoAck; + private Scheduler scheduler; + private ObjectValue service; - ArtemisMessageHandler(Resource onMessageResource, BMap sessionObj, boolean autoAck) { - this.onMessageResource = onMessageResource; + ArtemisMessageHandler(Scheduler scheduler, ObjectValue service, ObjectValue sessionObj, boolean autoAck) { this.sessionObj = sessionObj; this.autoAck = autoAck; + this.scheduler = scheduler; + this.service = service; + onMessageResource = service.getType().getAttachedFunctions()[0]; } @Override public void onMessage(ClientMessage clientMessage) { - List paramDetails = onMessageResource.getParamDetails(); - int paramSize = paramDetails.size(); - if (paramSize > 1) { - dispatchResourceWithDataBinding(clientMessage, paramDetails); + BType[] parameterTypes = onMessageResource.getParameterType(); + if (parameterTypes.length > 1) { + dispatchResourceWithDataBinding(clientMessage, parameterTypes); } else { - dispatchResource(clientMessage, createAndGetMessageObj(onMessageResource, clientMessage, sessionObj)); + Object[] signatureParams = new Object[parameterTypes.length * 2]; + signatureParams[0] = createAndGetMessageObj(clientMessage, sessionObj); + signatureParams[1] = true; + dispatchResource(clientMessage, signatureParams); } } - private void dispatchResourceWithDataBinding(ClientMessage clientMessage, List paramDetails) { - BValue[] bValues = new BValue[paramDetails.size()]; + private void dispatchResourceWithDataBinding(ClientMessage clientMessage, BType[] paramDetails) { + Object[] signatureParams = new Object[paramDetails.length * 2]; try { - bValues[1] = getContentForType(clientMessage, paramDetails.get(1).getVarType()); - bValues[0] = createAndGetMessageObj(onMessageResource, clientMessage, sessionObj); - dispatchResource(clientMessage, bValues); + // Checking the content type first before creating the message to fail fast during data binding scenario + signatureParams[2] = getContentForType(clientMessage, paramDetails[1]); + signatureParams[3] = true; + signatureParams[0] = createAndGetMessageObj(clientMessage, sessionObj); + signatureParams[1] = true; + dispatchResource(clientMessage, signatureParams); } catch (BallerinaException ex) { logger.error("The message received do not match the resource signature", ex); } } - private void dispatchResource(ClientMessage clientMessage, BValue... bValues) { + private void dispatchResource(ClientMessage clientMessage, Object... bValues) { // A CountDownLatch is used to prevent multiple resources executing in parallel and hence preventing the use // of the same session in multiple threads concurrently (Error AMQ212051). CountDownLatch countDownLatch = new CountDownLatch(1); - Executor.submit(onMessageResource, new ArtemisResourceCallback(clientMessage, autoAck, sessionObj, - countDownLatch), null, null, bValues); + Executor.submit(scheduler, service, onMessageResource.getName(), + new ArtemisResourceCallback(clientMessage, autoAck, sessionObj, countDownLatch), null, bValues); try { countDownLatch.await(); } catch (InterruptedException e) { @@ -114,38 +117,36 @@ private void dispatchResource(ClientMessage clientMessage, BValue... bValues) { } } - private BValue createAndGetMessageObj(Resource onMessageResource, ClientMessage clientMessage, - BMap sessionObj) { - ProgramFile programFile = onMessageResource.getResourceInfo().getPackageInfo().getProgramFile(); - BMap messageObj = BLangConnectorSPIUtil.createBStruct( - programFile, ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, ArtemisConstants.MESSAGE_OBJ); - ArtemisUtils.populateMessageObj(clientMessage, - sessionObj.getNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT), - messageObj); + private Object createAndGetMessageObj(ClientMessage clientMessage, + ObjectValue sessionObj) { + ObjectValue messageObj = BallerinaValues.createObjectValue(ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, + ArtemisConstants.MESSAGE_OBJ); + ArtemisUtils.populateMessageObj(clientMessage, sessionObj.getNativeData( + ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT), messageObj); return messageObj; } - private BValue getContentForType(ClientMessage message, BType dataType) { + private Object getContentForType(ClientMessage message, BType dataType) { int dataTypeTag = dataType.getTag(); byte messageType = message.getType(); switch (dataTypeTag) { case TypeTags.STRING_TAG: - return new BString(getBodyText(message, messageType)); + return getBodyText(message, messageType); case TypeTags.JSON_TAG: - return JsonParser.parse(getBodyText(message, messageType)); + return JSONParser.parse(getBodyText(message, messageType)); case TypeTags.XML_TAG: - BXML bxml = XMLUtils.parse(getBodyText(message, messageType)); + XMLValue bxml = XMLFactory.parse(getBodyText(message, messageType)); if (bxml.getNodeType() != XMLNodeType.ELEMENT) { throw new ArtemisConnectorException("Invalid XML data"); } return bxml; case TypeTags.RECORD_TYPE_TAG: - return JSONUtils.convertJSONToStruct(JsonParser.parse(getBodyText(message, messageType)), + return JSONUtils.convertJSONToRecord(JSONParser.parse(getBodyText(message, messageType)), (BStructureType) dataType); case TypeTags.ARRAY_TAG: if (((BArrayType) dataType).getElementType().getTag() == TypeTags.BYTE_TAG) { validateBytesContentType(messageType); - return ArtemisUtils.getBArrayValue(message); + return ArtemisUtils.getArrayValue(message); } else { throw new ArtemisConnectorException("Only byte[] is supported."); } @@ -159,17 +160,17 @@ private BValue getContentForType(ClientMessage message, BType dataType) { } } - private BValue createAndGetMapContent(ClientMessage message, int constrainedType) { + private Object createAndGetMapContent(ClientMessage message, int constrainedType) { Map map; - BMap mapObj; + MapValue mapObj; switch (constrainedType) { case TypeTags.STRING_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.typeString)); + mapObj = new MapValueImpl<>(new BMapType(BTypes.typeString)); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { - mapObj.put(entry.getKey(), new BString((String) value)); + mapObj.put(entry.getKey(), value); } else { throw new ArtemisConnectorException("The map has other than string data"); } @@ -177,11 +178,11 @@ private BValue createAndGetMapContent(ClientMessage message, int constrainedType return mapObj; case TypeTags.INT_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.typeInt)); + mapObj = new MapValueImpl<>(new BMapType(BTypes.typeInt)); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); if (value instanceof Integer || value instanceof Long || value instanceof Short) { - mapObj.put(entry.getKey(), new BInteger((long) value)); + mapObj.put(entry.getKey(), value); } else { throw new ArtemisConnectorException("The map has other than int data"); } @@ -189,11 +190,11 @@ private BValue createAndGetMapContent(ClientMessage message, int constrainedType return mapObj; case TypeTags.FLOAT_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.typeFloat)); + mapObj = new MapValueImpl<>(new BMapType(BTypes.typeFloat)); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); if (value instanceof Float || value instanceof Double) { - mapObj.put(entry.getKey(), new BFloat((double) value)); + mapObj.put(entry.getKey(), value); } else { throw new ArtemisConnectorException("The map has other than float data"); } @@ -201,11 +202,11 @@ private BValue createAndGetMapContent(ClientMessage message, int constrainedType return mapObj; case TypeTags.BYTE_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.typeByte)); + mapObj = new MapValueImpl<>(new BMapType(BTypes.typeByte)); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); - if (value instanceof Byte) { - mapObj.put(entry.getKey(), new BByte((byte) value)); + if (value instanceof Byte || value instanceof Integer) { + mapObj.put(entry.getKey(), value); } else { throw new ArtemisConnectorException("The map has other than byte data"); } @@ -213,11 +214,11 @@ private BValue createAndGetMapContent(ClientMessage message, int constrainedType return mapObj; case TypeTags.ARRAY_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.fromString("byte[]"))); + mapObj = new MapValueImpl<>(new BMapType(BTypes.fromString("byte[]"))); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); - if (value instanceof byte[]) { - mapObj.put(entry.getKey(), new BValueArray((byte[]) value)); + if (value instanceof byte[] || value instanceof int[]) { + mapObj.put(entry.getKey(), new ArrayValue((byte[]) value)); } else { throw new ArtemisConnectorException("The map has other than byte[] data"); } @@ -225,11 +226,11 @@ private BValue createAndGetMapContent(ClientMessage message, int constrainedType return mapObj; case TypeTags.BOOLEAN_TAG: map = getStringObjectMap(message); - mapObj = new BMap<>(new BMapType(BTypes.typeBoolean)); + mapObj = new MapValueImpl<>(new BMapType(BTypes.typeBoolean)); for (Map.Entry entry : map.entrySet()) { Object value = entry.getValue(); if (value instanceof Boolean) { - mapObj.put(entry.getKey(), new BBoolean((boolean) value)); + mapObj.put(entry.getKey(), value); } else { throw new ArtemisConnectorException("The map has other than boolean data"); } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisResourceCallback.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisResourceCallback.java index d660e33d20d4..f7dfd6d538c1 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisResourceCallback.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/ArtemisResourceCallback.java @@ -22,14 +22,12 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientSession; -import org.ballerinalang.bre.bvm.BLangVMErrors; -import org.ballerinalang.bre.bvm.CallableUnitCallback; +import org.ballerinalang.jvm.values.ErrorValue; +import org.ballerinalang.jvm.values.ObjectValue; +import org.ballerinalang.jvm.values.connector.CallableUnitCallback; import org.ballerinalang.messaging.artemis.ArtemisConnectorException; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; -import org.ballerinalang.model.values.BError; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.services.ErrorHandlerUtils; import java.util.concurrent.CountDownLatch; @@ -42,10 +40,10 @@ public class ArtemisResourceCallback implements CallableUnitCallback { private ClientMessage message; private boolean autoAck; - private BMap sessionObj; + private ObjectValue sessionObj; private CountDownLatch countDownLatch; - ArtemisResourceCallback(ClientMessage message, boolean autoAck, BMap sessionObj, + ArtemisResourceCallback(ClientMessage message, boolean autoAck, ObjectValue sessionObj, CountDownLatch countDownLatch) { this.message = message; this.autoAck = autoAck; @@ -72,8 +70,8 @@ public void notifySuccess() { } @Override - public void notifyFailure(BError error) { + public void notifyFailure(ErrorValue error) { countDownLatch.countDown(); - ErrorHandlerUtils.printError("error: " + BLangVMErrors.getPrintableStackTrace(error)); + ErrorHandlerUtils.printError("error: " + error.getPrintableStackTrace()); } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateConsumer.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateConsumer.java index 5c5b6287b0e0..05f2331e828e 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateConsumer.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateConsumer.java @@ -24,12 +24,12 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.slf4j.Logger; @@ -56,52 +56,38 @@ public class CreateConsumer extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap consumerObj = (BMap) context.getRefArgument(0); + } - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) context.getRefArgument(1); + // Todo: using an object for union. Check if correct + public static Object createConsumer(Strand strand, ObjectValue consumerObj, ObjectValue sessionObj, + MapValue queueConfig, + boolean autoAck, Object consumerFilter) { + try { ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap queueConfig = (BMap) context.getRefArgument(2); - String consumerFilter = getStringFromBValueOrNull(context.getNullableRefArgument(3)); - boolean autoAck = context.getBooleanArgument(0); - String queueName = queueConfig.get(ArtemisConstants.QUEUE_NAME).stringValue(); - SimpleString addressName = new SimpleString( - getStringFromBValueOrNull(queueConfig.get(ArtemisConstants.ADDRESS_NAME), queueName)); - boolean autoCreated = getBooleanFromBValue(queueConfig.get(ArtemisConstants.AUTO_CREATED)); - String routingType = queueConfig.get(ArtemisConstants.ROUTING_TYPE).stringValue(); - boolean temporary = getBooleanFromBValue(queueConfig.get(ArtemisConstants.TEMPORARY)); - String queueFilter = getStringFromBValueOrNull(queueConfig.get(ArtemisConstants.FILTER)); - boolean durable = getBooleanFromBValue(queueConfig.get(ArtemisConstants.DURABLE)); + String queueName = queueConfig.getStringValue(ArtemisConstants.QUEUE_NAME); + SimpleString addressName = new SimpleString(ArtemisUtils.getAddressName(queueConfig, queueName)); + boolean autoCreated = queueConfig.getBooleanValue(ArtemisConstants.AUTO_CREATED); + String routingType = queueConfig.getStringValue(ArtemisConstants.ROUTING_TYPE); + boolean temporary = queueConfig.getBooleanValue(ArtemisConstants.TEMPORARY); + String queueFilter = ArtemisUtils.getStringFromObjOrNull(queueConfig.get(ArtemisConstants.FILTER)); + boolean durable = queueConfig.getBooleanValue(ArtemisConstants.DURABLE); int maxConsumers = ArtemisUtils.getIntFromConfig(queueConfig, ArtemisConstants.MAX_CONSUMERS, logger); - boolean purgeOnNoConsumers = getBooleanFromBValue(queueConfig.get(ArtemisConstants.PURGE_ON_NO_CONSUMERS)); - boolean exclusive = getBooleanFromBValue(queueConfig.get(ArtemisConstants.EXCLUSIVE)); - boolean lastValue = getBooleanFromBValue(queueConfig.get(ArtemisConstants.LAST_VALUE)); + boolean purgeOnNoConsumers = queueConfig.getBooleanValue(ArtemisConstants.PURGE_ON_NO_CONSUMERS); + boolean exclusive = queueConfig.getBooleanValue(ArtemisConstants.EXCLUSIVE); + boolean lastValue = queueConfig.getBooleanValue(ArtemisConstants.LAST_VALUE); - ArtemisUtils.getClientConsumer(consumerObj, session, consumerFilter, queueName, addressName, - autoCreated, routingType, temporary, queueFilter, durable, maxConsumers, - purgeOnNoConsumers, exclusive, lastValue, logger); + ArtemisUtils.getClientConsumer(consumerObj, session, ArtemisUtils.getStringFromObjOrNull(consumerFilter), + queueName, addressName, autoCreated, routingType, temporary, queueFilter, + durable, maxConsumers, purgeOnNoConsumers, exclusive, lastValue, logger); consumerObj.addNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT, sessionObj.getNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT)); consumerObj.addNativeData(ArtemisConstants.ARTEMIS_AUTO_ACK, autoAck); session.start(); } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, e)); + return ArtemisUtils.getError(e); } + return null; } - private String getStringFromBValueOrNull(BValue value, String defaultVal) { - return value != null ? value.stringValue() : defaultVal; - } - - private String getStringFromBValueOrNull(BValue value) { - return value != null ? value.stringValue() : null; - } - - private boolean getBooleanFromBValue(BValue value) { - return ((BBoolean) value).booleanValue(); - } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateServiceConsumer.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateServiceConsumer.java index 2192a4b4628b..6a05acb41612 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateServiceConsumer.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/CreateServiceConsumer.java @@ -25,25 +25,19 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; -import org.ballerinalang.connector.api.Annotation; -import org.ballerinalang.connector.api.BLangConnectorSPIUtil; -import org.ballerinalang.connector.api.Resource; -import org.ballerinalang.connector.api.Service; -import org.ballerinalang.connector.api.Struct; -import org.ballerinalang.connector.api.Value; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ArrayValue; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; -import java.util.List; -import java.util.Map; /** * Extern function to create an async Artemis consumer. @@ -67,33 +61,30 @@ public class CreateServiceConsumer extends BlockingNativeCallableUnit { @Override public void execute(Context context) { + } + + public static Object createConsumer(Strand strand, ObjectValue listenerObj, ObjectValue service) { try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap listenerObj = (BMap) context.getRefArgument(0); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) listenerObj.get(ArtemisConstants.SESSION); + ObjectValue sessionObj = (ObjectValue) listenerObj.get(ArtemisConstants.SESSION); ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); - Service service = BLangConnectorSPIUtil.getServiceRegistered(context); - - Annotation serviceAnnotation = getServiceConfigAnnotation(service); - Struct annotationValue = serviceAnnotation.getValue(); - boolean autoAck = annotationValue.getBooleanField(ArtemisConstants.AUTO_ACK); - String consumerFilter = getStringFromValueOrNull(annotationValue.getRefField(ArtemisConstants.FILTER)); + MapValue serviceAnnotation = getServiceConfigAnnotation(service); + boolean autoAck = serviceAnnotation.getBooleanValue(ArtemisConstants.AUTO_ACK); + String consumerFilter = ArtemisUtils.getStringFromObjOrNull(serviceAnnotation.get(ArtemisConstants.FILTER)); - Map queueConfig = annotationValue.getMapField(ArtemisConstants.QUEUE_CONFIG); - String queueName = queueConfig.get(ArtemisConstants.QUEUE_NAME).getStringValue(); - SimpleString addressName = new SimpleString(getAddressName(queueConfig, queueName)); - boolean autoCreated = queueConfig.get(ArtemisConstants.AUTO_CREATED).getBooleanValue(); - String routingType = queueConfig.get(ArtemisConstants.ROUTING_TYPE).getStringValue(); - boolean temporary = queueConfig.get(ArtemisConstants.TEMPORARY).getBooleanValue(); - String queueFilter = getStringFromValueOrNull(queueConfig.get(ArtemisConstants.FILTER)); - boolean durable = queueConfig.get(ArtemisConstants.DURABLE).getBooleanValue(); - int maxConsumers = ArtemisUtils.getIntFromLong(queueConfig. - get(ArtemisConstants.MAX_CONSUMERS).getIntValue(), ArtemisConstants.MAX_CONSUMERS, logger); - boolean purgeOnNoConsumers = queueConfig.get(ArtemisConstants.PURGE_ON_NO_CONSUMERS).getBooleanValue(); - boolean exclusive = queueConfig.get(ArtemisConstants.EXCLUSIVE).getBooleanValue(); - boolean lastValue = queueConfig.get(ArtemisConstants.LAST_VALUE).getBooleanValue(); + MapValue queueConfig = serviceAnnotation.getMapValue(ArtemisConstants.QUEUE_CONFIG); + String queueName = queueConfig.getStringValue(ArtemisConstants.QUEUE_NAME); + SimpleString addressName = new SimpleString(ArtemisUtils.getAddressName(queueConfig, queueName)); + boolean autoCreated = queueConfig.getBooleanValue(ArtemisConstants.AUTO_CREATED); + String routingType = queueConfig.getStringValue(ArtemisConstants.ROUTING_TYPE); + boolean temporary = queueConfig.getBooleanValue(ArtemisConstants.TEMPORARY); + String queueFilter = ArtemisUtils.getStringFromObjOrNull(queueConfig.get(ArtemisConstants.FILTER)); + boolean durable = queueConfig.getBooleanValue(ArtemisConstants.DURABLE); + int maxConsumers = ArtemisUtils.getIntFromLong(queueConfig.getIntValue(ArtemisConstants.MAX_CONSUMERS), + ArtemisConstants.MAX_CONSUMERS, logger); + boolean purgeOnNoConsumers = queueConfig.getBooleanValue(ArtemisConstants.PURGE_ON_NO_CONSUMERS); + boolean exclusive = queueConfig.getBooleanValue(ArtemisConstants.EXCLUSIVE); + boolean lastValue = queueConfig.getBooleanValue(ArtemisConstants.LAST_VALUE); ClientConsumer consumer = ArtemisUtils.getClientConsumer(listenerObj, session, consumerFilter, queueName, addressName, autoCreated, routingType, temporary, @@ -101,33 +92,18 @@ public void execute(Context context) { purgeOnNoConsumers, exclusive, lastValue, logger); console.println("[" + ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS + "] Client Consumer created for queue " + queueName); - - Resource onMessageResource = service.getResources()[0]; - if (onMessageResource != null) { - consumer.setMessageHandler(new ArtemisMessageHandler(onMessageResource, sessionObj, autoAck)); - } + //Todo: Validate onMessage resource is not null at compiler level + consumer.setMessageHandler(new ArtemisMessageHandler(strand.scheduler, service, sessionObj, autoAck)); } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, e)); + return ArtemisUtils.getError(e); } + return null; } - private String getAddressName(Map queueConfig, String queueName) { - Value addressName = queueConfig.get(ArtemisConstants.ADDRESS_NAME); - return addressName != null ? addressName.getStringValue() : queueName; - } - private String getStringFromValueOrNull(Value value) { - return value != null ? value.getStringValue() : null; - } - - private Annotation getServiceConfigAnnotation(Service service) { - List annotationList = service - .getAnnotationList(ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, - "ServiceConfig"); - - if (annotationList == null) { - return null; - } - return annotationList.isEmpty() ? null : annotationList.get(0); + private static MapValue getServiceConfigAnnotation(ObjectValue service) { + ArrayValue annotation = service.getType().getAnnotation(ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, + "ServiceConfig"); + return (MapValue) annotation.get(0); } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Receive.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Receive.java index 188280470ad3..0b06670ab24e 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Receive.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Receive.java @@ -24,14 +24,13 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; -import org.ballerinalang.connector.api.BLangConnectorSPIUtil; +import org.ballerinalang.jvm.BallerinaValues; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisTransactionContext; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -50,39 +49,34 @@ structType = ArtemisConstants.CONSUMER_OBJ, structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS ), - args = { - @Argument( - name = "timeoutInMilliSeconds", - type = TypeKind.INT - ) - }, isPublic = true ) public class Receive extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap consumerObj = (BMap) context.getRefArgument(0); - long timeInMilliSeconds = context.getIntArgument(0); + } + + public static Object receive(Strand strand, ObjectValue consumerObj, long timeoutInMilliSeconds) { ClientConsumer consumer = (ClientConsumer) consumerObj.getNativeData(ArtemisConstants.ARTEMIS_CONSUMER); ArtemisTransactionContext transactionContext = (ArtemisTransactionContext) consumerObj.getNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT); boolean autoAck = (boolean) consumerObj.getNativeData(ArtemisConstants.ARTEMIS_AUTO_ACK); try { - ClientMessage clientMessage = consumer.receive(timeInMilliSeconds); - BMap messageObj = BLangConnectorSPIUtil.createBStruct( - context, ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, ArtemisConstants.MESSAGE_OBJ); + ClientMessage clientMessage = consumer.receive(timeoutInMilliSeconds); + ObjectValue messageObj = BallerinaValues.createObjectValue(ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS, + ArtemisConstants.MESSAGE_OBJ); ArtemisUtils.populateMessageObj(clientMessage, transactionContext, messageObj); if (autoAck) { clientMessage.acknowledge(); if (transactionContext != null) { - transactionContext.handleTransactionBlock(context, ArtemisConstants.CONSUMER_OBJ); + transactionContext.handleTransactionBlock(ArtemisConstants.CONSUMER_OBJ); } } - context.setReturnValues(messageObj); + return messageObj; } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, e)); + return ArtemisUtils.getError(e); } } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Start.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Start.java index 32eb52fea31c..6c6d0ddadb73 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Start.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Start.java @@ -23,11 +23,11 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -50,16 +50,16 @@ ) ) public class Start extends BlockingNativeCallableUnit { - private CountDownLatch countDownLatch = new CountDownLatch(1); @Override public void execute(Context context) { + } + + public static Object start(Strand strand, ObjectValue listenerObj) { try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap listenerObj = (BMap) context.getRefArgument(0); + CountDownLatch countDownLatch = new CountDownLatch(1); listenerObj.addNativeData(ArtemisConstants.COUNTDOWN_LATCH, countDownLatch); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) listenerObj.get("session"); + ObjectValue sessionObj = listenerObj.getObjectValue(ArtemisConstants.SESSION); ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); session.start(); // It is essential to keep a non-daemon thread running in order to avoid the java program or the @@ -72,7 +72,9 @@ public void execute(Context context) { } }).start(); } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error on starting the session")); + return ArtemisUtils.getError(e); } + return null; } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Stop.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Stop.java index a97dbce44475..6a09f6ff159d 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Stop.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/consumer/Stop.java @@ -23,11 +23,11 @@ import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -53,9 +53,10 @@ public class Stop extends BlockingNativeCallableUnit { @Override public void execute(Context context) { + } + + public static Object stop(Strand strand, ObjectValue listenerObj) { try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap listenerObj = (BMap) context.getRefArgument(0); ClientConsumer consumer = (ClientConsumer) listenerObj.getNativeData(ArtemisConstants.ARTEMIS_CONSUMER); consumer.close(); ArtemisUtils.closeIfAnonymousSession(listenerObj); @@ -65,7 +66,9 @@ public void execute(Context context) { countDownLatch.countDown(); } } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error when closing the consumer")); + return ArtemisUtils.getError(e); } + return null; } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/Acknowledge.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/Acknowledge.java index 368bb2a92456..4d3124737b9b 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/Acknowledge.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/Acknowledge.java @@ -23,12 +23,12 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.bre.bvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisTransactionContext; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -53,18 +53,21 @@ public class Acknowledge extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static Object acknowledge(Strand strand, ObjectValue messageObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); ArtemisTransactionContext transactionContext = (ArtemisTransactionContext) messageObj.getNativeData(ArtemisConstants.ARTEMIS_TRANSACTION_CONTEXT); try { message.acknowledge(); if (transactionContext != null) { - transactionContext.handleTransactionBlock(context, ArtemisConstants.MESSAGE_OBJ); + transactionContext.handleTransactionBlock(ArtemisConstants.MESSAGE_OBJ); } } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error on acknowledging the message")); + return ArtemisUtils.getError(e); } + return null; } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/CreateMessage.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/CreateMessage.java index a6163ecae1a8..eef44b5263c0 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/CreateMessage.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/CreateMessage.java @@ -29,18 +29,13 @@ import org.apache.activemq.artemis.utils.collections.TypedProperties; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ArrayValue; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BByte; -import org.ballerinalang.model.values.BFloat; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.model.values.BValueArray; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.ballerinalang.stdlib.io.channels.base.Channel; @@ -48,8 +43,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; - /** * Extern function to create an ActiveMQ Artemis message. * @@ -64,95 +57,76 @@ type = TypeKind.OBJECT, structType = ArtemisConstants.MESSAGE_OBJ, structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS - ), - args = { - @Argument( - name = "session", - type = TypeKind.OBJECT, - structType = ArtemisConstants.SESSION_OBJ - ), - @Argument( - name = "data", - type = TypeKind.UNION - ), - @Argument( - name = "config", - type = TypeKind.RECORD, - structType = "ConnectionConfiguration" - ) - } + ) ) public class CreateMessage extends BlockingNativeCallableUnit { private static final Logger logger = LoggerFactory.getLogger(CreateMessage.class); @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); - String type = messageObj.get(ArtemisConstants.MESSAGE_TYPE).stringValue(); - - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) context.getRefArgument(1); - BValue dataVal = context.getRefArgument(2); + } - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap configObj = (BMap) context.getRefArgument(3); - long expiration = ((BInteger) configObj.get(ArtemisConstants.EXPIRATION)).intValue(); - long timeStamp = ((BInteger) configObj.get(ArtemisConstants.TIME_STAMP)).intValue(); - byte priority = (byte) ((BByte) configObj.get(ArtemisConstants.PRIORITY)).byteValue(); - boolean durable = ((BBoolean) configObj.get(ArtemisConstants.DURABLE)).booleanValue(); - BValue routingType = configObj.get(ArtemisConstants.ROUTING_TYPE); - BValue groupId = configObj.get(ArtemisConstants.GROUP_ID); + public static void createMessage(Strand strand, ObjectValue messageObj, ObjectValue sessionObj, Object dataVal, + MapValue configObj) { + String type = messageObj.getStringValue(ArtemisConstants.MESSAGE_TYPE); + long expiration = configObj.getIntValue(ArtemisConstants.EXPIRATION); + long timeStamp = configObj.getIntValue(ArtemisConstants.TIME_STAMP); + byte priority = Byte.valueOf(configObj.get(ArtemisConstants.PRIORITY).toString()); + boolean durable = configObj.getBooleanValue(ArtemisConstants.DURABLE); + Object routingType = configObj.get(ArtemisConstants.ROUTING_TYPE); + Object groupId = configObj.get(ArtemisConstants.GROUP_ID); int groupSequence = ArtemisUtils.getIntFromConfig(configObj, ArtemisConstants.GROUP_SEQUENCE, logger); - BValue correlationId = configObj.get(ArtemisConstants.CORRELATION_ID); - BValue replyTo = configObj.get(ArtemisConstants.REPLY_TO); + Object correlationId = configObj.get(ArtemisConstants.CORRELATION_ID); + Object replyTo = configObj.get(ArtemisConstants.REPLY_TO); ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); byte messageType = getMessageType(type); ClientMessage message = session.createMessage(messageType, durable, expiration, timeStamp, priority); - if (routingType instanceof BString) { - message.setRoutingType(ArtemisUtils.getRoutingTypeFromString(routingType.stringValue())); + if (routingType instanceof String) { + message.setRoutingType(ArtemisUtils.getRoutingTypeFromString((String) routingType)); } - if (groupId instanceof BString) { - message.setGroupID(groupId.stringValue()); + if (groupId instanceof String) { + message.setGroupID((String) groupId); } message.setGroupSequence(groupSequence); - if (correlationId instanceof BString) { - message.setCorrelationID(correlationId.stringValue()); + if (correlationId instanceof String) { + message.setCorrelationID(correlationId); } - if (replyTo instanceof BString) { - message.setReplyTo(new SimpleString(replyTo.stringValue())); + if (replyTo instanceof String) { + message.setReplyTo(new SimpleString((String) replyTo)); } if (messageType == Message.TEXT_TYPE) { - TextMessageUtil.writeBodyText(message.getBodyBuffer(), new SimpleString(dataVal.stringValue())); + TextMessageUtil.writeBodyText(message.getBodyBuffer(), new SimpleString((String) dataVal)); } else if (messageType == Message.BYTES_TYPE) { - BytesMessageUtil.bytesWriteBytes(message.getBodyBuffer(), ArtemisUtils.getBytesData((BValueArray) dataVal)); + BytesMessageUtil.bytesWriteBytes(message.getBodyBuffer(), ArtemisUtils.getBytesData((ArrayValue) dataVal)); } else if (messageType == Message.MAP_TYPE) { @SuppressWarnings(ArtemisConstants.UNCHECKED) - Map mapObj = ((BMap) dataVal).getMap(); + String[] keys = ((MapValue) dataVal).getKeys(); TypedProperties map = new TypedProperties(); - for (Map.Entry entry : mapObj.entrySet()) { - SimpleString key = new SimpleString(entry.getKey()); - BValue value = entry.getValue(); - if (value instanceof BString) { - map.putSimpleStringProperty(key, new SimpleString(value.stringValue())); - } else if (value instanceof BInteger) { - map.putLongProperty(key, ((BInteger) value).intValue()); - } else if (value instanceof BFloat) { - map.putDoubleProperty(key, ((BFloat) value).floatValue()); - } else if (value instanceof BByte) { - map.putByteProperty(key, (byte) ((BByte) value).byteValue()); - } else if (value instanceof BBoolean) { - map.putBooleanProperty(key, ((BBoolean) value).booleanValue()); - } else if (value instanceof BValueArray) { - map.putBytesProperty(key, ArtemisUtils.getBytesData((BValueArray) value)); + for (String keyStr : keys) { + SimpleString key = new SimpleString(keyStr); + @SuppressWarnings(ArtemisConstants.UNCHECKED) + Object value = ((MapValue) dataVal).get(keyStr); + if (value instanceof String) { + map.putSimpleStringProperty(key, new SimpleString((String) value)); + } else if (value instanceof Long) { + map.putLongProperty(key, (long) value); + } else if (value instanceof Double) { + map.putDoubleProperty(key, (Double) value); + } else if (value instanceof Integer) { + map.putIntProperty(key, (Integer) value); + } else if (value instanceof Byte) { + map.putByteProperty(key, (Byte) value); + } else if (value instanceof Boolean) { + map.putBooleanProperty(key, (Boolean) value); + } else if (value instanceof ArrayValue) { + map.putBytesProperty(key, ArtemisUtils.getBytesData((ArrayValue) value)); } MapMessageUtil.writeBodyMap(message.getBodyBuffer(), map); } } else if (messageType == Message.STREAM_TYPE) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap streamObj = (BMap) dataVal; + ObjectValue streamObj = (ObjectValue) dataVal; Channel channel = (Channel) streamObj.getNativeData(IOConstants.BYTE_CHANNEL_NAME); message.setBodyInputStream(channel.getInputStream()); } @@ -161,7 +135,7 @@ public void execute(Context context) { messageObj.addNativeData(ArtemisConstants.ARTEMIS_MESSAGE, message); } - private byte getMessageType(String type) { + private static byte getMessageType(String type) { switch (type) { case "TEXT": return Message.TEXT_TYPE; diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetBodySize.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetBodySize.java index e04d395db19a..cd89dc963722 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetBodySize.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetBodySize.java @@ -22,11 +22,10 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -51,9 +50,10 @@ public class GetBodySize extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static Long getBodySize(Strand strand, ObjectValue messageObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); - context.setReturnValues(new BInteger(message.getBodySize())); + return Long.valueOf(message.getBodySize()); } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetPayload.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetPayload.java index 166d5da89d7c..f73559cefc8f 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetPayload.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetPayload.java @@ -27,14 +27,15 @@ import org.apache.activemq.artemis.utils.collections.TypedProperties; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.types.BMapType; +import org.ballerinalang.jvm.types.BTypes; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.MapValueImpl; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; -import org.ballerinalang.model.types.BMapType; -import org.ballerinalang.model.types.BTypes; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -67,49 +68,49 @@ public class GetPayload extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static Object getPayload(Strand strand, ObjectValue messageObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); byte messageType = message.getType(); if (messageType == Message.TEXT_TYPE) { ActiveMQBuffer msgBuffer = message.getBodyBuffer(); - context.setReturnValues(new BString(TextMessageUtil.readBodyText(msgBuffer).toString())); + return TextMessageUtil.readBodyText(msgBuffer).toString(); } else if (messageType == Message.BYTES_TYPE || messageType == Message.DEFAULT_TYPE) { - context.setReturnValues(ArtemisUtils.getBArrayValue(message)); + return ArtemisUtils.getArrayValue(message); } else if (messageType == Message.MAP_TYPE) { ActiveMQBuffer msgBuffer = message.getBodyBuffer(); TypedProperties properties = MapMessageUtil.readBodyMap(msgBuffer); Map map = properties.getMap(); - BMap mapObj = getMapObj(map.entrySet().iterator().next().getValue()); + MapValue mapObj = getMapObj(map.entrySet().iterator().next().getValue()); if (mapObj != null) { for (Map.Entry entry : map.entrySet()) { - mapObj.put(entry.getKey(), ArtemisUtils.getBValueFromObj(entry.getValue(), context)); + mapObj.put(entry.getKey(), ArtemisUtils.getValidObj(entry.getValue())); } - context.setReturnValues(mapObj); + return mapObj; } else { - context.setReturnValues(ArtemisUtils.getError(context, "Unsupported type")); + return ArtemisUtils.getError("Unsupported type"); } } else if (messageType == Message.STREAM_TYPE) { - context.setReturnValues( - ArtemisUtils.getError(context, "Use the saveToFile function for STREAM type message")); + return ArtemisUtils.getError("Use the saveToFile function for STREAM type message"); } else { - context.setReturnValues(ArtemisUtils.getError(context, "Unsupported type")); + return ArtemisUtils.getError("Unsupported type"); } } - private BMap getMapObj(Object val) { + private static MapValue getMapObj(Object val) { if (val instanceof String) { - return new BMap<>(new BMapType(BTypes.typeString)); - } else if (val instanceof Long || val instanceof Integer || val instanceof Short) { - return new BMap<>(new BMapType(BTypes.typeInt)); + return new MapValueImpl<>(new BMapType(BTypes.typeString)); + } else if (val instanceof Long) { + return new MapValueImpl<>(new BMapType(BTypes.typeInt)); } else if (val instanceof Float || val instanceof Double) { - return new BMap<>(new BMapType(BTypes.typeFloat)); - } else if (val instanceof Byte) { - return new BMap<>(new BMapType(BTypes.typeByte)); - } else if (val instanceof byte[]) { - return new BMap<>(new BMapType(BTypes.fromString("byte[]"))); + return new MapValueImpl<>(new BMapType(BTypes.typeFloat)); + } else if (val instanceof Byte || val instanceof Integer) { + return new MapValueImpl<>(new BMapType(BTypes.typeByte)); + } else if (val instanceof byte[] || val instanceof int[]) { + return new MapValueImpl<>(new BMapType(BTypes.fromString("byte[]"))); } else if (val instanceof Boolean) { - return new BMap<>(new BMapType(BTypes.typeBoolean)); + return new MapValueImpl<>(new BMapType(BTypes.typeBoolean)); } return null; } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetProperty.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetProperty.java index 4aa6723b59d8..6346008c5a29 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetProperty.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetProperty.java @@ -22,11 +22,11 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -57,16 +57,15 @@ public class GetProperty extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); - ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); + } - String key = context.getStringArgument(0); + public static Object getProperty(Strand strand, ObjectValue messageObj, String key) { + ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); Object property = message.getObjectProperty(key); if (property != null) { - context.setReturnValues(ArtemisUtils.getBValueFromObj(property, context)); - } else { - context.setReturnValues(); + return ArtemisUtils.getValidObj(property); } + return null; } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetType.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetType.java index dba6486b2410..0974ef292d76 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetType.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/GetType.java @@ -23,11 +23,10 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.bre.bvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -51,28 +50,23 @@ public class GetType extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static Object getType(Strand strand, ObjectValue messageObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); byte messageType = message.getType(); - BString type; switch (messageType) { case Message.TEXT_TYPE: - type = new BString("TEXT"); - break; + return "TEXT"; case Message.BYTES_TYPE: - type = new BString("BYTES"); - break; + return "BYTES"; case Message.MAP_TYPE: - type = new BString("MAP"); - break; + return "MAP"; case Message.STREAM_TYPE: - type = new BString("STREAM"); - break; + return "STREAM"; default: - type = new BString("UNSUPPORTED"); - + return "UNSUPPORTED"; } - context.setReturnValues(type); } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/PutProperty.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/PutProperty.java index d884655f28c0..39569a2e57e0 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/PutProperty.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/PutProperty.java @@ -22,18 +22,12 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ArrayValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BByte; -import org.ballerinalang.model.values.BFloat; -import org.ballerinalang.model.values.BInteger; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.model.values.BValueArray; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -51,40 +45,32 @@ type = TypeKind.OBJECT, structType = ArtemisConstants.MESSAGE_OBJ, structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS - ), - args = { - @Argument( - name = "key", - type = TypeKind.STRING - ), - @Argument( - name = "value", - type = TypeKind.UNION - ) - } + ) ) public class PutProperty extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static void putProperty(Strand strand, ObjectValue messageObj, String key, Object valObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); - String key = context.getStringArgument(0); - BValue valObj = context.getRefArgument(1); - if (valObj instanceof BString) { - message.putStringProperty(key, valObj.stringValue()); - } else if (valObj instanceof BInteger) { - message.putLongProperty(key, ((BInteger) valObj).intValue()); - } else if (valObj instanceof BFloat) { - message.putDoubleProperty(key, ((BFloat) valObj).floatValue()); - } else if (valObj instanceof BBoolean) { - message.putBooleanProperty(key, ((BBoolean) valObj).booleanValue()); - } else if (valObj instanceof BByte) { - message.putByteProperty(key, (byte) ((BByte) valObj).byteValue()); - } else if (valObj instanceof BValueArray) { - message.putBytesProperty(key, ArtemisUtils.getBytesData((BValueArray) valObj)); + if (valObj instanceof String) { + message.putStringProperty(key, (String) valObj); + } else if (valObj instanceof Long) { + message.putLongProperty(key, (long) valObj); + } else if (valObj instanceof Double) { + message.putDoubleProperty(key, (double) valObj); + } else if (valObj instanceof Boolean) { + message.putBooleanProperty(key, (boolean) valObj); + } else if (valObj instanceof Byte) { + message.putByteProperty(key, (byte) valObj); + } else if (valObj instanceof ArrayValue) { + message.putBytesProperty(key, ArtemisUtils.getBytesData((ArrayValue) valObj)); + } else if (valObj instanceof Integer) { + message.putIntProperty(key, (Integer) valObj); }//else is not needed because these are the only values supported by the Ballerina the method } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/SaveToWritableByteChannel.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/SaveToWritableByteChannel.java index 8b081dd2a7e0..5fd0d632a2eb 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/SaveToWritableByteChannel.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/message/SaveToWritableByteChannel.java @@ -24,11 +24,11 @@ import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -64,21 +64,20 @@ public class SaveToWritableByteChannel extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap messageObj = (BMap) context.getRefArgument(0); + } + + public static Object saveToWritableByteChannel(Strand strand, ObjectValue messageObj, ObjectValue byteChannelObj) { ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); if (message.getType() == Message.STREAM_TYPE) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap byteChannelObj = (BMap) context.getRefArgument(1); Channel channel = (Channel) byteChannelObj.getNativeData(IOConstants.BYTE_CHANNEL_NAME); try { message.saveToOutputStream(Channels.newOutputStream(channel.getByteChannel())); } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error while writing to WritableByteChannel")); + return ArtemisUtils.getError("Error while writing to WritableByteChannel"); } - } else { - context.setReturnValues(ArtemisUtils.getError(context, "Unsupported type")); + return ArtemisUtils.getError("Unsupported type"); } + return null; } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Close.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Close.java index e6e70ec71723..f9e1f2af386a 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Close.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Close.java @@ -23,11 +23,11 @@ import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -52,8 +52,9 @@ public class Close extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap producerObj = (BMap) context.getRefArgument(0); + } + + public static Object close(Strand strand, ObjectValue producerObj) { ClientProducer producer = (ClientProducer) producerObj.getNativeData(ArtemisConstants.ARTEMIS_PRODUCER); try { if (!producer.isClosed()) { @@ -61,7 +62,8 @@ public void execute(Context context) { } ArtemisUtils.closeIfAnonymousSession(producerObj); } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error when closing the producer")); + return ArtemisUtils.getError("Error when closing the producer"); } + return null; } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/CreateProducer.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/CreateProducer.java index 846df18ba236..f7a404d3b6ca 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/CreateProducer.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/CreateProducer.java @@ -24,15 +24,13 @@ import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; -import org.ballerinalang.bre.bvm.CallableUnitCallback; +import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; -import org.ballerinalang.model.NativeCallableUnit; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.slf4j.Logger; @@ -52,44 +50,27 @@ type = TypeKind.OBJECT, structType = ArtemisConstants.PRODUCER_OBJ, structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS - ), - args = { - @Argument( - name = "addressName", - type = TypeKind.STRING - ), - @Argument( - name = "config", - type = TypeKind.RECORD, - structType = "AddressConfiguration" - ), - @Argument( - name = "rate", - type = TypeKind.INT - ) - } + ) ) -public class CreateProducer implements NativeCallableUnit { +public class CreateProducer extends BlockingNativeCallableUnit { private static final Logger logger = LoggerFactory.getLogger(CreateProducer.class); @Override - public void execute(Context context, CallableUnitCallback callableUnitCallback) { - try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap producerObj = (BMap) context.getRefArgument(0); + public void execute(Context context) { + } - SimpleString addressName = new SimpleString(context.getStringArgument(0)); + public static void createProducer(Strand strand, ObjectValue producerObj, String addressStr, + MapValue configObj, long rateArg) { + try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap configObj = (BMap) context.getRefArgument(1); + SimpleString addressName = new SimpleString(addressStr); - String routingType = configObj.get(ArtemisConstants.ROUTING_TYPE).stringValue(); - boolean autoCreated = ((BBoolean) configObj.get(ArtemisConstants.AUTO_CREATED)).booleanValue(); + String routingType = configObj.getStringValue(ArtemisConstants.ROUTING_TYPE); + boolean autoCreated = configObj.getBooleanValue(ArtemisConstants.AUTO_CREATED); - int rate = ArtemisUtils.getIntFromLong(context.getIntArgument(0), ArtemisConstants.RATE, logger); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) producerObj.get(ArtemisConstants.SESSION); + int rate = ArtemisUtils.getIntFromLong(rateArg, ArtemisConstants.RATE, logger); + ObjectValue sessionObj = producerObj.getObjectValue(ArtemisConstants.SESSION); ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); if (autoCreated) { @@ -106,12 +87,7 @@ public void execute(Context context, CallableUnitCallback callableUnitCallback) producerObj.addNativeData(ArtemisConstants.ARTEMIS_PRODUCER, producer); } catch (ActiveMQException ex) { - ArtemisUtils.throwException("Error occurred while creating the producer.", context, ex, logger); + ArtemisUtils.throwException("Error occurred while creating the producer.", ex, logger); } } - - @Override - public boolean isBlocking() { - return true; - } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/IsClosed.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/IsClosed.java index f3ce81887d89..7871e6e02502 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/IsClosed.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/IsClosed.java @@ -22,11 +22,10 @@ import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -51,10 +50,12 @@ public class IsClosed extends BlockingNativeCallableUnit { @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap producerObj = (BMap) context.getRefArgument(0); + } + + public static boolean isClosed(Strand strand, ObjectValue producerObj) { ClientProducer producer = (ClientProducer) producerObj.getNativeData(ArtemisConstants.ARTEMIS_PRODUCER); - context.setReturnValues(new BBoolean(producer.isClosed())); + return producer.isClosed(); } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Send.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Send.java index d9ae9d5db09f..f79a939d0aee 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Send.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/producer/Send.java @@ -24,12 +24,12 @@ import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisTransactionContext; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -61,11 +61,10 @@ public class Send extends BlockingNativeCallableUnit { @Override public void execute(Context context) { + } + + public static Object externSend(Strand strand, ObjectValue producerObj, ObjectValue data) { try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap producerObj = (BMap) context.getRefArgument(0); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap data = (BMap) context.getRefArgument(1); ClientProducer producer = (ClientProducer) producerObj.getNativeData(ArtemisConstants.ARTEMIS_PRODUCER); ClientMessage message = (ClientMessage) data.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE); ArtemisTransactionContext transactionContext = @@ -74,10 +73,12 @@ public void execute(Context context) { // https://issues.apache.org/jira/browse/ARTEMIS-2325 producer.send(message); if (transactionContext != null) { - transactionContext.handleTransactionBlock(context, ArtemisConstants.PRODUCER_OBJ); + transactionContext.handleTransactionBlock(ArtemisConstants.PRODUCER_OBJ); } } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, e)); + return ArtemisUtils.getError(e); } + return null; } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/Close.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/Close.java index 1cd3aac74a27..bfc937a5c080 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/Close.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/Close.java @@ -22,13 +22,12 @@ import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; -import org.ballerinalang.bre.bvm.CallableUnitCallback; +import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisUtils; -import org.ballerinalang.model.NativeCallableUnit; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -49,24 +48,22 @@ ), isPublic = true ) -public class Close implements NativeCallableUnit { +public class Close extends BlockingNativeCallableUnit { @Override - public void execute(Context context, CallableUnitCallback callableUnitCallback) { + public void execute(Context context) { + } + + public static Object close(Strand strand, ObjectValue sessionObj) { try { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) context.getRefArgument(0); ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); if (!session.isClosed()) { session.close(); } } catch (ActiveMQException e) { - context.setReturnValues(ArtemisUtils.getError(context, "Error when closing the Session")); + return ArtemisUtils.getError("Error when closing the Session"); } + return null; } - @Override - public boolean isBlocking() { - return true; - } } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/CreateSession.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/CreateSession.java index 165f8068f64a..e565a7acd093 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/CreateSession.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/CreateSession.java @@ -25,15 +25,13 @@ import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.ballerinalang.bre.Context; import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.MapValue; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; import org.ballerinalang.messaging.artemis.ArtemisTransactionContext; import org.ballerinalang.messaging.artemis.ArtemisUtils; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BString; -import org.ballerinalang.model.values.BValue; -import org.ballerinalang.natives.annotations.Argument; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; import org.slf4j.Logger; @@ -53,32 +51,17 @@ type = TypeKind.OBJECT, structType = ArtemisConstants.SESSION_OBJ, structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS - ), - args = { - @Argument( - name = "con", - type = TypeKind.OBJECT, - structType = ArtemisConstants.CONNECTION_OBJ - ), - @Argument( - name = "config", - type = TypeKind.RECORD, - structType = "SessionConfiguration" - ) - } + ) ) public class CreateSession extends BlockingNativeCallableUnit { private static final Logger logger = LoggerFactory.getLogger(CreateSession.class); @Override public void execute(Context context) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) context.getRefArgument(0); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap connection = (BMap) context.getRefArgument(1); - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap config = (BMap) context.getRefArgument(2); + } + public static void createSession(Strand strand, ObjectValue sessionObj, ObjectValue connection, + MapValue config) { ServerLocator serverLocator = (ServerLocator) connection.getNativeData( ArtemisConstants.ARTEMIS_CONNECTION_POOL); ClientSessionFactory sessionFactory = @@ -86,16 +69,16 @@ public void execute(Context context) { try { String username = null; String password = null; - BValue userValue = config.get(ArtemisConstants.USERNAME); - if (userValue instanceof BString) { - username = userValue.stringValue(); + Object userValue = config.get(ArtemisConstants.USERNAME); + if (userValue instanceof String) { + username = (String) userValue; } - BValue passValue = config.get(ArtemisConstants.PASSWORD); - if (passValue instanceof BString) { - password = passValue.stringValue(); + Object passValue = config.get(ArtemisConstants.PASSWORD); + if (passValue instanceof String) { + password = (String) passValue; } - boolean autoCommitSends = ((BBoolean) config.get(ArtemisConstants.AUTO_COMMIT_SENDS)).booleanValue(); - boolean autoCommitAcks = ((BBoolean) config.get(ArtemisConstants.AUTO_COMMIT_ACKS)).booleanValue(); + boolean autoCommitSends = config.getBooleanValue(ArtemisConstants.AUTO_COMMIT_SENDS); + boolean autoCommitAcks = config.getBooleanValue(ArtemisConstants.AUTO_COMMIT_ACKS); ClientSession session = sessionFactory.createSession(username, password, false, autoCommitSends, autoCommitAcks, serverLocator.isPreAcknowledge(), serverLocator.getAckBatchSize()); @@ -105,7 +88,8 @@ public void execute(Context context) { new ArtemisTransactionContext(sessionObj)); } } catch (ActiveMQException e) { - ArtemisUtils.throwException("Error occurred while starting session", context, e, logger); + ArtemisUtils.throwException("Error occurred while starting session", e, logger); } } + } diff --git a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/IsClosed.java b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/IsClosed.java index c77f958725d7..7203b708f7c5 100644 --- a/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/IsClosed.java +++ b/stdlib/messaging/activemq-artemis/src/main/java/org/ballerinalang/messaging/artemis/externimpl/session/IsClosed.java @@ -21,13 +21,11 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.ballerinalang.bre.Context; -import org.ballerinalang.bre.bvm.CallableUnitCallback; +import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit; +import org.ballerinalang.jvm.Strand; +import org.ballerinalang.jvm.values.ObjectValue; import org.ballerinalang.messaging.artemis.ArtemisConstants; -import org.ballerinalang.model.NativeCallableUnit; import org.ballerinalang.model.types.TypeKind; -import org.ballerinalang.model.values.BBoolean; -import org.ballerinalang.model.values.BMap; -import org.ballerinalang.model.values.BValue; import org.ballerinalang.natives.annotations.BallerinaFunction; import org.ballerinalang.natives.annotations.Receiver; @@ -38,25 +36,26 @@ */ @BallerinaFunction( - orgName = ArtemisConstants.BALLERINA, packageName = ArtemisConstants.ARTEMIS, + orgName = ArtemisConstants.BALLERINA, + packageName = ArtemisConstants.ARTEMIS, functionName = "isClosed", - receiver = @Receiver(type = TypeKind.OBJECT, structType = ArtemisConstants.SESSION_OBJ, - structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS), + receiver = @Receiver( + type = TypeKind.OBJECT, + structType = ArtemisConstants.SESSION_OBJ, + structPackage = ArtemisConstants.PROTOCOL_PACKAGE_ARTEMIS + ), isPublic = true ) -public class IsClosed implements NativeCallableUnit { +public class IsClosed extends BlockingNativeCallableUnit { @Override - public void execute(Context context, CallableUnitCallback callableUnitCallback) { - @SuppressWarnings(ArtemisConstants.UNCHECKED) - BMap sessionObj = (BMap) context.getRefArgument(0); + public void execute(Context context) { + } + + public static boolean isClosed(Strand strand, ObjectValue sessionObj) { ClientSession session = (ClientSession) sessionObj.getNativeData(ArtemisConstants.ARTEMIS_SESSION); - context.setReturnValues(new BBoolean(session.isClosed())); + return session.isClosed(); } - @Override - public boolean isBlocking() { - return true; - } } diff --git a/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisCompilationTest.java b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisCompilationTest.java index 66c8251df19d..ab7c7b1692de 100644 --- a/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisCompilationTest.java +++ b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisCompilationTest.java @@ -18,9 +18,9 @@ package org.ballerinalang.messaging.artemis; -import org.ballerinalang.launcher.util.BAssertUtil; -import org.ballerinalang.launcher.util.BCompileUtil; -import org.ballerinalang.launcher.util.CompileResult; +import org.ballerinalang.test.util.BAssertUtil; +import org.ballerinalang.test.util.BCompileUtil; +import org.ballerinalang.test.util.CompileResult; import org.testng.Assert; import org.testng.annotations.Test; @@ -35,7 +35,7 @@ public class ArtemisCompilationTest { private static final Path TEST_PATH = Paths.get("src", "test", "resources", "test-src"); - @Test(description = "Successfully compiling Artemis service") + @Test(description = "Successfully compiling Artemis service", enabled = false) public void testValidService() { CompileResult compileResult = getCompileResult("artemis_success.bal"); diff --git a/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisDataBindingCompilationTest.java b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisDataBindingCompilationTest.java index 1b945bd76ce6..379fcc76bdbc 100644 --- a/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisDataBindingCompilationTest.java +++ b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/ArtemisDataBindingCompilationTest.java @@ -18,9 +18,9 @@ package org.ballerinalang.messaging.artemis; -import org.ballerinalang.launcher.util.BAssertUtil; -import org.ballerinalang.launcher.util.BCompileUtil; -import org.ballerinalang.launcher.util.CompileResult; +import org.ballerinalang.test.util.BAssertUtil; +import org.ballerinalang.test.util.BCompileUtil; +import org.ballerinalang.test.util.CompileResult; import org.testng.Assert; import org.testng.annotations.Test; @@ -33,7 +33,7 @@ public class ArtemisDataBindingCompilationTest { private static final Path TEST_PATH = Paths.get("src", "test", "resources", "test-src", "data-binding"); - @Test(description = "Successfully compiling Artemis services") + @Test(description = "Successfully compiling Artemis services", enabled = false) public void testValidService() { CompileResult compileResult = BCompileUtil.compile(TEST_PATH.resolve("artemis_success.bal").toAbsolutePath() .toString()); diff --git a/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/JBallerinaTestInitializer.java b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/JBallerinaTestInitializer.java new file mode 100644 index 000000000000..2e773e4cd725 --- /dev/null +++ b/stdlib/messaging/activemq-artemis/src/test/java/org/ballerinalang/messaging/artemis/JBallerinaTestInitializer.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.ballerinalang.messaging.artemis; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestContext; +import org.testng.ITestListener; +import org.testng.ITestResult; + +/** + * A test suit listener for jballerina test cases initialization. + * + * @since 0.995.0 + */ +public class JBallerinaTestInitializer implements ITestListener { + + private static Logger log = LoggerFactory.getLogger(JBallerinaTestInitializer.class); + private static final String ENABLE_JBALLERINA_TESTS = "enableJBallerinaTests"; + + @Override + public void onStart(ITestContext context) { + String property = context.getCurrentXmlTest().getParameter(ENABLE_JBALLERINA_TESTS); + if (property != null && Boolean.valueOf(property)) { + log.info("JBallerina tests initialized..."); + System.setProperty(ENABLE_JBALLERINA_TESTS, "true"); + } + } + + @Override + public void onFinish(ITestContext context) { + String property = context.getCurrentXmlTest().getParameter(ENABLE_JBALLERINA_TESTS); + if (property != null && Boolean.valueOf(property)) { + log.info("JBallerina tests disabled..."); + System.clearProperty(ENABLE_JBALLERINA_TESTS); + } + } + + @Override + public void onTestStart(ITestResult result) { + //ignore + } + + @Override + public void onTestSuccess(ITestResult result) { + //ignore + } + + @Override + public void onTestFailure(ITestResult result) { + //ignore + } + + @Override + public void onTestSkipped(ITestResult result) { + //ignore + } + + @Override + public void onTestFailedButWithinSuccessPercentage(ITestResult result) { + //ignore + } +} diff --git a/stdlib/messaging/activemq-artemis/src/test/resources/testng.xml b/stdlib/messaging/activemq-artemis/src/test/resources/testng.xml index ef8c6eb7177b..67f8be938c82 100644 --- a/stdlib/messaging/activemq-artemis/src/test/resources/testng.xml +++ b/stdlib/messaging/activemq-artemis/src/test/resources/testng.xml @@ -20,10 +20,14 @@ under the License. + + + + - + diff --git a/stdlib/utils/src/main/java/org/ballerinalang/utils/SimpleValueConvert.java b/stdlib/utils/src/main/java/org/ballerinalang/utils/SimpleValueConvert.java index fd7c2c48440d..b11ae68cac81 100644 --- a/stdlib/utils/src/main/java/org/ballerinalang/utils/SimpleValueConvert.java +++ b/stdlib/utils/src/main/java/org/ballerinalang/utils/SimpleValueConvert.java @@ -110,7 +110,7 @@ public void execute(Context ctx) { public static Object simpleValueConvert(Strand strand, TypedescValue typedescValue, Object inputValue) { org.ballerinalang.jvm.types.BType targetType = typedescValue.getDescribingType(); - if (inputValue == null) { + if (inputValue == null && targetType.getTag() != TypeTags.STRING_TAG) { return BallerinaErrors .createError(org.ballerinalang.jvm.util.exceptions.BallerinaErrorReasons.CONVERSION_ERROR, org.ballerinalang.jvm.util.exceptions.BLangExceptionHelper @@ -128,6 +128,9 @@ public static Object simpleValueConvert(Strand strand, TypedescValue typedescVal // function. try { if (targetType.getTag() == org.ballerinalang.jvm.types.TypeTags.STRING_TAG) { + if (inputValue == null) { + return "()"; + } return ((RefValue) inputValue).stringValue(); } return BallerinaErrors.createConversionError(inputValue, targetType); diff --git a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/anycast_message.bal b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/anycast_message.bal index e5c00f448643..41263827c56c 100644 --- a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/anycast_message.bal +++ b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/anycast_message.bal @@ -33,12 +33,12 @@ service anyCastConsumer on artemisListener { io:print("byte[] "); } else if (payload is map) { io:print("map "); - } else if (payload is map) { - io:print("map "); } else if (payload is map) { io:print("map "); } else if (payload is map) { io:print("map "); + } else if (payload is map) { + io:print("map "); } else if (payload is map) { io:print("map "); } else if (payload is map) { diff --git a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/data_binding.bal b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/data_binding.bal index 978048bf34d4..81e629a187a3 100644 --- a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/data_binding.bal +++ b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/consumers/data_binding.bal @@ -17,6 +17,10 @@ import ballerina/artemis; import ballerina/io; +artemis:Connection con = new("tcp://localhost:61616"); +artemis:Session session = new(con); +listener artemis:Listener artemisListener = new(session); + @artemis:ServiceConfig { queueConfig: { queueName: "queue1" diff --git a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/anycast_message.bal b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/anycast_message.bal index dff8fb43cd73..617afe2462eb 100644 --- a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/anycast_message.bal +++ b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/anycast_message.bal @@ -53,7 +53,7 @@ public function testSendMapFloat() { var err = prod->send(msg); } -public function testSendMapByte() { +public function main() { map msg = { "byte1": 1, "byte2": 7 diff --git a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/data_binding_message.bal b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/data_binding_message.bal index abc8b7e886dd..ca748cc50a1b 100644 --- a/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/data_binding_message.bal +++ b/tests/ballerina-integration-test/src/test/resources/messaging/artemis/producers/data_binding_message.bal @@ -95,7 +95,7 @@ public function testSendMapByteArray() { var err = prod->send(msg); } -public function testSendMapBoolean() { +public function main() { artemis:Producer prod = new(config, "queue12", addressConfig = addressConfig); map msg = { "first": true, diff --git a/tests/ballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java b/tests/ballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java index c6cf86a85e29..48c3e517b13e 100644 --- a/tests/ballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java +++ b/tests/ballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java @@ -23,6 +23,7 @@ import org.ballerinalang.model.values.BFloat; import org.ballerinalang.model.values.BInteger; import org.ballerinalang.model.values.BValue; +import org.ballerinalang.model.values.BValueType; import org.ballerinalang.test.util.BCompileUtil; import org.ballerinalang.test.util.BRunUtil; import org.ballerinalang.test.util.CompileResult; @@ -186,8 +187,7 @@ public void testIntAsByte(String functionName, int i) { Assert.assertEquals(returns.length, 2); Assert.assertSame(returns[0].getClass(), BBoolean.class); Assert.assertTrue(((BBoolean) returns[0]).booleanValue(), "expected bytes to be the same"); - Assert.assertSame(returns[1].getClass(), BByte.class); - Assert.assertEquals(((BByte) returns[1]).byteValue(), (new BInteger(i)).byteValue(), "incorrect int " + + Assert.assertEquals(((BValueType) returns[1]).byteValue(), (new BInteger(i)).byteValue(), "incorrect int " + "representation as byte"); } @@ -219,8 +219,7 @@ public void testByteAsInt(String functionName, long i) { Assert.assertEquals(returns.length, 2); Assert.assertSame(returns[0].getClass(), BBoolean.class); Assert.assertTrue(((BBoolean) returns[0]).booleanValue(), "expected ints to be the same"); - Assert.assertSame(returns[1].getClass(), BInteger.class); - Assert.assertEquals(((BInteger) returns[1]).intValue(), (new BByte(i)).intValue(), "incorrect byte " + + Assert.assertEquals(((BValueType) returns[1]).intValue(), (new BByte(i)).intValue(), "incorrect byte " + "representation as int"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprEvalPrecedenceTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprEvalPrecedenceTest.java index acd7359aeeba..f40820dc2fb6 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprEvalPrecedenceTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/binaryoperations/BinaryExprEvalPrecedenceTest.java @@ -22,7 +22,6 @@ import org.ballerinalang.test.util.BCompileUtil; import org.ballerinalang.test.util.BRunUtil; import org.ballerinalang.test.util.CompileResult; -import org.ballerinalang.util.exceptions.BLangRuntimeException; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -56,16 +55,15 @@ public void testBinaryOrExprWithLeftMostExprTrue() { Assert.assertEquals(actualResult, expectedResult); } - //TODO this expected NullPointerException should be properly handled at ballerina layer when - //TODO accessing non existing JSON elements. - @Test(description = "Test binary OR expression with " + - "left most expr evaluated to false expression.", expectedExceptions = {BLangRuntimeException.class}) + @Test(description = "Test binary OR expression with left most expr evaluated to false expression.") public void testBinaryOrExprWithLeftMostExprFalseNegativeCase() { boolean one = false; boolean two = false; boolean three = false; BValue[] args = {new BBoolean(one), new BBoolean(two), new BBoolean(three)}; - BRunUtil.invoke(result, "binaryOrExprWithLeftMostSubExprTrue", args); + BValue[] returns = BRunUtil.invoke(result, "binaryOrExprWithLeftMostSubExprTrue", args); + boolean actualResult = ((BBoolean) returns[0]).booleanValue(); + Assert.assertEquals(actualResult, one); } @Test(description = "Test binary AND expression with left most expr evaluated to false expression.") @@ -85,16 +83,15 @@ public void testBinaryAndExprWithLeftMostExprTrue() { Assert.assertEquals(actualResult, expectedResult); } - //TODO this expected NullPointerException should be properly handled at ballerina layer when - //TODO accessing non existing JSON elements. - @Test(description = "Test binary AND expression with " + - "left most expr evaluated to true expression.", expectedExceptions = {BLangRuntimeException.class}) + @Test(description = "Test binary AND expression with left most expr evaluated to true expression.") public void testBinaryAndExprWithLeftMostExprFalseNegativeCase() { boolean one = true; boolean two = false; boolean three = false; BValue[] args = {new BBoolean(one), new BBoolean(two), new BBoolean(three)}; - BRunUtil.invoke(result, "binaryANDExprWithLeftMostSubExprFalse", args); + BValue[] returns = BRunUtil.invoke(result, "binaryANDExprWithLeftMostSubExprFalse", args); + boolean actualResult = ((BBoolean) returns[0]).booleanValue(); + Assert.assertEquals(actualResult, false); } @Test(description = "Test multi binary expression with OR sub expressions inside If condition.") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionNegativeTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionNegativeTest.java index 93057cdf6bd9..6967de957182 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionNegativeTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionNegativeTest.java @@ -60,7 +60,7 @@ public void testIncompatibleJsonToStructWithErrors() { // check the error Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'json' value cannot be converted as 'Person'"); + Assert.assertEquals(errorMsg, "'json' value cannot be converted to 'Person'"); } @Test @@ -68,7 +68,7 @@ public void testEmptyJSONtoStructWithoutDefaults() { BValue[] returns = BRunUtil.invoke(negativeResult, "testEmptyJSONtoStructWithoutDefaults"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'json' value cannot be converted as " + Assert.assertEquals(errorMsg, "'json' value cannot be converted to " + "'StructWithoutDefaults'"); } @@ -77,7 +77,7 @@ public void testEmptyMaptoStructWithDefaults() { BValue[] returns = BRunUtil.invoke(negativeResult, "testEmptyMaptoStructWithDefaults"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'map' value cannot be converted as " + Assert.assertEquals(errorMsg, "'map' value cannot be converted to " + "'StructWithDefaults'"); } @@ -86,7 +86,7 @@ public void testEmptyMaptoStructWithoutDefaults() { BValue[] returns = BRunUtil.invoke(negativeResult, "testEmptyMaptoStructWithoutDefaults"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'map' value cannot be converted as " + Assert.assertEquals(errorMsg, "'map' value cannot be converted to " + "'StructWithoutDefaults'"); } @@ -94,7 +94,7 @@ public void testEmptyMaptoStructWithoutDefaults() { public void testTupleConversionFail() { BValue[] returns = BRunUtil.invoke(negativeResult, "testTupleConversionFail"); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: '(T1,T1)' value cannot be converted as '(T1," + Assert.assertEquals(errorMsg, "'(T1,T1)' value cannot be converted to '(T1," + "T2)'"); } @@ -103,7 +103,7 @@ public void testArrayToJsonFail() { BValue[] returns = BRunUtil.invoke(negativeResult, "testArrayToJsonFail"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'TX[]' value cannot be converted as 'json'"); + Assert.assertEquals(errorMsg, "'TX[]' value cannot be converted to 'json'"); } @Test(description = "Test passing tainted value with convert") @@ -140,7 +140,7 @@ public void testIncompatibleImplicitConversion() { BValue[] returns = BRunUtil.invoke(negativeResult, "testIncompatibleImplicitConversion"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'string' value 'abjd' cannot be converted as " + Assert.assertEquals(errorMsg, "'string' value 'abjd' cannot be converted to " + "'int'"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java index 0ee3f112b227..bc688762ed9f 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/conversion/NativeConversionTest.java @@ -232,8 +232,7 @@ public void testMapToJsonConversion() { @Test(description = "Test converting a struct with map of blob to a JSON", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'Info2' value cannot be converted as" - + " 'json'.*") + expectedExceptionsMessageRegExp = ".*'Info2' value cannot be converted to 'json'.*") public void testStructWithIncompatibleTypeToJson() { BRunUtil.invoke(compileResult, "testStructWithIncompatibleTypeToJson"); } @@ -263,22 +262,21 @@ public void testMapWithMissingOptionalFieldsToStruct() { @Test(description = "Test converting a map with incompatible inner array to a struct", expectedExceptions = { BLangRuntimeException.class }, expectedExceptionsMessageRegExp = - ".*incompatible convert operation: 'map' value cannot be converted as 'Person'.*") + ".*'map' value cannot be converted to 'Person'.*") public void testMapWithIncompatibleArrayToStruct() { BRunUtil.invoke(compileResult, "testMapWithIncompatibleArrayToStruct"); } @Test(description = "Test converting a map with incompatible inner struct to a struct", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'map' value cannot be converted " - + "as 'Employee'.*") + expectedExceptionsMessageRegExp = ".*'map' value cannot be converted to 'Employee'.*") public void testMapWithIncompatibleStructToStruct() { BRunUtil.invoke(compileResult, "testMapWithIncompatibleStructToStruct"); } @Test(description = "Test converting a incompatible JSON to a struct", expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to " + "'Person'.*") public void testIncompatibleJsonToStruct() { BRunUtil.invoke(compileResult, "testIncompatibleJsonToStruct"); @@ -295,48 +293,45 @@ public void testJsonToStructWithMissingOptionalFields() { @Test(description = "Test converting a incompatible JSON to a struct", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"incompatible " - + "convert operation: 'json' value cannot be converted as 'Person'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"'json' value " + + "cannot be converted to 'Person'\"\\}.*") public void testJsonToStructWithMissingRequiredFields() { BRunUtil.invoke(compileResult, "testJsonToStructWithMissingRequiredFields"); } @Test(description = "Test converting a JSON with incompatible inner map to a struct", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"incompatible " - + "convert operation: 'json' value cannot be converted as 'Person'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"'json' value " + + "cannot be converted to 'Person'\"\\}.*") public void testJsonWithIncompatibleMapToStruct() { BRunUtil.invoke(compileResult, "testJsonWithIncompatibleMapToStruct"); } @Test(description = "Test converting a JSON with incompatible inner struct to a struct", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"incompatible " - + "convert operation: 'json' value cannot be converted as 'Person'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"'json' value " + + "cannot be converted to 'Person'\"\\}.*") public void testJsonWithIncompatibleStructToStruct() { BRunUtil.invoke(compileResult, "testJsonWithIncompatibleStructToStruct"); } @Test(description = "Test converting a JSON array to a struct", expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json\\[\\]' value cannot be converted" - + " as 'Person'.*") + expectedExceptionsMessageRegExp = ".*'json\\[\\]' value cannot be converted to 'Person'.*") public void testJsonArrayToStruct() { BRunUtil.invoke(compileResult, "testJsonArrayToStruct"); } @Test(description = "Test converting a JSON with incompatible inner type to a struct", expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " - + "'Person'.*") + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to 'Person'.*") public void testJsonWithIncompatibleTypeToStruct() { BRunUtil.invoke(compileResult, "testJsonWithIncompatibleTypeToStruct"); } @Test(description = "Test converting a struct with map of blob to a JSON", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'Info' value cannot be converted as " - + "'json'.*") + expectedExceptionsMessageRegExp = ".*'Info' value cannot be converted to 'json'.*") public void testStructWithIncompatibleTypeMapToJson() { BRunUtil.invoke(compileResult, "testStructWithIncompatibleTypeMapToJson"); } @@ -399,7 +394,7 @@ public void testJsonIntArrayToStringArray() { @Test(description = "Test converting a JSON array to xml array", expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to " + "'XmlArray.*") public void testJsonToXmlArray() { BRunUtil.invoke(compileResult, "testJsonToXmlArray"); @@ -416,15 +411,15 @@ public void testNullJsonToArray() { @Test(description = "Test converting a JSON null to string array", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"incompatible " - + "convert operation: 'json' value cannot be converted as 'StringArray'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}ConversionError \\{\"message\":\"'json' value " + + "cannot be converted to 'StringArray'\"\\}.*") public void testNullJsonArrayToArray() { BRunUtil.invoke(compileResult, "testNullJsonArrayToArray"); } @Test(description = "Test converting a JSON string to string array", expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to " + "'StringArray.*") public void testNonArrayJsonToArray() { BRunUtil.invoke(compileResult, "testNonArrayJsonToArray"); @@ -583,7 +578,7 @@ public void testJsonToMapConstrained2() { @Test(description = "Test converting json to constrained map", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to " + "'map'.*") public void testJsonToMapConstrainedFail() { BRunUtil.invoke(compileResult, "testJsonToMapConstrainedFail"); @@ -655,7 +650,7 @@ public void testJsonToArray2() { @Test(description = "Test an invalid json to array conversion", expectedExceptions = { BLangRuntimeException.class }, - expectedExceptionsMessageRegExp = ".*incompatible convert operation: 'json' value cannot be converted as " + expectedExceptionsMessageRegExp = ".*'json' value cannot be converted to " + "'int\\[\\]'.*") public void testJsonToArrayFail() { BRunUtil.invoke(compileResult, "testJsonToArrayFail"); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/fieldaccess/SafeNavigationTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/fieldaccess/SafeNavigationTest.java index b4babb59ffe8..4283ce16dda1 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/fieldaccess/SafeNavigationTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/fieldaccess/SafeNavigationTest.java @@ -231,9 +231,9 @@ public void testJSONNilLiftingOnLHS_1() { Assert.assertEquals(returns[3].stringValue(), "{\"info\":{\"address4\":{\"city\":\"Jaffna\"}}}"); } - @Test(expectedExceptions = {BLangRuntimeException.class}, - expectedExceptionsMessageRegExp = "error: failed to get element from json: " + - "\\{\"message\":\"array index out of range: index: 2, size: 0\"\\}.*") + @Test(expectedExceptions = { BLangRuntimeException.class }, + expectedExceptionsMessageRegExp = "error: failed to get element from json: array index out of range:" + + " index: 2, size: 0.*") public void testJSONNilLiftingOnLHS_2() { BRunUtil.invoke(result, "testJSONNilLiftingOnLHS_2"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java index c6cf86a85e29..5208854faae7 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/NumericConversionTest.java @@ -23,6 +23,7 @@ import org.ballerinalang.model.values.BFloat; import org.ballerinalang.model.values.BInteger; import org.ballerinalang.model.values.BValue; +import org.ballerinalang.model.values.BValueType; import org.ballerinalang.test.util.BCompileUtil; import org.ballerinalang.test.util.BRunUtil; import org.ballerinalang.test.util.CompileResult; @@ -186,8 +187,7 @@ public void testIntAsByte(String functionName, int i) { Assert.assertEquals(returns.length, 2); Assert.assertSame(returns[0].getClass(), BBoolean.class); Assert.assertTrue(((BBoolean) returns[0]).booleanValue(), "expected bytes to be the same"); - Assert.assertSame(returns[1].getClass(), BByte.class); - Assert.assertEquals(((BByte) returns[1]).byteValue(), (new BInteger(i)).byteValue(), "incorrect int " + + Assert.assertEquals(((BValueType) returns[1]).byteValue(), (new BInteger(i)).byteValue(), "incorrect int " + "representation as byte"); } @@ -219,8 +219,7 @@ public void testByteAsInt(String functionName, long i) { Assert.assertEquals(returns.length, 2); Assert.assertSame(returns[0].getClass(), BBoolean.class); Assert.assertTrue(((BBoolean) returns[0]).booleanValue(), "expected ints to be the same"); - Assert.assertSame(returns[1].getClass(), BInteger.class); - Assert.assertEquals(((BInteger) returns[1]).intValue(), (new BByte(i)).intValue(), "incorrect byte " + + Assert.assertEquals(((BValueType) returns[1]).intValue(), (new BByte(i)).intValue(), "incorrect byte " + "representation as int"); } @@ -271,10 +270,10 @@ public void testInvalidDecimalAsByte(int i) { } @Test(dataProvider = "invalidByteValues", expectedExceptions = BLangRuntimeException.class, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}NumberConversionError \\{\"message\":\"'decimal'" + - " value '.*' cannot be converted to 'byte'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}TypeCastError \\{\"message\":\"incompatible " + + "types: 'decimal' cannot be cast to 'byte\\|Employee'\"}.*") public void testInvalidDecimalAsByteInUnions(int i) { - BRunUtil.invoke(result, "testDecimalAsByteInUnions", new BValue[]{new BDecimal(new BigDecimal(i))}); + BRunUtil.invoke(result, "testDecimalAsByteInUnions", new BValue[] { new BDecimal(new BigDecimal(i)) }); } @Test(dataProvider = "naNFloatAsByteTests", expectedExceptions = BLangRuntimeException.class, @@ -306,15 +305,15 @@ public void testInfiniteFloatAsInt(String functionName) { } @Test(dataProvider = "outOfRangeFloatAsIntTests", expectedExceptions = BLangRuntimeException.class, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}NumberConversionError \\{\"message\":\"out of " + - "range 'float' value '.*' cannot be converted to 'int'\"\\}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}NumberConversionError \\{\"message\":\"" + + "'float' value '.*' cannot be converted to 'int'\"\\}.*") public void testOutOfRangeFloatAsInt(String functionName) { BRunUtil.invoke(result, functionName, new BValue[0]); } @Test(dataProvider = "outOfRangeDecimalAsIntTests", expectedExceptions = BLangRuntimeException.class, - expectedExceptionsMessageRegExp = "error: \\{ballerina\\}NumberConversionError \\{\"message\":\"out of " + - "range 'decimal' value '.*' cannot be converted to 'int'\"}.*") + expectedExceptionsMessageRegExp = "error: \\{ballerina\\}NumberConversionError \\{\"message\":\"" + + "'decimal' value '.*' cannot be converted to 'int'\"}.*") public void testOutOfRangeDecimalAsInt(String functionName) { BRunUtil.invoke(result, functionName, new BValue[0]); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java index 1f01cee822d4..a1a2089fd30e 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExprTest.java @@ -320,8 +320,7 @@ public void testIncompatibleJsonToInt() { Assert.assertTrue(returns[0] instanceof BError); BError error = (BError) returns[0]; String errorMsg = ((BMap) error.getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'string' value 'hello' cannot be converted as " - + "'int'"); + Assert.assertEquals(errorMsg, "'string' value 'hello' cannot be converted to 'int'"); } @Test @@ -330,8 +329,7 @@ public void testIncompatibleJsonToFloat() { Assert.assertTrue(returns[0] instanceof BError); BError error = (BError) returns[0]; String errorMsg = ((BMap) error.getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'string' value 'hello' cannot be converted as " - + "'float'"); + Assert.assertEquals(errorMsg, "'string' value 'hello' cannot be converted to 'float'"); } @Test @@ -562,7 +560,7 @@ public void testInCompatibleStructForceCasting() { Assert.assertTrue(returns[0] instanceof BError); BError error = (BError) returns[0]; String errorMsg = ((BMap) error.getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, "incompatible convert operation: 'B' value cannot be converted as 'A'"); + Assert.assertEquals(errorMsg, "'B' value cannot be converted to 'A'"); } @Test (description = "Test any to int casting happens without errors, error struct should be null") @@ -597,8 +595,7 @@ public void testAnyNullToString() { BValue[] returns = BRunUtil.invoke(result, "testAnyNullToString"); // null to string should return string null - Assert.assertEquals(returns[0].stringValue(), "{ballerina}ConversionError {\"message\":\"cannot convert " - + "'null' value to type 'string'\"}"); + Assert.assertEquals(returns[0].stringValue(), "()"); } @Test diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java index b4cf906e6bfc..a4335a3a08b6 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/expressions/typecast/TypeCastExpressionsTest.java @@ -81,7 +81,7 @@ public void testNilValueCastAsStructuredTypeNegative() { @Test(expectedExceptions = BLangRuntimeException.class, expectedExceptionsMessageRegExp = "error: \\{ballerina\\}TypeCastError \\{\"message\":\"incompatible " + - "types: 'string\\|int\\|null\\[2\\]' cannot be cast to 'string\\[2\\]'\"\\}.*") + "types: 'string\\|int\\|\\(\\)\\[2\\]' cannot be cast to 'string\\[2\\]'\"\\}.*") public void testArrayCastNegative() { BRunUtil.invoke(result, "testArrayCastNegative"); } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/foreach/ForeachJSONTests.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/foreach/ForeachJSONTests.java index f3a499069549..8e7c3ba1b03d 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/foreach/ForeachJSONTests.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/statements/foreach/ForeachJSONTests.java @@ -65,8 +65,8 @@ public void testArrayOfJSON() { @Test public void testJSONString() { - String result = "{ballerina}ConversionError {\"message\":\"incompatible convert operation: 'string' value " - + "cannot be converted as 'map'\"}"; + String result = "{ballerina}ConversionError {\"message\":\"'string' value " + + "cannot be converted to 'map'\"}"; BValue[] returns = BRunUtil.invoke(program, "testJSONString"); Assert.assertEquals(returns.length, 1); Assert.assertEquals(returns[0].stringValue(), result); @@ -74,8 +74,8 @@ public void testJSONString() { @Test public void testJSONNumber() { - String result = "{ballerina}ConversionError {\"message\":\"incompatible convert operation: 'int' value cannot" - + " be converted as 'map'\"}"; + String result = "{ballerina}ConversionError {\"message\":\"'int' value cannot" + + " be converted to 'map'\"}"; BValue[] returns = BRunUtil.invoke(program, "testJSONNumber"); Assert.assertEquals(returns.length, 1); Assert.assertEquals(returns[0].stringValue(), result); @@ -83,8 +83,8 @@ public void testJSONNumber() { @Test public void testJSONBoolean() { - String result = "{ballerina}ConversionError {\"message\":\"incompatible convert operation: 'boolean' value " - + "cannot be converted as 'map'\"}"; + String result = "{ballerina}ConversionError {\"message\":\"'boolean' value " + + "cannot be converted to 'map'\"}"; BValue[] returns = BRunUtil.invoke(program, "testJSONBoolean"); Assert.assertEquals(returns.length, 1); Assert.assertEquals(returns[0].stringValue(), result); diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueNegativeTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueNegativeTest.java index 9991459e3e80..baf1cb328259 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueNegativeTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/bytetype/BByteValueNegativeTest.java @@ -95,7 +95,7 @@ public void byteValueRuntimeNegative1() { Assert.assertEquals(returnValue.length, 1); Assert.assertTrue(returnValue[0] instanceof BError); Assert.assertEquals(returnValue[0].stringValue(), "{ballerina}NumberConversionError {\"message\":" + - "\"incompatible convert operation: 'int' value '-12' cannot be converted as 'byte'\"}"); + "\"'int' value '-12' cannot be converted to 'byte'\"}"); } @Test(description = "Test int to byte conversion negative") @@ -104,7 +104,7 @@ public void byteValueRuntimeNegative2() { Assert.assertEquals(returnValue.length, 1); Assert.assertTrue(returnValue[0] instanceof BError); Assert.assertEquals(returnValue[0].stringValue(), "{ballerina}NumberConversionError {\"message\":" + - "\"incompatible convert operation: 'int' value '-257' cannot be converted as 'byte'\"}"); + "\"'int' value '-257' cannot be converted to 'byte'\"}"); } @Test(description = "Test int to byte conversion negative") @@ -113,6 +113,6 @@ public void byteValueRuntimeNegative3() { Assert.assertEquals(returnValue.length, 1); Assert.assertTrue(returnValue[0] instanceof BError); Assert.assertEquals(returnValue[0].stringValue(), "{ballerina}NumberConversionError {\"message\":" + - "\"incompatible convert operation: 'int' value '12,345' cannot be converted as 'byte'\"}"); + "\"'int' value '12,345' cannot be converted to 'byte'\"}"); } } diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/ConstrainedMapTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/ConstrainedMapTest.java index 59f7dd0c09b2..d04acb724f6a 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/ConstrainedMapTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/map/ConstrainedMapTest.java @@ -431,8 +431,7 @@ public void testJsonToStructConversionStructWithConstrainedMapNegative() { "testJsonToStructConversionStructWithConstrainedMapNegative"); Assert.assertTrue(returns[0] instanceof BError); String errorMsg = ((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(); - Assert.assertEquals(errorMsg, - "incompatible convert operation: 'json' value cannot be converted as 'PersonComplexTwo'"); + Assert.assertEquals(errorMsg, "'json' value cannot be converted to 'PersonComplexTwo'"); } @Test(description = "Test constrained map with union retrieving string value.") diff --git a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/var/VarDeclaredAssignmentStmtTest.java b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/var/VarDeclaredAssignmentStmtTest.java index 6690ea74e438..b0d2b5e3dd85 100644 --- a/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/var/VarDeclaredAssignmentStmtTest.java +++ b/tests/jballerina-unit-test/src/test/java/org/ballerinalang/test/types/var/VarDeclaredAssignmentStmtTest.java @@ -207,7 +207,7 @@ public void testIncompatibleJsonToStructWithErrors() { Assert.assertSame(returns[0].getClass(), BError.class); Assert.assertEquals(((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(), - "incompatible convert operation: 'json' value cannot be converted as 'Person'"); + "'json' value cannot be converted to 'Person'"); } @Test(description = "Test incompatible json to struct with errors.") @@ -219,7 +219,7 @@ public void testJsonToStructWithErrors() { Assert.assertSame(returns[0].getClass(), BError.class); Assert.assertEquals(((BMap) ((BError) returns[0]).getDetails()).get("message").stringValue(), - "incompatible convert operation: 'json' value cannot be converted as 'PersonA'"); + "'json' value cannot be converted to 'PersonA'"); } @Test(description = "Test compatible struct with force casting.") diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/numeric_conversion.bal b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/numeric_conversion.bal index 3b601ee88d21..87dbd3ac67c2 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/numeric_conversion.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/numeric_conversion.bal @@ -15,14 +15,14 @@ // under the License. //////////////////////// from float //////////////////////// -function testFloatAsFloat(float f1) returns (boolean, float) { +function testFloatAsFloat(float f1) returns [boolean, float] { float s3 = f1; anydata s4 = getFloat(f1); - return (s3 == s4 && s4 is float, s3); + return [s3 == s4 && s4 is float, s3]; } -function testFloatAsFloatInUnions(float f1) returns (boolean, float) { +function testFloatAsFloatInUnions(float f1) returns [boolean, float] { Employee|string|float f2 = f1; json f3 = f1; anydata f4 = f1; @@ -33,17 +33,17 @@ function testFloatAsFloatInUnions(float f1) returns (boolean, float) { float s8 = f4; float s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testFloatAsDecimal(float f1) returns (boolean, decimal) { +function testFloatAsDecimal(float f1) returns [boolean, decimal] { decimal s3 = f1; anydata s4 = getFloat(f1); - return (s3 == s4 && s4 is decimal, s3); + return [s3 == s4 && s4 is decimal, s3]; } -function testFloatAsDecimalInUnions(float f1) returns (boolean, decimal) { +function testFloatAsDecimalInUnions(float f1) returns [boolean, decimal] { Employee|string|float f2 = f1; json f3 = f1; anydata f4 = getFloat(f1); @@ -54,17 +54,17 @@ function testFloatAsDecimalInUnions(float f1) returns (boolean, decimal) { decimal s8 = f4; decimal s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testFloatAsInt(float f1) returns (boolean, int) { +function testFloatAsInt(float f1) returns [boolean, int] { int s3 = f1; anydata s4 = getFloat(f1); - return (s3 == s4 && s4 is int, s3); + return [s3 == s4 && s4 is int, s3]; } -function testFloatAsIntInUnions(float f1) returns (boolean, int) { +function testFloatAsIntInUnions(float f1) returns [boolean, int] { Employee|string|float f2 = f1; json f3 = f1; anydata f4 = getFloat(f1); @@ -75,17 +75,17 @@ function testFloatAsIntInUnions(float f1) returns (boolean, int) { int s8 = f4; int|string s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testFloatAsByte(float f1) returns (boolean, byte) { +function testFloatAsByte(float f1) returns [boolean, byte] { byte s3 = f1; anydata s4 = getFloat(f1); - return (s3 == s4 && s4 is byte, s3); + return [s3 == s4 && s4 is byte, s3]; } -function testFloatAsByteInUnions(float f1) returns (boolean, byte) { +function testFloatAsByteInUnions(float f1) returns [boolean, byte] { Employee|string|float f2 = f1; json f3 = f1; anydata f4 = getFloat(f1); @@ -96,18 +96,18 @@ function testFloatAsByteInUnions(float f1) returns (boolean, byte) { byte s8 = f4; byte|string s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } //////////////////////// from decimal //////////////////////// -function testDecimalAsFloat(decimal f1) returns (boolean, float) { +function testDecimalAsFloat(decimal f1) returns [boolean, float] { float s3 = f1; anydata s4 = getDecimal(f1); - return (s3 == s4 && s4 is float, s3); + return [s3 == s4 && s4 is float, s3]; } -function testDecimalAsFloatInUnions(decimal f1) returns (boolean, float|Employee|boolean|string) { +function testDecimalAsFloatInUnions(decimal f1) returns [boolean, float|Employee|boolean|string] { Employee|string|decimal f2 = f1; json f3 = f1; anydata f4 = f1; @@ -118,17 +118,17 @@ function testDecimalAsFloatInUnions(decimal f1) returns (boolean, float|Employee float s8 = f4; float s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testDecimalAsDecimal(decimal f1) returns (boolean, decimal) { +function testDecimalAsDecimal(decimal f1) returns [boolean, decimal] { decimal s3 = f1; anydata s4 = getDecimal(f1); - return (s3 == s4 && s4 is decimal, s3); + return [s3 == s4 && s4 is decimal, s3]; } -function testDecimalAsDecimalInUnions(decimal f1) returns (boolean, decimal|string) { +function testDecimalAsDecimalInUnions(decimal f1) returns [boolean, decimal|string] { Employee|string|decimal f2 = f1; json f3 = f1; anydata f4 = f1; @@ -139,16 +139,16 @@ function testDecimalAsDecimalInUnions(decimal f1) returns (boolean, decimal|stri decimal s8 = f4; decimal s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testDecimalAsInt(decimal f1) returns (boolean, int) { +function testDecimalAsInt(decimal f1) returns [boolean, int] { int s3 = f1; anydata s4 = getDecimal(f1); - return (s3 == s4 && s4 is int, s3); + return [s3 == s4 && s4 is int, s3]; } -function testDecimalAsIntInUnions(decimal f1) returns (boolean, int) { +function testDecimalAsIntInUnions(decimal f1) returns [boolean, int] { Employee|string|decimal f2 = f1; json f3 = f1; anydata f4 = f1; @@ -159,16 +159,16 @@ function testDecimalAsIntInUnions(decimal f1) returns (boolean, int) { int s8 = f4; int s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testDecimalAsByte(decimal f1) returns (boolean, byte) { +function testDecimalAsByte(decimal f1) returns [boolean, byte] { byte s3 = f1; anydata s4 = getDecimal(f1); - return (s3 == s4 && s4 is byte, s3); + return [s3 == s4 && s4 is byte, s3]; } -function testDecimalAsByteInUnions(decimal f1) returns (boolean, byte) { +function testDecimalAsByteInUnions(decimal f1) returns [boolean, byte] { Employee|string|decimal f2 = f1; json f3 = f1; anydata f4 = f1; @@ -179,18 +179,18 @@ function testDecimalAsByteInUnions(decimal f1) returns (boolean, byte) { byte s8 = f4; byte s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s9); + return [s7 == s6 && s7 == s8 && s9 == s8, s9]; } //////////////////////// from int //////////////////////// -function testIntAsFloat(int f1) returns (boolean, float) { +function testIntAsFloat(int f1) returns [boolean, float] { float s3 = f1; anydata s4 = getInt(f1); - return (s3 == s4 && s4 is float, s3); + return [s3 == s4 && s4 is float, s3]; } -function testIntAsFloatInUnions(int f1) returns (boolean, float) { +function testIntAsFloatInUnions(int f1) returns [boolean, float] { string|int|boolean f2 = f1; json f3 = f1; anydata f4 = f1; @@ -201,17 +201,17 @@ function testIntAsFloatInUnions(int f1) returns (boolean, float) { float|Employee|map s8 = > f4; float s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testIntAsDecimal(int f1) returns (boolean, decimal) { +function testIntAsDecimal(int f1) returns [boolean, decimal] { decimal s3 = f1; anydata s4 = getInt(f1); - return (s3 == s4 && s4 is decimal, s3); + return [s3 == s4 && s4 is decimal, s3]; } -function testIntAsDecimalInUnions(int f1) returns (boolean, decimal) { +function testIntAsDecimalInUnions(int f1) returns [boolean, decimal] { string|int|boolean f2 = f1; json f3 = f1; anydata f4 = f1; @@ -222,16 +222,16 @@ function testIntAsDecimalInUnions(int f1) returns (boolean, decimal) { decimal|Employee|map s8 = > f4; decimal s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testIntAsInt(int f1) returns (boolean, int) { +function testIntAsInt(int f1) returns [boolean, int] { int s3 = f1; anydata s4 = getInt(f1); - return (s3 == s4 && s4 is int, s3); + return [s3 == s4 && s4 is int, s3]; } -function testIntAsIntInUnions(int f1) returns (boolean, int|boolean) { +function testIntAsIntInUnions(int f1) returns [boolean, int|boolean] { Employee|string|int f2 = f1; json f3 = f1; anydata f4 = f1; @@ -242,16 +242,16 @@ function testIntAsIntInUnions(int f1) returns (boolean, int|boolean) { int s8 = f4; int s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } -function testIntAsByte(int f1) returns (boolean, byte) { +function testIntAsByte(int f1) returns [boolean, byte] { byte s3 = f1; anydata s4 = getInt(f1); - return (s3 == s4 && s4 is byte, s3); + return [s3 == s4 && s4 is byte, s3]; } -function testIntAsByteInUnions(int f1) returns (boolean, byte|boolean) { +function testIntAsByteInUnions(int f1) returns [boolean, byte|boolean] { Employee|string|int f2 = f1; json f3 = f1; anydata f4 = f1; @@ -262,18 +262,18 @@ function testIntAsByteInUnions(int f1) returns (boolean, byte|boolean) { byte s8 = f4; byte s9 = f5; - return (s7 == s6 && s7 == s8 && s9 == s8, s6); + return [s7 == s6 && s7 == s8 && s9 == s8, s6]; } //////////////////////// from byte //////////////////////// -function testByteAsFloat(byte f1) returns (boolean, float) { +function testByteAsFloat(byte f1) returns [boolean, float] { float s3 = f1; anydata s4 = getByte(f1); - return (s3 == s4 && s4 is float, s3); + return [s3 == s4 && s4 is float, s3]; } -function testByteAsFloatInUnions(byte f1) returns (boolean, float) { +function testByteAsFloatInUnions(byte f1) returns [boolean, float] { string|byte|boolean f2 = f1; anydata f3 = f1; any f4 = f1; @@ -282,17 +282,17 @@ function testByteAsFloatInUnions(byte f1) returns (boolean, float) { float|string s7 = f3; float|Employee|map s8 = > f4; - return (s7 == s6 && s7 == s8, s6); + return [s7 == s6 && s7 == s8, s6]; } -function testByteAsDecimal(byte f1) returns (boolean, decimal) { +function testByteAsDecimal(byte f1) returns [boolean, decimal] { decimal s3 = f1; anydata s4 = getByte(f1); - return (s3 == s4 && s4 is decimal, s3); + return [s3 == s4 && s4 is decimal, s3]; } -function testByteAsDecimalInUnions(byte f1) returns (boolean, decimal) { +function testByteAsDecimalInUnions(byte f1) returns [boolean, decimal] { string|byte f2 = f1; anydata f3 = f1; any f4 = f1; @@ -301,16 +301,16 @@ function testByteAsDecimalInUnions(byte f1) returns (boolean, decimal) { decimal|string s7 = f3; decimal|Employee|map s8 = > f4; - return (s7 == s6 && s7 == s8, s6); + return [s7 == s6 && s7 == s8, s6]; } -function testByteAsInt(byte f1) returns (boolean, int) { +function testByteAsInt(byte f1) returns [boolean, int] { int s3 = f1; anydata s4 = getByte(f1); - return (s3 == s4 && s4 is int, s3); + return [s3 == s4 && s4 is int, s3]; } -function testByteAsIntInUnions(byte f1) returns (boolean, int|boolean) { +function testByteAsIntInUnions(byte f1) returns [boolean, int|boolean] { Employee|byte f2 = f1; anydata f3 = f1; any f4 = f1; @@ -319,16 +319,16 @@ function testByteAsIntInUnions(byte f1) returns (boolean, int|boolean) { int s7 = f3; int s8 = f4; - return (s7 == s6 && s7 == s8, s6); + return [s7 == s6 && s7 == s8, s6]; } -function testByteAsByte(byte f1) returns (boolean, byte) { +function testByteAsByte(byte f1) returns [boolean, byte] { byte s3 = f1; anydata s4 = getByte(f1); - return (s3 == s4 && s4 is byte, s3); + return [s3 == s4 && s4 is byte, s3]; } -function testByteAsByteInUnions(byte f1) returns (boolean, byte|boolean) { +function testByteAsByteInUnions(byte f1) returns [boolean, byte|boolean] { Employee|string|byte f2 = f1; anydata f3 = f1; any f4 = f1; @@ -337,7 +337,7 @@ function testByteAsByteInUnions(byte f1) returns (boolean, byte|boolean) { byte s7 = f3; byte s8 = f4; - return (s7 == s6 && s7 == s8, s6); + return [s7 == s6 && s7 == s8, s6]; } function testNaNFloatAsByte() { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type-casting.bal b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type-casting.bal index 04d9f88b8ab4..9d59292b10a8 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type-casting.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type-casting.bal @@ -482,7 +482,7 @@ function testSameTypeCast() returns int { return b; } -function testJSONValueCasting() returns (string|error, int|error, float|error, boolean|error) { +function testJSONValueCasting() returns [string|error, int|error, float|error, boolean|error] { // json to string json j1 = "hello"; @@ -500,7 +500,7 @@ function testJSONValueCasting() returns (string|error, int|error, float|error, b json j4 = true; var b = j4; - return (s, i, f, b); + return [s, i, f, b]; } function testAnyToTable() returns table|error { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type_cast_expr.bal b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type_cast_expr.bal index cfb337eeec02..2a8ab54080b2 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type_cast_expr.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/expressions/typecast/type_cast_expr.bal @@ -227,21 +227,21 @@ function testArrayCastNegative() { } function testTupleCastPositive() returns boolean { - (string, int, float) s = ("this is an array", 1, 3.0); + [string, int, float] s = ["this is an array", 1, 3.0]; any a = s; - (string, int, float) s2 = <(string, int, float)> a; + [string, int, float] s2 = <[string, int, float]> a; - (string, int|string, float) s3 = ("this is an array", 1, 3.0); + [string, int|string, float] s3 = ["this is an array", 1, 3.0]; anydata a2 = s3; - (string, int|string, float) s4 = <(string, int|string, float)> a2; + [string, int|string, float] s4 = <[string, int|string, float]> a2; return s === s2 && s3 === s4; } function testTupleCastNegative() { - (string, int|string, float) s = ("this is an array", 1, 3.0); + [string, int|string, float] s = ["this is an array", 1, 3.0]; any a = s; - (string, int|string, float) s2 = <(string, int, float)> a; + [string, int|string, float] s2 = <[string, int, float]> a; } function testJsonCastPositive() returns boolean { @@ -477,7 +477,7 @@ function testListElementCastPositive() returns boolean { string sVal = "Hello from Ballerina"; any[] anyArr = [iValTwo, sVal, bVal]; - (Employee, int, any[]) t1 = (e1, iVal, anyArr); + [Employee, int, any[]] t1 = [e1, iVal, anyArr]; any a = t1[2]; any[] anyArrTwo = a; @@ -493,7 +493,7 @@ function testListElementCastNegative() { string sVal = "Hello from Ballerina"; any[] anyArr = [sVal, bVal]; - (Employee, int, any[]) t1 = (e1, iVal, anyArr); + [Employee, int, any[]] t1 = [e1, iVal, anyArr]; any a = t1[2]; any[] anyArrTwo = a; @@ -584,7 +584,7 @@ function testStringInUnionAsString(string s1) returns boolean { //////////////////////// from boolean //////////////////////// -function testBooleanAsBoolean() returns (boolean, boolean, boolean, boolean) { +function testBooleanAsBoolean() returns [boolean, boolean, boolean, boolean] { boolean b1 = true; boolean s1 = b1; anydata a = getBoolean(b1); @@ -597,10 +597,10 @@ function testBooleanAsBoolean() returns (boolean, boolean, boolean, boolean) { boolean s3 = b1; boolean s4 = getBoolean(b1); - return (s1, s2, s3, s4); + return [s1, s2, s3, s4]; } -function testBooleanInUnionAsBoolean() returns (boolean, boolean) { +function testBooleanInUnionAsBoolean() returns [boolean, boolean] { boolean f1 = true; Employee|string|int|boolean f2 = f1; json f3 = true; @@ -627,7 +627,7 @@ function testBooleanInUnionAsBoolean() returns (boolean, boolean) { boolean ft2 = (s7 == s6 && s7 == s8 && s9 == s8) ? s6 : true; - return(ft1, ft2); + return [ft1, ft2]; } function testSimpleTypeToUnionCastPositive() returns boolean { @@ -666,11 +666,11 @@ function testDirectlyUnmatchedUnionToUnionCastNegative_2() { Lead|int v4 = v3; } -function testTypeCastOnRecordLiterals() returns (string, string, string) { +function testTypeCastOnRecordLiterals() returns [string, string, string] { string s1 = init({}); string s2 = init({}); string s3 = init({}); - return (s1, s2, s3); + return [s1, s2, s3]; } function init(InMemoryModeConfig|ServerModeConfig|EmbeddedModeConfig rec) returns string { diff --git a/tests/jballerina-unit-test/src/test/resources/test-src/statements/foreach/foreach-arrays-typed-binding-patterns.bal b/tests/jballerina-unit-test/src/test/resources/test-src/statements/foreach/foreach-arrays-typed-binding-patterns.bal index 36e6e47232ed..ae526ba8a60f 100644 --- a/tests/jballerina-unit-test/src/test/resources/test-src/statements/foreach/foreach-arrays-typed-binding-patterns.bal +++ b/tests/jballerina-unit-test/src/test/resources/test-src/statements/foreach/foreach-arrays-typed-binding-patterns.bal @@ -1,5 +1,3 @@ -string output = ""; - type Data record { int i; string v; @@ -15,92 +13,80 @@ type Data3 record { [int, string] v; }; -function concatIntString(int i, string s) { - output = output + i + ":" + s + " "; -} - -function concatIntStringFloat(int i, string s, float f) { - output = output + i + ":" + s + ":" + f + " "; -} - -function concatIntIntString(int i1, int i2, string s) { - output = output + i1 + ":" + i2 + ":" + s + " "; -} - // --------------------------------------------------------------------------------------------------------------------- function testArrayWithSimpleVariableWithoutType() returns string { - output = ""; + string output = ""; string[] arr = ["A", "B", "C"]; int i = 0; foreach var v in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; i += 1; } return output; } function testArrayWithSimpleVariableWithType() returns string { - output = ""; + string output = ""; string[] arr = ["A", "B", "C"]; int i = 0; foreach string v in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; i += 1; } return output; } function testArrayWithTupleWithoutType() returns string { - output = ""; + string output = ""; [int, string][] arr = [[1, "A"], [2, "B"], [3, "C"]]; foreach var [i, v] in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; } return output; } function testArrayWithTupleWithType() returns string { - output = ""; + string output = ""; [int, string][] arr = [[1, "A"], [2, "B"], [3, "C"]]; foreach [int, string] [i, v] in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; } return output; } function testArrayWithTupleInTupleWithoutType() returns string { - output = ""; + string output = ""; [int, [string, float]][] arr = [[1, ["A", 2.0]], [2, ["B", 3.0]], [3, ["C", 4.0]]]; foreach var [i, [s, f]] in arr { - concatIntStringFloat(i, s, f); + output = output + i + ":" + s + ":" + f + " "; } return output; } function testArrayWithTupleInTupleWithType() returns string { - output = ""; + string output = ""; [int, [string, float]][] arr = [[1, ["A", 2.0]], [2, ["B", 3.0]], [3, ["C", 4.0]]]; foreach [int, [string, float]] [i, [s, f]] in arr { - concatIntStringFloat(i, s, f); + output = output + i + ":" + s + ":" + f + " "; } return output; } function testArrayWithRecordInTupleWithoutType() returns string { - output = ""; + string output = ""; Data d1 = { i: 1, v: "A" }; Data d2 = { i: 2, v: "B" }; @@ -109,13 +95,13 @@ function testArrayWithRecordInTupleWithoutType() returns string { [int, Data][] arr = [[1, d1], [2, d2], [3, d3]]; foreach var [i, {i: j, v: k}] in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } function testArrayWithRecordInTupleWithType() returns string { - output = ""; + string output = ""; Data d1 = { i: 1, v: "A" }; Data d2 = { i: 2, v: "B" }; @@ -124,13 +110,13 @@ function testArrayWithRecordInTupleWithType() returns string { [int, Data][] arr = [[1, d1], [2, d2], [3, d3]]; foreach [int, Data] [i, {i: j, v: k}] in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } function testArrayWithRecordWithoutType() returns string { - output = ""; + string output = ""; Data d1 = { i: 1, v: "A" }; Data d2 = { i: 2, v: "B" }; @@ -139,13 +125,13 @@ function testArrayWithRecordWithoutType() returns string { Data[] arr = [d1, d2, d3]; foreach var {i, v} in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; } return output; } function testArrayWithRecordWithType() returns string { - output = ""; + string output = ""; Data d1 = { i: 1, v: "A" }; Data d2 = { i: 2, v: "B" }; @@ -154,13 +140,13 @@ function testArrayWithRecordWithType() returns string { Data[] arr = [d1, d2, d3]; foreach Data {i, v} in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; } return output; } function testArrayWithRecordInRecordWithoutType() returns string { - output = ""; + string output = ""; Data d11 = { i: 1, v: "A" }; Data d12 = { i: 2, v: "B" }; @@ -173,13 +159,13 @@ function testArrayWithRecordInRecordWithoutType() returns string { Data2[] arr = [d21, d22, d23]; foreach var {i, v: {i: j, v: k}} in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } function testArrayWithRecordInRecordWithType() returns string { - output = ""; + string output = ""; Data d11 = { i: 1, v: "A" }; Data d12 = { i: 2, v: "B" }; @@ -192,13 +178,13 @@ function testArrayWithRecordInRecordWithType() returns string { Data2[] arr = [d21, d22, d23]; foreach Data2 {i, v: {i: j, v: k}} in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } function testArrayWithTupleInRecordWithoutType() returns string { - output = ""; + string output = ""; Data3 d1 = { i: 1, v: [1, "A"] }; Data3 d2 = { i: 2, v: [2, "B"] }; @@ -207,13 +193,13 @@ function testArrayWithTupleInRecordWithoutType() returns string { Data3[] arr = [d1, d2, d3]; foreach var {i, v: [j, k]} in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } function testArrayWithTupleInRecordWithType() returns string { - output = ""; + string output = ""; Data3 d1 = { i: 1, v: [1, "A"] }; Data3 d2 = { i: 2, v: [2, "B"] }; @@ -222,7 +208,7 @@ function testArrayWithTupleInRecordWithType() returns string { Data3[] arr = [d1, d2, d3]; foreach Data3 {i, v: [j, k]} in arr { - concatIntIntString(i, j, k); + output = output + i + ":" + i + ":" + k + " "; } return output; } @@ -230,13 +216,13 @@ function testArrayWithTupleInRecordWithType() returns string { // --------------------------------------------------------------------------------------------------------------------- function testEmptyArrayIteration() returns string { - output = ""; + string output = ""; string[] arr = []; int i = 0; foreach var v in arr { - concatIntString(i, v); + output = output + i + ":" + v + " "; i += 1; } return output; diff --git a/tests/jballerina-unit-test/src/test/resources/testng.xml b/tests/jballerina-unit-test/src/test/resources/testng.xml index a51da007d7a9..43cd7ddd3344 100644 --- a/tests/jballerina-unit-test/src/test/resources/testng.xml +++ b/tests/jballerina-unit-test/src/test/resources/testng.xml @@ -27,7 +27,7 @@ - + @@ -105,6 +105,7 @@ +