use of org.ballerinalang.nativeimpl.io.channels.base.Channel in project ballerina by ballerina-lang.
the class OpenSocket method execute.
@Override
public void execute(Context context) {
final String host = context.getStringArgument(0);
final int port = (int) context.getIntArgument(0);
final BStruct options = (BStruct) context.getRefArgument(0);
if (log.isDebugEnabled()) {
log.debug("Remote host: " + host);
log.debug("Remote port: " + port);
}
Socket socket;
SocketChannel channel;
try {
// Open a client connection
SocketChannel socketChannel = SocketChannel.open();
if (options.getIntField(LOCAL_PORT_OPTION_FIELD_INDEX) > 0) {
if (log.isDebugEnabled()) {
log.debug("Bind client socket to local port: " + options.getIntField(0));
}
socketChannel.bind(new InetSocketAddress((int) options.getIntField(0)));
}
socketChannel.connect(new InetSocketAddress(host, port));
log.debug("Successfully connect to remote server.");
socket = socketChannel.socket();
if (log.isDebugEnabled()) {
log.debug("Bound local port: " + socket.getLocalPort());
log.debug("Timeout on blocking Socket operations: " + socket.getSoTimeout());
log.debug("ReceiveBufferSize: " + socket.getReceiveBufferSize());
log.debug("KeepAlive: " + socket.getKeepAlive());
}
channel = socket.getChannel();
PackageInfo ioPackageInfo = context.getProgramFile().getPackageInfo(SOCKET_PACKAGE);
// Create ByteChannel Struct
StructInfo channelStructInfo = ioPackageInfo.getStructInfo(BYTE_CHANNEL_STRUCT_TYPE);
Channel ballerinaSocketChannel = new SocketIOChannel(channel, 0);
BStruct channelStruct = BLangVMStructs.createBStruct(channelStructInfo, ballerinaSocketChannel);
channelStruct.addNativeData(IOConstants.BYTE_CHANNEL_NAME, ballerinaSocketChannel);
// Create Socket Struct
StructInfo socketStructInfo = ioPackageInfo.getStructInfo(SOCKET_STRUCT_TYPE);
BStruct socketStruct = BLangVMStructs.createBStruct(socketStructInfo);
socketStruct.setRefField(0, channelStruct);
socketStruct.setIntField(0, socket.getPort());
socketStruct.setIntField(1, socket.getLocalPort());
socketStruct.setStringField(0, socket.getInetAddress().getHostAddress());
socketStruct.setStringField(1, socket.getLocalAddress().getHostAddress());
socketStruct.addNativeData(IOConstants.CLIENT_SOCKET_NAME, channel);
context.setReturnValues(socketStruct);
} catch (Throwable e) {
String msg = "Failed to open a connection to [" + host + ":" + port + "] : " + e.getMessage();
log.error(msg, e);
context.setReturnValues(IOUtils.createError(context, msg));
}
}
use of org.ballerinalang.nativeimpl.io.channels.base.Channel in project ballerina by ballerina-lang.
the class MimeUtilityFunctionTest method testLargePayload.
@Test(description = "When the payload exceeds 2MB check whether the response received back matches " + "the original content length")
public void testLargePayload() {
String path = "/test/largepayload";
try {
ByteChannel byteChannel = TestUtil.openForReading("datafiles/io/text/fileThatExceeds2MB.txt");
Channel channel = new MockByteChannel(byteChannel, 10);
CharacterChannel characterChannel = new CharacterChannel(channel, StandardCharsets.UTF_8.name());
String responseValue = characterChannel.readAll();
characterChannel.close();
HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage(path, "POST", responseValue);
HTTPCarbonMessage response = Services.invokeNew(serviceResult, "mockEP", cMsg);
Assert.assertNotNull(response, "Response message not found");
InputStream inputStream = new HttpMessageDataStreamer(response).getInputStream();
Assert.assertNotNull(inputStream, "Inputstream is null");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
MimeUtil.writeInputToOutputStream(inputStream, outputStream);
Assert.assertEquals(outputStream.size(), 2323779);
} catch (IOException | URISyntaxException e) {
log.error("Error occurred in testLargePayload", e.getMessage());
}
}
use of org.ballerinalang.nativeimpl.io.channels.base.Channel in project ballerina by ballerina-lang.
the class MimeUtilityFunctionTest method testGetByteChannel.
@Test(description = "Set byte channel as entity body and get that channel back")
public void testGetByteChannel() {
try {
File file = File.createTempFile("testFile", ".tmp");
file.deleteOnExit();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("Hello Ballerina!");
bufferedWriter.close();
BStruct byteChannelStruct = Util.getByteChannelStruct(compileResult);
byteChannelStruct.addNativeData(IOConstants.BYTE_CHANNEL_NAME, EntityBodyHandler.getByteChannelForTempFile(file.getAbsolutePath()));
BValue[] args = { byteChannelStruct };
BValue[] returns = BRunUtil.invoke(compileResult, "testGetByteChannel", args);
Assert.assertEquals(returns.length, 1);
BStruct returnByteChannelStruct = (BStruct) returns[0];
Channel byteChannel = (Channel) returnByteChannelStruct.getNativeData(IOConstants.BYTE_CHANNEL_NAME);
Assert.assertEquals(StringUtils.getStringFromInputStream(byteChannel.getInputStream()), "Hello Ballerina!");
} catch (IOException e) {
log.error("Error occurred in testSetByteChannel", e.getMessage());
}
}
use of org.ballerinalang.nativeimpl.io.channels.base.Channel in project ballerina by ballerina-lang.
the class AsyncReadWriteTest method writeBytes.
@Test(description = "Write into a channel using async io framework")
public void writeBytes() throws IOException, URISyntaxException, ExecutionException, InterruptedException {
// Number of characters in this file would be 6
ByteChannel byteChannel = TestUtil.openForWriting(currentDirectoryPath + "write.txt");
Channel channel = new MockByteChannel(byteChannel);
byte[] bytes = "hello".getBytes();
int numberOfBytesWritten = IOUtils.writeFull(channel, bytes, 0, new EventContext());
Assert.assertEquals(numberOfBytesWritten, bytes.length);
}
use of org.ballerinalang.nativeimpl.io.channels.base.Channel in project ballerina by ballerina-lang.
the class BytesInputOutputBufferTest method excessBufferAllocation.
@Test(description = "Read all bytes from file with larger buffer size")
public void excessBufferAllocation() throws IOException, URISyntaxException {
int initialReadLimit = 3;
int secondLapReadLimit = 3;
int thirdLapReadLimit = 3;
// During the 3rd lap all the bytes were get
int thirdLapReadLimitExpected = 0;
// Number of characters in this file would be 6
ByteChannel byteChannel = TestUtil.openForReading("datafiles/io/text/6charfile.txt");
Channel channel = new MockByteChannel(byteChannel, IOConstants.CHANNEL_BUFFER_SIZE);
byte[] readBytes = channel.readFull(initialReadLimit);
// This should hold the number of bytes get
Assert.assertEquals(readBytes.length, initialReadLimit);
readBytes = channel.readFull(secondLapReadLimit);
// This should hold the number of bytes get
Assert.assertEquals(readBytes.length, secondLapReadLimit);
readBytes = channel.readFull(thirdLapReadLimit);
channel.close();
// This should hold the number of bytes get
Assert.assertEquals(readBytes.length, thirdLapReadLimitExpected);
}
Aggregations