Search in sources :

Example 1 with Channel

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));
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) BStruct(org.ballerinalang.model.values.BStruct) StructInfo(org.ballerinalang.util.codegen.StructInfo) SocketIOChannel(org.ballerinalang.nativeimpl.io.channels.SocketIOChannel) InetSocketAddress(java.net.InetSocketAddress) PackageInfo(org.ballerinalang.util.codegen.PackageInfo) SocketIOChannel(org.ballerinalang.nativeimpl.io.channels.SocketIOChannel) Channel(org.ballerinalang.nativeimpl.io.channels.base.Channel) SocketChannel(java.nio.channels.SocketChannel) Socket(java.net.Socket)

Example 2 with Channel

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());
    }
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) InputStream(java.io.InputStream) Channel(org.ballerinalang.nativeimpl.io.channels.base.Channel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) CharacterChannel(org.ballerinalang.nativeimpl.io.channels.base.CharacterChannel) BString(org.ballerinalang.model.values.BString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) CharacterChannel(org.ballerinalang.nativeimpl.io.channels.base.CharacterChannel) Test(org.testng.annotations.Test)

Example 3 with Channel

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());
    }
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) BValue(org.ballerinalang.model.values.BValue) FileWriter(java.io.FileWriter) Channel(org.ballerinalang.nativeimpl.io.channels.base.Channel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) CharacterChannel(org.ballerinalang.nativeimpl.io.channels.base.CharacterChannel) IOException(java.io.IOException) File(java.io.File) BufferedWriter(java.io.BufferedWriter) Test(org.testng.annotations.Test)

Example 4 with Channel

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);
}
Also used : EventContext(org.ballerinalang.nativeimpl.io.events.EventContext) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) Channel(org.ballerinalang.nativeimpl.io.channels.base.Channel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) Test(org.testng.annotations.Test)

Example 5 with Channel

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);
}
Also used : MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) Channel(org.ballerinalang.nativeimpl.io.channels.base.Channel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) ByteChannel(java.nio.channels.ByteChannel) MockByteChannel(org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel) Test(org.testng.annotations.Test)

Aggregations

Channel (org.ballerinalang.nativeimpl.io.channels.base.Channel)49 ByteChannel (java.nio.channels.ByteChannel)33 MockByteChannel (org.ballerinalang.test.nativeimpl.functions.io.MockByteChannel)31 Test (org.testng.annotations.Test)31 CharacterChannel (org.ballerinalang.nativeimpl.io.channels.base.CharacterChannel)19 BStruct (org.ballerinalang.model.values.BStruct)12 IOException (java.io.IOException)7 FileChannel (java.nio.channels.FileChannel)7 DelimitedRecordChannel (org.ballerinalang.nativeimpl.io.channels.base.DelimitedRecordChannel)7 EventContext (org.ballerinalang.nativeimpl.io.events.EventContext)6 TempFileIOChannel (org.ballerinalang.nativeimpl.io.channels.TempFileIOChannel)5 InputStream (java.io.InputStream)4 EventResult (org.ballerinalang.nativeimpl.io.events.EventResult)4 BallerinaIOException (org.ballerinalang.nativeimpl.io.BallerinaIOException)3 BufferedReader (java.io.BufferedReader)2 BufferedWriter (java.io.BufferedWriter)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileWriter (java.io.FileWriter)2 InputStreamReader (java.io.InputStreamReader)2