### Build Ballerina IO Library Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Execute this command to clean and build the library from source. Ensure you have Gradle installed and configured. ```bash ./gradlew clean build ``` -------------------------------- ### Ballerina CSV Stream Data Mapping Example Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/docs/proposals/CSV data mapping.md Illustrates reading CSV data as a stream of `Employee` records and processing it. This example assumes the CSV file has headers matching the record fields. ```ballerina isolated function testCsvStreamContent() returns error? { float expectedValue = 60001.00; float total = 0; stream csvStream = check io:fileReadCsvAsStream(filePath); check csvStream.forEach(function(Employee x) { total = total + x.salary; }); test:assertEquals(total, expectedValue); check fileWriteCsv(filePath, result); } ``` -------------------------------- ### Run Bag of Word Example in Ballerina Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/A Guideline on Implementing Bag of Word Model Generator.md Execute the Ballerina project to generate the BoW model. You will be prompted to enter the number of most frequent words to retrieve. ```sh cd examples/bow bal run ``` -------------------------------- ### Ballerina CSV Data Mapping Example Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/docs/proposals/CSV data mapping.md Demonstrates reading CSV data directly into an array of `Employee` records and writing them back. Assumes the CSV file has headers matching the record fields. ```ballerina type Employee record { string id; string name; float salary; }; @test:Config {} isolated function testCsvContent() returns error? { float expectedValue = 60001.00; float total = 0; Employee[] result = check fileReadCSV(filePath); foreach Employee x in result { total = total + x.salary; } test:assertEquals(total, expectedValue); check fileWriteCsv(filePath, result); } ``` -------------------------------- ### Example Input for Frequent Words Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/A Guideline on Implementing Bag of Word Model Generator.md Provide the desired number of most frequent words when prompted by the program. ```text > Enter the number of most frequent words to retrieve: 10 ``` -------------------------------- ### Print using string templates Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/docs/spec/spec.md Demonstrates using string templates with `io:println` for formatted output. ```ballerina import ballerina/io; public function main() { string name = "Harry"; int age = 20; io:println(`My name is ${name} and I am ${age} years old.`); } ``` -------------------------------- ### Configure gRPC Access and Trace Logs Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Enable access and trace logs for gRPC by configuring the `Config.toml` file. Options include printing logs to the console, a file, or sending them to a specified host and port. ```toml [ballerina.grpc.traceLog.advancedConfig] console = true # path testTraceLog.txt # Optional # host = "localhost" # Optional # port = 8080 # Optional [ballerina.grpc.accessLogConfig] console = true # path testTraceLog.txt # Optional ``` -------------------------------- ### Example Output of Frequent Words Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/A Guideline on Implementing Bag of Word Model Generator.md The output displays the most frequent words and their counts as a map, based on the input number. ```text Most frequent 10 words are: {"ballerina":100,"grpc":59,"is":41,"the":176,"to":50,"and":49,"client":41,"service":53,"a":51,"rpc":52} ``` -------------------------------- ### Publish Ballerina IO Artifacts to Local Ballerina Central Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Run this command to build the module and publish the generated artifacts to the local Ballerina central repository. ```bash ./gradlew clean build -PpublishToLocalCentral=true ``` -------------------------------- ### Run Ballerina IO Integration Tests Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Execute this command to clean and run all integration tests for the module. This is useful for verifying the module's functionality. ```bash ./gradlew clean test ``` -------------------------------- ### Build Ballerina IO Module Without Tests Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Use this command to build the module while skipping the execution of tests. This can speed up the build process when tests are not immediately required. ```bash ./gradlew clean build -x test ``` -------------------------------- ### Debug Ballerina IO Module with Ballerina Language Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Use these commands to debug the module's implementation specifically from the Ballerina language perspective. Replace `` with your desired debugging port. ```bash ./gradlew clean build -PbalJavaDebug= ``` ```bash ./gradlew clean test -PbalJavaDebug= ``` -------------------------------- ### Simple RPC - Direct Return Implementation Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Implement a simple RPC using direct return. This is suitable for synchronous calls where a response can be returned immediately. ```ballerina service RouteGuide on new grpcListener8980 remote function GetFeaturePoint point returns Featureerror foreach Feature feature in FEATURES if featurelocation point return feature return location point name ``` -------------------------------- ### Publish Ballerina IO Artifacts to Ballerina Central Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Execute this command to build the module and publish the generated artifacts to the official Ballerina central repository. ```bash ./gradlew clean build -PpublishToCentral=true ``` -------------------------------- ### gRPC Access and Trace Logs Configuration Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Enable access and trace logs for gRPC communication by configuring the `Config.toml` file. ```APIDOC ## gRPC Access and Trace Logs Configuration ### Description Enable access and trace logs for gRPC communication by configuring the `Config.toml` file. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```toml [ballerina.grpc.trace] LogAdvancedConfig { # Enable printing trace logs in console console = true # Default is false # Prints the trace logs to the given file path = "testTraceLog.txt" # Optional # Sends the trace logs to the configured endpoint host = "localhost" # Optional port = 8080 # Optional } [ballerina.grpc.access] LogConfig { # Enable printing access logs in console console = true # Default is false # Prints the access logs to the given file path = "testAccessLog.txt" # Optional } ``` ### Response N/A ``` -------------------------------- ### Debug Ballerina IO Module Implementation Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md These commands allow you to debug the module's Java implementation. Replace `` with your desired debugging port. ```bash ./gradlew clean build -Pdebug= ``` ```bash ./gradlew clean test -Pdebug= ``` -------------------------------- ### Publish Ballerina IO Artifacts to Maven Local Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/README.md Execute this command to build the module and publish the generated ZIP artifact to your local Maven repository. ```bash ./gradlew clean build publishToMavenLocal ``` -------------------------------- ### Print to specific output streams using io:fprint/io:fprintln Source: https://context7.com/ballerina-platform/module-ballerina-io/llms.txt Utilize `io:fprint` and `io:fprintln` to direct output to `io:stdout` or `io:stderr`. This is useful for separating informational messages from error or warning logs. ```ballerina import ballerina/io; public function main() { string inputFile = "data.csv"; // Write informational message to stdout io:fprintln(io:stdout, `Starting to process: ${inputFile}`); // Write error/warning messages to stderr io:fprintln(io:stderr, "WARNING: File size exceeds recommended limit"); io:fprint(io:stderr, "ERROR: "); io:fprintln(io:stderr, "Failed to open file"); // stderr output: WARNING: File size exceeds recommended limit // ERROR: Failed to open file } ``` -------------------------------- ### Console I/O - readln Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/docs/spec/spec.md Reads content from standard input and returns it as a string. It can optionally take a prompt message to display to the user. ```APIDOC ## readln ### Description Retrieves the input read from the STDIN. ### Syntax ```ballerina public function readln(any? a = ()) returns string; ``` ### Parameters * `a` (any?) - Optional. Any value to be printed as a prompt. ### Returns * `string` - Input read from the STDIN. ``` -------------------------------- ### gRPC Client Basic Authentication Configuration Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Configure gRPC clients to use basic authentication with a username and password. ```ballerina HelloWorldClient securedEP check newhttpslocalhost9090 auth username john password ballerina123 ``` -------------------------------- ### SSL/TLS Listener Configuration Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Expose gRPC services with SSL/TLS using a gRPC listener configured with `grpcListenerSecureSocket`. ```APIDOC ## SSL/TLS Listener Configuration ### Description Expose gRPC services with SSL/TLS using a gRPC listener configured with `grpcListenerSecureSocket`. ### Method Ballerina Code ### Endpoint N/A ### Parameters N/A ### Request Example ```ballerina listener grpcListener securedEp = new (9090, { secureSocket: { key: { certFile: "resources/public.crt", keyFile: "resources/private.key" } } }); grpcServiceDescriptor serviceDescriptor = {descriptor: ROOTDESCRIPTORGRPCSERVICE, descMap: getDescriptorMapGrpcService()}; service HelloWorld on securedEp { remote function hello() returns string { return "Hello World"; } } ``` ### Response N/A ``` -------------------------------- ### Client Configuration: Basic Auth Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Configures a gRPC client for basic authentication using `grpcClientBasicAuthHandler`. This involves providing username and password credentials and using the `enrich` API to pass authentication headers to the RPC call. ```ballerina grpcCredentialsConfig config username admin password 123 grpcClientBasicAuthHandler handler new config mapstringstringgrpcClientAuthError result handlerenrichrequestHeaders ``` -------------------------------- ### Service Configuration: File User Store Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Configures a gRPC service to use a file-based user store for authentication and authorization. This handler, `grpcListenerFileUserStoreBasicAuthHandler`, processes authentication requests based on user details defined in a TOML configuration. ```ballerina service HelloWorld on new grpcListener9090 remote function sayHelloContextString request returns stringerror grpcListenerFileUserStoreBasicAuthHandler handler new authUserDetailsgrpcUnauthenticatedError authnResult handlerauthenticaterequestheaders ``` ```toml Configtoml ballerinaobserve enabledtrue providernoop authusers usernameadmin password123 scopeswrite update ``` -------------------------------- ### Simple RPC - Caller Implementation Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Implement a simple RPC using a caller. This approach is ideal for asynchronous RPC calls. ```ballerina service RouteGuide on new grpcListener8980 remote function GetFeatureRouteGuideFeatureCaller caller Point point returns error Featureerror feature featureFromPointpoint if feature is Feature check callersendFeaturefeature else if feature is error check callersendErrorgrpcError feature else check callersendFeaturelocation latitude 0 longitude 0 name ``` -------------------------------- ### Configure gRPC Listener for SSL/TLS Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Expose gRPC services with SSL/TLS by configuring `grpcListenerSecureSocket`. This involves specifying the key and certificate files. ```ballerina listener grpcListener securedEp = new 9090 { secureSocket { key { certFile "resources/public.crt" keyFile "resources/private.key" } } grpcServiceDescriptor { descriptor ROOTDESCRIPTORGRPCSERVICE descMap getDescriptorMapGrpcService } }; service HelloWorld on securedEp { remote function hello() returns string { return "Hello World"; } } ``` -------------------------------- ### Simple RPC - Client Invocation Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Invoke a simple RPC using the generated Ballerina stub. This demonstrates how a client interacts with the RPC service. ```ballerina public function main returns error RouteGuideClient ep check new httplocalhost8980 Feature feature check epGetFeaturelatitude 406109563 longitude 742186778 ``` -------------------------------- ### Client Streaming RPC Implementation in Ballerina Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt This snippet demonstrates a client streaming RPC where the client sends a stream of points to the server to calculate route summaries. It initializes a client, sends points, completes the stream, and receives the summary. ```ballerina public function main returns error RouteGuideClient ep check new httplocalhost8980 Point points latitude 406109563 longitude 742186778 latitude 411733222 longitude 744228360 latitude 744228334 longitude 742186778 RecordRouteStreamingClient recordRouteStrmClient check epRecordRoute foreach Point p in points check recordRouteStrmClientsendPointp check recordRouteStrmClientcomplete RouteSummary routeSummary check recordRouteStrmClientreceiveRouteSummary if routeSummary is RouteSummary ioprintlnFinished trip with routeSummarypointcount points Passed routeSummaryfeaturecount features Travelled routeSummarydistance meters It took routeSummaryelapsedtime seconds ``` -------------------------------- ### Print to standard output Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/docs/spec/spec.md Prints given values to STDOUT. Supports string templates. ```ballerina # Prints `any`, `error`, or string templates(such as `The respective int value is ${val}`) value(s) to the STDOUT. # ```ballerina # io:print("Start processing the CSV file from ", srcFileName); # ``` # # + values - The value(s) to be printed public isolated function print(Printable... values); ``` -------------------------------- ### Write Byte Stream to File using io:fileWriteBlocksFromStream Source: https://context7.com/ballerina-platform/module-ballerina-io/llms.txt Consumes a stream of byte arrays and writes each block to a file, suitable for piping data without full memory buffering. ```ballerina import ballerina/io; public function main() returns error? { // Copy a file by streaming blocks stream sourceStream = check io:fileReadBlocksAsStream("./resources/source.bin", 4096); // Write the stream to a destination file io:Error? writeResult = io:fileWriteBlocksFromStream("./output/destination.bin", sourceStream); if writeResult is io:Error { io:fprintln(io:stderr, `Write failed: ${writeResult.message()}`); return writeResult; } io:println("File copied successfully via streaming"); } ``` -------------------------------- ### Service Configuration: LDAP User Store Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Configures a gRPC service to use an LDAP user store for authentication and authorization. The `grpcListenerLdapUserStoreBasicAuthHandler` requires detailed LDAP connection and search configurations. ```ballerina service HelloWorld on new grpcListener9090 remote function sayHelloContextString request returns stringerror grpcLdapUserStoreConfig config domainName avixlk connectionUrl ldaplocalhost389 connectionName cnadmindcavixdclk connectionPassword avix123 userSearchBase ouUsersdcavixdclk userEntryObjectClass inetOrgPerson userNameAttribute uid userNameSearchFilter objectClassinetOrgPersonuid userNameListFilter objectClassinetOrgPerson groupSearchBase ouGroupsdcavixdclk groupEntryObjectClass groupOfNames groupNameAttribute cn groupNameSearchFilter objectClassgroupOfNamescn groupNameListFilter objectClassgroupOfNames membershipAttribute member userRolesCacheEnabled true connectionPoolingEnabled false connectionTimeout 5 readTimeout 60 grpcListenerLdapUserStoreBasicAuthHandler handler newconfig authUserDetailsgrpcUnauthenticatedError authnResult handlerauthenticaterequestheaders ``` -------------------------------- ### Ballerina gRPC CLI Command Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Use this command to generate gRPC client stubs and server skeletons from protobuf files. Specify the input proto file path and optionally an output directory, mode (client/service), and proto path for imports. ```sh bal grpc input protofilepath output outputdirectory mode clientservice protopath protodirectory ``` -------------------------------- ### Client Streaming RPC - Direct Return Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Implement a client streaming RPC using direct return. The function receives a stream of Points and returns a RouteSummary. ```ballerina service RouteGuide on new grpcListener8980 remote function RecordRoutestreamPoint grpcError clientStream returns RouteSummaryerror Point lastPoint int pointCount 0 int featureCount 0 int distance 0 decimal startTime timemonotonicNow check clientStreamforEachfunctionPoint p pointCount 1 if pointExistsInFeaturesFEATURES p featureCount 1 if lastPoint is Point distance calculateDistancePointlastPoint p lastPoint p decimal endTime timemonotonicNow int elapsedTime intendTime startTime return pointcount pointCount featurecount featureCount distance distance elapsedtime elapsedTime ``` -------------------------------- ### gRPC Service File User Store Configuration Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Configure gRPC services to use a file-based user store for authentication and authorization. Specify user credentials and scopes in a TOML file. ```ballerina grpcServiceConfig auth fileUserStoreConfig scopes admin grpcServiceDescriptor descriptor ROOTDESCRIPTORGRPCSERVICE descMap getDescriptorMapGrpcService service HelloWorld on new grpcListener9090 remote function hello returns string return Hello World ``` ```toml Configtoml ballerinaauthusers usernamealice passwordalice123 scopesdeveloper ballerinaauthusers usernameldclakmal passwordldclakmal123 scopesdeveloper admin ballerinaauthusers usernameeve passwordeve123 ``` -------------------------------- ### Enable Compression for gRPC Calls Source: https://github.com/ballerina-platform/module-ballerina-io/blob/master/examples/bow/resources/data.txt Enable compression for gRPC calls, currently supporting Gzip, by adding the `grpc-encoding` header using the `setCompression` function. This function takes a compression type and an optional header map. ```ballerina map headers = grpc:setCompression(grpc:GRPC_GZIP); ``` -------------------------------- ### Read a line from STDIN using io:readln Source: https://context7.com/ballerina-platform/module-ballerina-io/llms.txt The `io:readln` function reads a single line of text from standard input. An optional prompt can be provided to display a message before waiting for user input. It can also read silently without a prompt. ```ballerina import ballerina/io; public function main() { // Read with a prompt string username = io:readln("Enter username: "); // Prints "Enter username: " then waits for input string password = io:readln("Enter password: "); io:println(`Welcome, ${username}! `); // Read without a prompt (silent) string command = io:readln(); io:println(`Command received: ${command}`); } ``` -------------------------------- ### Open and Use Readable/Writable Byte Channels in Ballerina Source: https://context7.com/ballerina-platform/module-ballerina-io/llms.txt Opens files as raw byte channels for low-level byte access. These can be wrapped for typed access. Ensure files exist for reading and output directories are writable. ```ballerina import ballerina/io; public function main() returns error? { // Open a readable byte channel manually io:ReadableByteChannel readChannel = check io:openReadableFile("./resources/data.bin"); // Read 512 bytes at offset 0 [byte[], int] result = check readChannel.read(512); byte[] bytes = result[0]; int bytesRead = result[1]; io:println(`Read ${bytesRead} bytes`); check readChannel.close(); // Open a writable byte channel (OVERWRITE) io:WritableByteChannel writeChannel = check io:openWritableFile("./output/out.bin"); byte[] data = [0x48, 0x65, 0x6C, 0x6C, 0x6F]; // "Hello" int bytesWritten = check writeChannel.write(data, 0); io:println(`Wrote ${bytesWritten} bytes`); check writeChannel.close(); // Wrap in a character channel for text operations io:ReadableByteChannel byteChannel2 = check io:openReadableFile("./resources/notes.txt"); io:ReadableCharacterChannel charChannel = new (byteChannel2, "UTF-8"); string text = check charChannel.readString(); io:println(`Text: ${text}`); check charChannel.close(); } ``` -------------------------------- ### Write String to File using io:fileWriteString Source: https://context7.com/ballerina-platform/module-ballerina-io/llms.txt Writes a given string to a file, supporting OVERWRITE or APPEND modes. ```ballerina import ballerina/io; public function main() returns error? { string logEntry = "2024-08-06T10:00:00Z INFO Server started\n"; // Create or overwrite the file check io:fileWriteString("./logs/app.log", "=== Log Start ===\n"); // Append a log entry io:Error? result = io:fileWriteString("./logs/app.log", logEntry, io:APPEND); if result is io:Error { io:fprintln(io:stderr, `Log write failed: ${result.message()}`); return result; } io:println("Log entry written"); } ```