use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.
the class CPU method convertMapToStruct.
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void convertMapToStruct(WorkerExecutionContext ctx, int[] operands, WorkerData sf) {
int i = operands[0];
int cpIndex = operands[1];
int j = operands[2];
TypeRefCPEntry typeRefCPEntry = (TypeRefCPEntry) ctx.constPool[cpIndex];
BMap<String, BValue> bMap = (BMap<String, BValue>) sf.refRegs[i];
if (bMap == null) {
handleNullRefError(ctx);
return;
}
int longRegIndex = -1;
int doubleRegIndex = -1;
int stringRegIndex = -1;
int booleanRegIndex = -1;
int blobRegIndex = -1;
int refRegIndex = -1;
BStructType structType = (BStructType) typeRefCPEntry.getType();
BStruct bStruct = new BStruct(structType);
StructInfo structInfo = ctx.callableUnitInfo.getPackageInfo().getStructInfo(structType.getName());
Set<String> keys = bMap.keySet();
for (StructFieldInfo fieldInfo : structInfo.getFieldInfoEntries()) {
String key = fieldInfo.getName();
BType fieldType = fieldInfo.getFieldType();
BValue mapVal = null;
try {
boolean containsField = keys.contains(key);
DefaultValueAttributeInfo defaultValAttrInfo = null;
if (containsField) {
mapVal = bMap.get(key);
if (mapVal == null && BTypes.isValueType(fieldType)) {
throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_FIELD_TYPE_FOR_CASTING, key, fieldType, null);
}
if (mapVal != null && !checkCast(mapVal, fieldType)) {
throw BLangExceptionHelper.getRuntimeException(RuntimeErrors.INCOMPATIBLE_FIELD_TYPE_FOR_CASTING, key, fieldType, mapVal.getType());
}
} else {
defaultValAttrInfo = (DefaultValueAttributeInfo) getAttributeInfo(fieldInfo, AttributeInfo.Kind.DEFAULT_VALUE_ATTRIBUTE);
}
switch(fieldType.getTag()) {
case TypeTags.INT_TAG:
longRegIndex++;
if (containsField) {
bStruct.setIntField(longRegIndex, ((BInteger) mapVal).intValue());
} else if (defaultValAttrInfo != null) {
bStruct.setIntField(longRegIndex, defaultValAttrInfo.getDefaultValue().getIntValue());
}
break;
case TypeTags.FLOAT_TAG:
doubleRegIndex++;
if (containsField) {
bStruct.setFloatField(doubleRegIndex, ((BFloat) mapVal).floatValue());
} else if (defaultValAttrInfo != null) {
bStruct.setFloatField(doubleRegIndex, defaultValAttrInfo.getDefaultValue().getFloatValue());
}
break;
case TypeTags.STRING_TAG:
stringRegIndex++;
if (containsField) {
bStruct.setStringField(stringRegIndex, ((BString) mapVal).stringValue());
} else if (defaultValAttrInfo != null) {
bStruct.setStringField(stringRegIndex, defaultValAttrInfo.getDefaultValue().getStringValue());
}
break;
case TypeTags.BOOLEAN_TAG:
booleanRegIndex++;
if (containsField) {
bStruct.setBooleanField(booleanRegIndex, ((BBoolean) mapVal).booleanValue() ? 1 : 0);
} else if (defaultValAttrInfo != null) {
bStruct.setBooleanField(booleanRegIndex, defaultValAttrInfo.getDefaultValue().getBooleanValue() ? 1 : 0);
}
break;
case TypeTags.BLOB_TAG:
blobRegIndex++;
if (containsField && mapVal != null) {
bStruct.setBlobField(blobRegIndex, ((BBlob) mapVal).blobValue());
}
break;
default:
bStruct.setRefField(++refRegIndex, (BRefType) mapVal);
}
} catch (BallerinaException e) {
sf.refRegs[j] = null;
String errorMsg = "cannot convert '" + bMap.getType() + "' to type '" + structType + ": " + e.getMessage();
handleTypeConversionError(ctx, sf, j, errorMsg);
return;
}
}
sf.refRegs[j] = bStruct;
}
use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.
the class BLangVMUtils method populateArgAndReturnData.
@SuppressWarnings("rawtypes")
public static int[][] populateArgAndReturnData(WorkerExecutionContext ctx, CallableUnitInfo callableUnitInfo, BValue[] args) {
WorkerDataIndex wdi1 = callableUnitInfo.paramWorkerIndex;
WorkerDataIndex wdi2 = callableUnitInfo.retWorkerIndex;
WorkerData local = createWorkerData(wdi1, wdi2);
BType[] types = callableUnitInfo.getParamTypes();
int longParamCount = 0, doubleParamCount = 0, stringParamCount = 0, intParamCount = 0, byteParamCount = 0, refParamCount = 0;
for (int i = 0; i < types.length; i++) {
switch(types[i].getTag()) {
case TypeTags.INT_TAG:
if (args[i] instanceof BString) {
local.longRegs[longParamCount] = ((BString) args[i]).intValue();
} else {
local.longRegs[longParamCount] = ((BInteger) args[i]).intValue();
}
longParamCount++;
break;
case TypeTags.FLOAT_TAG:
if (args[i] instanceof BString) {
local.doubleRegs[doubleParamCount] = ((BString) args[i]).floatValue();
} else {
local.doubleRegs[doubleParamCount] = ((BFloat) args[i]).floatValue();
}
doubleParamCount++;
break;
case TypeTags.STRING_TAG:
local.stringRegs[stringParamCount] = args[i].stringValue();
stringParamCount++;
break;
case TypeTags.BOOLEAN_TAG:
if (args[i] instanceof BString) {
local.intRegs[intParamCount] = ((BString) args[i]).value().toLowerCase().equals("true") ? 1 : 0;
} else {
local.intRegs[intParamCount] = ((BBoolean) args[i]).booleanValue() ? 1 : 0;
}
intParamCount++;
break;
case TypeTags.BLOB_TAG:
local.byteRegs[byteParamCount] = ((BBlob) args[i]).blobValue();
byteParamCount++;
break;
default:
local.refRegs[refParamCount] = (BRefType) args[i];
refParamCount++;
break;
}
}
ctx.workerLocal = local;
return new int[][] { wdi1.retRegs, BLangVMUtils.createReturnRegValues(wdi1, wdi2, callableUnitInfo.getRetParamTypes()) };
}
use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.
the class BLangVMUtils method populateReturnData.
public static BValue[] populateReturnData(WorkerExecutionContext ctx, CallableUnitInfo callableUnitInfo, int[] retRegs) {
WorkerData data = ctx.workerLocal;
BType[] retTypes = callableUnitInfo.getRetParamTypes();
BValue[] returnValues = new BValue[retTypes.length];
for (int i = 0; i < returnValues.length; i++) {
BType retType = retTypes[i];
switch(retType.getTag()) {
case TypeTags.INT_TAG:
returnValues[i] = new BInteger(data.longRegs[retRegs[i]]);
break;
case TypeTags.FLOAT_TAG:
returnValues[i] = new BFloat(data.doubleRegs[retRegs[i]]);
break;
case TypeTags.STRING_TAG:
returnValues[i] = new BString(data.stringRegs[retRegs[i]]);
break;
case TypeTags.BOOLEAN_TAG:
boolean boolValue = data.intRegs[retRegs[i]] == 1;
returnValues[i] = new BBoolean(boolValue);
break;
case TypeTags.BLOB_TAG:
returnValues[i] = new BBlob(data.byteRegs[retRegs[i]]);
break;
default:
returnValues[i] = data.refRegs[retRegs[i]];
break;
}
}
return returnValues;
}
use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.
the class WebSocketServerConnectorListener method onMessage.
@Override
public void onMessage(WebSocketInitMessage webSocketInitMessage) {
HTTPCarbonMessage msg = new HTTPCarbonMessage(((DefaultWebSocketInitMessage) webSocketInitMessage).getHttpRequest());
Map<String, String> pathParams = new HashMap<>();
WebSocketService wsService = WebSocketDispatcher.findService(servicesRegistry, pathParams, webSocketInitMessage, msg);
BStruct serviceEndpoint = BLangConnectorSPIUtil.createBStruct(wsService.getResources()[0].getResourceInfo().getServiceInfo().getPackageInfo().getProgramFile(), PROTOCOL_PACKAGE_HTTP, WEBSOCKET_ENDPOINT);
BStruct serverConnector = WebSocketUtil.createAndGetBStruct(wsService.getResources()[0]);
serverConnector.addNativeData(WebSocketConstants.WEBSOCKET_MESSAGE, webSocketInitMessage);
serverConnector.addNativeData(WebSocketConstants.WEBSOCKET_SERVICE, wsService);
serviceEndpoint.setRefField(SERVICE_ENDPOINT_CONNECTION_INDEX, serverConnector);
serviceEndpoint.setRefField(3, new BMap());
serverConnector.addNativeData(WEBSOCKET_ENDPOINT, serviceEndpoint);
Map<String, String> upgradeHeaders = webSocketInitMessage.getHeaders();
BMap<String, BString> bUpgradeHeaders = new BMap<>();
upgradeHeaders.forEach((key, value) -> bUpgradeHeaders.put(key, new BString(value)));
serviceEndpoint.setRefField(4, bUpgradeHeaders);
Resource onUpgradeResource = wsService.getResourceByName(WebSocketConstants.RESOURCE_NAME_ON_UPGRADE);
if (onUpgradeResource != null) {
Semaphore semaphore = new Semaphore(0);
AtomicBoolean isResourceExeSuccessful = new AtomicBoolean(false);
BStruct inRequest = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), PROTOCOL_PACKAGE_HTTP, HttpConstants.REQUEST);
BStruct inRequestEntity = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.ENTITY);
BStruct mediaType = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), org.ballerinalang.mime.util.Constants.PROTOCOL_PACKAGE_MIME, Constants.MEDIA_TYPE);
BStruct cacheControlStruct = BLangConnectorSPIUtil.createBStruct(WebSocketUtil.getProgramFile(wsService.getResources()[0]), PROTOCOL_PACKAGE_HTTP, REQUEST_CACHE_CONTROL);
RequestCacheControlStruct requestCacheControl = new RequestCacheControlStruct(cacheControlStruct);
HttpUtil.populateInboundRequest(inRequest, inRequestEntity, mediaType, msg, requestCacheControl);
List<ParamDetail> paramDetails = onUpgradeResource.getParamDetails();
BValue[] bValues = new BValue[paramDetails.size()];
bValues[0] = serviceEndpoint;
bValues[1] = inRequest;
WebSocketDispatcher.setPathParams(bValues, paramDetails, pathParams, 2);
Tracer tracer = TraceManagerWrapper.newTracer(null, false);
upgradeHeaders.entrySet().stream().filter(c -> c.getKey().startsWith(TraceConstants.TRACE_PREFIX)).forEach(e -> tracer.addProperty(e.getKey(), e.getValue()));
Executor.submit(onUpgradeResource, new CallableUnitCallback() {
@Override
public void notifySuccess() {
isResourceExeSuccessful.set(true);
semaphore.release();
}
@Override
public void notifyFailure(BStruct error) {
ErrorHandlerUtils.printError("error: " + BLangVMErrors.getPrintableStackTrace(error));
semaphore.release();
}
}, null, tracer, bValues);
try {
semaphore.acquire();
if (isResourceExeSuccessful.get() && !webSocketInitMessage.isCancelled() && !webSocketInitMessage.isHandshakeStarted()) {
WebSocketUtil.handleHandshake(wsService, null, serverConnector);
}
} catch (InterruptedException e) {
throw new BallerinaConnectorException("Connection interrupted during handshake");
}
} else {
WebSocketUtil.handleHandshake(wsService, null, serverConnector);
}
}
use of org.ballerinalang.model.values.BString in project ballerina by ballerina-lang.
the class UpgradeToWebSocket method execute.
@Override
public void execute(Context context) {
BStruct serverConnector = (BStruct) context.getRefArgument(0);
WebSocketService webSocketService = (WebSocketService) serverConnector.getNativeData(WebSocketConstants.WEBSOCKET_SERVICE);
BMap<String, BString> headers = (BMap<String, BString>) context.getRefArgument(1);
DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
Set<String> keys = headers.keySet();
for (String key : keys) {
httpHeaders.add(key, headers.get(key));
}
WebSocketUtil.handleHandshake(webSocketService, httpHeaders, serverConnector);
context.setReturnValues();
}
Aggregations