### Testing with FakeFileSystem in Kotlin Source: https://github.com/square/okio/blob/master/docs/file_system.md Illustrates how to use Okio's FakeFileSystem for testing purposes. This example shows creating a fake file system, writing to a file, and then verifying the content after a hypothetical fix. ```kotlin val fileSystem = FakeFileSystem() val userHome = "/Users/sandy".toPath() val gitConfig = userHome / ".gitconfig" fileSystem.createDirectories(userHome) val original = """ |[user] | email = sandy@example.com |""".trimMargin() fileSystem.write(gitConfig) { writeUtf8(original) } GitConfigFixer(fileSystem).fix(userHome) val expected = """ |[user] | email = sandy@example.com |[diff] | renames = true | indentHeuristic = on """.trimIndent() assertEquals(expected, fileSystem.read(gitConfig) { readUtf8() }) ``` -------------------------------- ### Android Environment Setup Source: https://github.com/square/okio/blob/master/android-test/README.md Configures the Android SDK and PATH environment variables required for running tests on an Android device. This includes setting ANDROID_SDK_ROOT and adding necessary tools to the PATH. ```bash export ANDROID_SDK_ROOT=/Users/$USER/Library/Android/sdk export PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin:$ANDROID_SDK_ROOT/platform-tools ``` -------------------------------- ### Copying Data Between Sockets Source: https://github.com/square/okio/blob/master/docs/recipes.md Provides code examples in Java and Kotlin for copying data from a source to a sink, flushing after each read. It also mentions the `writeAll` method as an alternative if flushing is not required and explains the significance of the buffer size argument in the `read` method. ```Java Buffer buffer = new Buffer(); for (long byteCount; (byteCount = source.read(buffer, 8192L)) != -1; ) { sink.write(buffer, byteCount); sink.flush(); } ``` ```Kotlin val buffer = Buffer() var byteCount: Long while (source.read(buffer, 8192L).also { byteCount = it } != -1L) { sink.write(buffer, byteCount) sink.flush() } ``` -------------------------------- ### UTF-8 String Encoding Example (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md An example demonstrating how to dump string data, potentially involving UTF-8 characters, to standard output in Java. ```Java public void dumpStringData(String s) throws IOException { System.out.println(" " + s); } ``` -------------------------------- ### Successful Test Run Log Indicator Source: https://github.com/square/okio/blob/master/android-test/README.md An example logcat output indicating a successful test run completion. The presence of 'run finished' with zero failures confirms that all tests executed without critical errors. ```java 01-01 00:00:00.000 12345 23456 I TestRunner: run finished: 2976 tests, 0 failed, 3 ignored ``` -------------------------------- ### Basic File Read and Write in Kotlin Source: https://github.com/square/okio/blob/master/docs/file_system.md Demonstrates how to read content from a file and write updated content back to it using Okio's FileSystem API in Kotlin. It shows concise file operations. ```kotlin val path = "README.md".toPath() val readmeContent = FileSystem.SYSTEM.read(path) { readUtf8() } val updatedContent = readmeContent.replace("red", "blue") FileSystem.SYSTEM.write(path) { writeUtf8(updatedContent) } ``` -------------------------------- ### Okio FileSystem Limitations Overview Source: https://github.com/square/okio/blob/master/docs/file_system.md Summarizes the known limitations of Okio's FileSystem across different platforms, including general constraints and platform-specific issues like symlink support and atomic move behavior. ```APIDOC Okio FileSystem Limitations: General Limitations (All Platforms): - No APIs for file permissions, watches, volume management, memory mapping, or locking. - Paths must be representable as UTF-8 strings; underlying APIs treat paths as strings. Kotlin/JVM Specific: - On Android (API level <26): Symlink creation and access are unsupported. - On Windows: `FileSystem.atomicMove()` fails if the target file already exists. Kotlin/Native Specific: - `FakeFileSystem` does not support concurrent use. - On Windows: Symlink creation and access are unsupported. Kotlin/JS Specific (NodeJsFileSystem): - `source()` and `sink()` cannot access UNIX pipes. - `NodeJsFileSystem.metadataOrNull()` throws `IOException` for invalid paths instead of returning null. ``` -------------------------------- ### Okio Gradle Configuration Source: https://github.com/square/okio/blob/master/docs/multiplatform.md This snippet shows the Gradle build script configuration for the Okio project, including dependency declarations for different source sets like commonMain, jsMain, and commonTest. It specifies the Okio version and includes specific modules like okio-nodefilesystem and okio-fakefilesystem. ```kotlin // build.gradle.kts kotlin { sourceSets { val okioVersion = "3.XXX" val commonMain by getting { dependencies { implementation("com.squareup.okio:okio:$okioVersion") } } val jsMain by getting { dependencies { implementation("com.squareup.okio:okio-nodefilesystem:$okioVersion") } } val commonTest by getting { dependencies { implementation("com.squareup.okio:okio-fakefilesystem:$okioVersion") } } } } ``` -------------------------------- ### WASI FileSystem Overview Source: https://github.com/square/okio/blob/master/okio-wasifilesystem/README.md This section provides an overview of the WASI FileSystem module, its dependencies on WASI, and its current status. It highlights the use of WASI preview1 APIs and testing on NodeJS. ```APIDOC WASI FileSystem ============== ⚠️ This is a work in progress ⚠️ This module implements Okio's FileSystem API using the [WebAssembly System Interface (WASI)][wasi]. It currently uses the WASI [preview1] APIs and is tested on NodeJS with the `--experimental-wasi-unstable-preview1` option. [wasi]: https://wasi.dev/ [preview1]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md ``` -------------------------------- ### Okio FileSystem Platform Abstraction Source: https://github.com/square/okio/blob/master/docs/file_system.md Details the underlying platform APIs that Okio's FileSystem abstracts over for different operating systems and Java/Android versions. This provides context on Okio's multiplatform nature. ```APIDOC Okio FileSystem Platform Abstraction: Okio's `FileSystem` abstracts over various platform-specific file system APIs to provide a consistent interface. Platform Implementations: - Android API levels <26: Uses `java.io.File`. - Java and Android API level 26+: Uses `java.nio.file`. - Linux: Abstracts `man pages`. - UNIX: Abstracts `stdio.h`. - Windows: Abstracts `fileapi.h`. - Node.js: Abstracts the Node.js `file system` module. ``` -------------------------------- ### Run Okio Benchmarks Source: https://github.com/square/okio/blob/master/okio/jvm/jmh/README.md Executes JMH microbenchmarks for the Okio project using Gradle. Configuration for benchmarks is done in the `jmh` section of the `okio/jvm/jmh/build.gradle` file. ```bash ./gradlew jmh ``` -------------------------------- ### Write Environment Variables to File (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Shows how to write system environment variables to a file in Kotlin using Okio's FileSystem.write function. This approach buffers the sink and handles closing automatically. ```Kotlin @Throws(IOException::class) fun writeEnv(path: Path) { FileSystem.SYSTEM.write(path) { for ((key, value) in System.getenv()) { writeUtf8(key) writeUtf8("=") writeUtf8(value) writeUtf8("\n") } } } ``` -------------------------------- ### Read Text File Line-by-Line Compact (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md A more compact Kotlin version for reading a text file line by line using Okio's FileSystem.read() for buffering and automatic closing. ```Kotlin @Throws(IOException::class) fun readLines(path: Path) { FileSystem.SYSTEM.read(path) { while (true) { val line = readUtf8Line() ?: break if ("square" in line) { println(line) } } } } ``` -------------------------------- ### Read Text File Line-by-Line (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates reading a text file line by line in Kotlin using Okio's FileSystem, Source, and BufferedSource. It uses the 'use' extension function for automatic resource management and filters lines containing 'square'. ```Kotlin fun readLines(path: Path) { FileSystem.SYSTEM.source(path).use { fileSource -> fileSource.buffer().use { bufferedFileSource -> while (true) { val line = bufferedFileSource.readUtf8Line() ?: break if ("square" in line) { println(line) } } } } } ``` -------------------------------- ### Write Environment Variables to File (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates how to write all system environment variables to a file using Okio's BufferedSink. It iterates through the environment entries and writes key-value pairs followed by a newline character. ```Java public void writeEnv(Path path) throws IOException { try (Sink fileSink = FileSystem.SYSTEM.sink(path); BufferedSink bufferedSink = Okio.buffer(fileSink)) { for (Map.Entry entry : System.getenv().entrySet()) { bufferedSink.writeUtf8(entry.getKey()); bufferedSink.writeUtf8("="); bufferedSink.writeUtf8(entry.getValue()); bufferedSink.writeUtf8("\n"); } } } ``` -------------------------------- ### Run Tests with Gradle Source: https://github.com/square/okio/blob/master/CONTRIBUTING.md This command cleans the project and runs all checks, ensuring tests are passing before submitting code changes. It is a prerequisite for contributing code. ```bash ./gradlew clean check ``` -------------------------------- ### Write Environment Variables to File (Java - Compact) Source: https://github.com/square/okio/blob/master/docs/recipes.md A more compact version of writing environment variables to a file in Java, utilizing method chaining for a more concise implementation. ```Java public void writeEnv(Path path) throws IOException { try (BufferedSink sink = Okio.buffer(FileSystem.SYSTEM.sink(path))) { for (Map.Entry entry : System.getenv().entrySet()) { sink.writeUtf8(entry.getKey()) .writeUtf8("=") .writeUtf8(entry.getValue()) .writeUtf8("\n"); } } } ``` -------------------------------- ### Network Communication with Okio Sockets (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates the basic usage of Okio for network communication with Java sockets. It shows how to obtain Okio sources and sinks from a Java Socket, which can also be used with SSLSocket. ```Java // Okio.source(Socket) // Okio.sink(Socket) // These APIs also work with SSLSocket. ``` -------------------------------- ### String UTF-8 Utility Functions Source: https://github.com/square/okio/blob/master/docs/recipes.md Prints string length, code point count, UTF-8 size, and UTF-8 bytes for a given string. This helps in understanding string encoding and size in Okio. ```Kotlin println(" " + s) println(" String.length: " + s.length) println("String.codePointCount: " + s.codePointCount(0, s.length)) println(" Utf8.size: " + s.utf8Size()) println(" UTF-8 bytes: " + s.encodeUtf8().hex()) println() ``` -------------------------------- ### Okio Dependency (Snapshot) Source: https://github.com/square/okio/blob/master/docs/index.md Adds a snapshot version of the Okio library to your project's dependencies. Snapshot builds are pre-release versions and may be unstable. ```kotlin repositories { maven("https://central.sonatype.com/repository/maven-snapshots/") } dependencies { implementation("com.squareup.okio:okio:3.17.0-SNAPSHOT") } ``` -------------------------------- ### Read Text File Line-by-Line (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates reading a text file line by line in Java using Okio's FileSystem, Source, and BufferedSource. It utilizes try-with-resources for automatic stream closing and filters lines containing 'square'. ```Java public void readLines(Path path) throws IOException { try (Source fileSource = FileSystem.SYSTEM.source(path); BufferedSource bufferedFileSource = Okio.buffer(fileSource)) { while (true) { String line = bufferedFileSource.readUtf8Line(); if (line == null) break; if (line.contains("square")) { System.out.println(line); } } } } ``` -------------------------------- ### Reading Signed Bytes and Shorts Source: https://github.com/square/okio/blob/master/docs/recipes.md Illustrates how to read byte and short values from a BufferedSource and convert them to unsigned integers using bitwise operations in Java and Kotlin. It includes a cheat sheet for converting signed to unsigned byte, short, and int types. ```Java int addressType = fromSource.readByte() & 0xff; int port = fromSource.readShort() & 0xffff; ``` ```Kotlin val addressType = fromSource.readByte().toInt() and 0xff val port = fromSource.readShort().toInt() and 0xffff ``` -------------------------------- ### Write Environment Variables to File with java.io.File Source: https://github.com/square/okio/blob/master/docs/java_io_recipes.md Writes all system environment variables to a text file using Okio's Sink and BufferedSink with a java.io.File. Each environment variable is written on a new line in the format 'KEY=VALUE'. This method requires Okio and standard Java I/O. ```Java public void writeEnv(File file) throws IOException { try (Sink fileSink = Okio.sink(file); BufferedSink bufferedSink = Okio.buffer(fileSink)) { for (Map.Entry entry : System.getenv().entrySet()) { bufferedSink.writeUtf8(entry.getKey()); bufferedSink.writeUtf8("="); bufferedSink.writeUtf8(entry.getValue()); bufferedSink.writeUtf8("\n"); } } } ``` ```Kotlin @Throws(IOException::class) fun writeEnv(file: File) { file.sink().buffer().use { sink -> for ((key, value) in System.getenv()) { sink.writeUtf8(key) sink.writeUtf8("=") sink.writeUtf8(value) sink.writeUtf8("\n") } } } ``` -------------------------------- ### String UTF-8 Utility Functions Source: https://github.com/square/okio/blob/master/docs/recipes.md Prints string length, code point count, UTF-8 size, and UTF-8 bytes for a given string. This helps in understanding string encoding and size in Okio. ```Java System.out.println(" String.length: " + s.length()); System.out.println("String.codePointCount: " + s.codePointCount(0, s.length())); System.out.println(" Utf8.size: " + Utf8.size(s)); System.out.println(" UTF-8 bytes: " + ByteString.encodeUtf8(s).hex()); System.out.println(); ``` -------------------------------- ### Creating Sockets with Okio Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates how to create BufferedSource and BufferedSink for sockets using Okio in both Java and Kotlin. It highlights that once a Source or Sink is created for a socket, the underlying InputStream or OutputStream should not be used. ```Java BufferedSource fromSource = Okio.buffer(Okio.source(fromSocket)); BufferedSink fromSink = Okio.buffer(Okio.sink(fromSocket)); ``` ```Kotlin val fromSocket: Socket = ... val fromSource = fromSocket.source().buffer() val fromSink = fromSocket.sink().buffer() ``` -------------------------------- ### Update Project Files for Release Source: https://github.com/square/okio/blob/master/docs/releasing.md This script updates version information in `gradle.properties` and `index.md` files using `sed`. It replaces the current release version with the new one and updates snapshot versions for the next development cycle. It also includes committing changes and tagging the release. ```bash sed -i "" "s/VERSION_NAME=.*/VERSION_NAME=$RELEASE_VERSION/g" \ gradle.properties sed -i "" "s/\"com.squareup.okio:\\([^:]*\):[0-9.]*\"/\"com.squareup.okio:\\1:$RELEASE_VERSION\"/g" \ `find . -name "index.md"` sed -i "" "s/\"com.squareup.okio:\\([^:]*\):[0-9.]*-SNAPSHOT\"/\"com.squareup.okio:\\1:$NEXT_VERSION\"/g" \ `find . -name "index.md"` git commit -am "Prepare for release $RELEASE_VERSION." git tag -a parent-$RELEASE_VERSION -m "Version $RELEASE_VERSION" sed -i "" "s/VERSION_NAME=.*/VERSION_NAME=$NEXT_VERSION/g" \ gradle.properties git commit -am "Prepare next development version." git push && git push --tags ``` -------------------------------- ### Okio Dependency (Stable) Source: https://github.com/square/okio/blob/master/docs/index.md Adds the stable version of the Okio library to your project's dependencies. This is the recommended version for most use cases. ```kotlin implementation("com.squareup.okio:okio:3.16.0") ``` -------------------------------- ### Read Text File Line-by-Line Compact (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md A more compact Java version for reading a text file line by line using Okio. It inlines the file source and uses a for loop for conciseness. ```Java public void readLines(Path path) throws IOException { try (BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(path))) { for (String line; (line = source.readUtf8Line()) != null; ) { if (line.contains("square")) { System.out.println(line); } } } } ``` -------------------------------- ### Generate MD5, SHA1, SHA256, SHA512 Hashes from Buffer Source: https://github.com/square/okio/blob/master/docs/recipes.md Shows how to compute MD5, SHA1, SHA256, and SHA512 hashes from a Buffer using Okio. The hex representation of the hash is printed. ```Java Buffer buffer = readBuffer(Path.get("README.md")); System.out.println(" md5: " + buffer.md5().hex()); System.out.println(" sha1: " + buffer.sha1().hex()); System.out.println("sha256: " + buffer.sha256().hex()); System.out.println("sha512: " + buffer.sha512().hex()); ``` ```Kotlin val buffer = readBuffer("README.md".toPath()) println(" md5: " + buffer.md5().hex()) println(" sha1: " + buffer.sha1().hex()) println(" sha256: " + buffer.sha256().hex()) println(" sha512: " + buffer.sha512().hex()) ``` -------------------------------- ### Set Release Versions Source: https://github.com/square/okio/blob/master/docs/releasing.md Sets the environment variables for the release version and the next development version. These variables are used in subsequent steps to update project files. ```shell export RELEASE_VERSION=X.Y.Z export NEXT_VERSION=X.Y.Z-SNAPSHOT ``` -------------------------------- ### Stream SHA256 Hash to Sink Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates computing a SHA256 hash while streaming data to a Sink using Okio. The data is read from a source and written to a HashingSink wrapped in a BufferedSink. ```Java try (HashingSink hashingSink = HashingSink.sha256(Okio.blackhole()); BufferedSink sink = Okio.buffer(hashingSink); Source source = FileSystem.SYSTEM.source(path)) { sink.writeAll(source); sink.close(); // Emit anything buffered. System.out.println("sha256: " + hashingSink.hash().hex()); } ``` ```Kotlin sha256(blackholeSink()).use { hashingSink -> hashingSink.buffer().use { sink -> FileSystem.SYSTEM.source(path).use { source -> sink.writeAll(source) sink.close() // Emit anything buffered. println(" sha256: " + hashingSink.hash.hex()) } } } ``` -------------------------------- ### Encrypt and Decrypt Data with Okio Cipher Source: https://github.com/square/okio/blob/master/docs/recipes.md This snippet shows how to encrypt data to a file and decrypt it back into a ByteString using Okio's cipherSource and cipherSink. It utilizes AES/CBC/PKCS5Padding for encryption and decryption. ```kotlin import okio.ByteString import okio.FileSystem import okio.buffer import okio.cipherSink import okio.cipherSource import java.nio.file.Path import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec // Extension function to encrypt ByteString to a file fun encryptAes(bytes: ByteString, path: Path, key: ByteArray, iv: ByteArray) { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv)) val cipherSink = FileSystem.SYSTEM.sink(path).cipherSink(cipher) cipherSink.buffer().use { it.write(bytes) } } // Extension function to decrypt a file to a ByteString fun decryptAesToByteString(path: Path, key: ByteArray, iv: ByteArray): ByteString { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv)) val cipherSource = FileSystem.SYSTEM.source(path).cipherSource(cipher) return cipherSource.buffer().use { it.readByteString() } } ``` ```java import okio.BufferedSource; import okio.ByteString; import okio.Okio; import okio.FileSystem; import java.nio.file.Path; import javax.crypto.Cipher; try (BufferedSource source = Okio.buffer( Okio.cipherSource(FileSystem.SYSTEM.source(path), cipher))) { return source.readByteString(); } ``` -------------------------------- ### Running All Android Tests Source: https://github.com/square/okio/blob/master/android-test/README.md Executes the entire Okio test suite on a connected Android device using Gradle. This command triggers the connectedAndroidTest task for the android-test module. ```bash ./gradlew :android-test:connectedAndroidTest ``` -------------------------------- ### Read Text File Line-by-Line Strict (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates reading a text file line by line strictly in Kotlin using Okio's readUtf8LineStrict. This method requires lines to be terminated by '\n' or '\r\n' and includes a byte limit. ```Kotlin @Throws(IOException::class) fun readLines(path: Path) { FileSystem.SYSTEM.read(path) { while (!source.exhausted()) { val line = source.readUtf8LineStrict(1024) if ("square" in line) { println(line) } } } } ``` -------------------------------- ### BMP Row Padding Logic (Java Snippet) Source: https://github.com/square/okio/blob/master/docs/recipes.md Illustrates the logic for calculating and applying padding to BMP image rows to ensure 4-byte alignment. This is crucial for the BMP format's integrity. ```Java // Padding for 4-byte alignment. // for (int p = rowByteCountWithoutPadding; p < rowByteCount; p++) { // sink.writeByte(0); // } ``` -------------------------------- ### Read Text File Line-by-Line with java.io.File Source: https://github.com/square/okio/blob/master/docs/java_io_recipes.md Reads a text file line by line using Okio's Source and BufferedSource with a java.io.File. It filters lines containing 'square' and prints them. This method requires Okio and standard Java I/O. ```Java public void readLines(File file) throws IOException { try (Source fileSource = Okio.source(file); BufferedSource bufferedFileSource = Okio.buffer(fileSource)) { while (true) { String line = bufferedFileSource.readUtf8Line(); if (line == null) break; if (line.contains("square")) { System.out.println(line); } } } } ``` ```Kotlin @Throws(IOException::class) fun readLines(file: File) { file.source().use { fileSource -> fileSource.buffer().use { bufferedFileSource -> while (true) { val line = bufferedFileSource.readUtf8Line() ?: break if ("square" in line) { println(line) } } } } } ``` -------------------------------- ### Stream SHA256 Hash from Source Source: https://github.com/square/okio/blob/master/docs/recipes.md Illustrates how to compute a SHA256 hash while streaming data from a Source using Okio's HashingSink. The hash is calculated from the entire content read from the source. ```Java try (HashingSink hashingSink = HashingSink.sha256(Okio.blackhole()); BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(path))) { source.readAll(hashingSink); System.out.println("sha256: " + hashingSink.hash().hex()); } ``` ```Kotlin sha256(blackholeSink()).use { hashingSink -> FileSystem.SYSTEM.source(path).buffer().use { source -> source.readAll(hashingSink) println(" sha256: " + hashingSink.hash.hex()) } } ``` -------------------------------- ### AES Encryption of a ByteString to a File Source: https://github.com/square/okio/blob/master/docs/recipes.md Provides a Java method to encrypt a ByteString to a file using AES/CBC/PKCS5Padding. It requires a key and an initialization vector (IV), both typically 16 bytes long. ```Java void encryptAes(ByteString bytes, Path path, byte[] key, byte[] iv) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); try (BufferedSink sink = Okio.buffer( Okio.cipherSink(FileSystem.SYSTEM.sink(path), cipher))) { sink.write(bytes); } } ``` -------------------------------- ### AES Decryption from a File to ByteString Source: https://github.com/square/okio/blob/master/docs/recipes.md Presents a Java method to decrypt a file using AES/CBC/PKCS5Padding and return the content as a ByteString. It requires the file path, a secret key, and an initialization vector (IV). ```Java ByteString decryptAesToByteString(Path path, byte[] key, byte[] iv) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); try (BufferedSource source = Okio.buffer(Okio.cipherSource(FileSystem.SYSTEM.source(path), cipher))) { return source.readByteString(); } } ``` -------------------------------- ### Generate MD5, SHA1, SHA256, SHA512 Hashes from ByteString Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates how to compute MD5, SHA1, SHA256, and SHA512 hashes from a ByteString using Okio. The hex representation of the hash is printed to the console. ```Java ByteString byteString = readByteString(Path.get("README.md")); System.out.println(" md5: " + byteString.md5().hex()); System.out.println(" sha1: " + byteString.sha1().hex()); System.out.println("sha256: " + byteString.sha256().hex()); System.out.println("sha512: " + byteString.sha512().hex()); ``` ```Kotlin val byteString = readByteString("README.md".toPath()) println(" md5: " + byteString.md5().hex()) println(" sha1: " + byteString.sha1().hex()) println(" sha256: " + byteString.sha256().hex()) println(" sha512: " + byteString.sha512().hex()) ``` -------------------------------- ### Read Text File Line-by-Line Strict (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Demonstrates reading a text file line by line strictly in Java using Okio's readUtf8LineStrict. This method requires lines to be terminated by '\n' or '\r\n' and includes a byte limit. ```Java public void readLines(Path path) throws IOException { try (BufferedSource source = Okio.buffer(FileSystem.SYSTEM.source(path))) { while (!source.exhausted()) { String line = source.readUtf8LineStrict(1024L); if (line.contains("square")) { System.out.println(line); } } } } ``` -------------------------------- ### Running a Specific Android Test Source: https://github.com/square/okio/blob/master/android-test/README.md Executes a single specified test class within the Okio test suite on an Android device. This is useful for targeted debugging and uses a Gradle property to specify the test class. ```bash ./gradlew :android-test:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=okio.SystemFileSystemTest ``` -------------------------------- ### Encode Bitmap to BMP Format (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Encodes a Bitmap object into the BMP file format using Okio's BufferedSink. This function handles the BMP header, DIB header, and pixel data, including necessary padding for 4-byte alignment of each row. It writes pixel data in BGR order. ```Kotlin import okio.BufferedSink import java.io.IOException // Assuming Bitmap class has methods like height, width, blue(x, y), green(x, y), red(x, y) // fun encode(bitmap: Bitmap, sink: BufferedSink) { // val height = bitmap.height // val width = bitmap.width // val bytesPerPixel = 3 // val rowByteCountWithoutPadding = bytesPerPixel * width // val rowByteCount = (rowByteCountWithoutPadding + 3) / 4 * 4 // val pixelDataSize = rowByteCount * height // val bmpHeaderSize = 14 // val dibHeaderSize = 40 // // // BMP Header // sink.writeUtf8("BM") // ID. // sink.writeIntLe(bmpHeaderSize + dibHeaderSize + pixelDataSize) // File size. // sink.writeShortLe(0) // Unused. // sink.writeShortLe(0) // Unused. // sink.writeIntLe(bmpHeaderSize + dibHeaderSize) // Offset of pixel data. // // // DIB Header // sink.writeIntLe(dibHeaderSize) // sink.writeIntLe(width) // sink.writeIntLe(height) // sink.writeShortLe(1) // Color plane count. // sink.writeShortLe(bytesPerPixel * Byte.SIZE_BITS) // sink.writeIntLe(0) // No compression. // sink.writeIntLe(16) // Size of bitmap data including padding. // sink.writeIntLe(2835) // Horizontal print resolution in pixels/meter. (72 dpi). // sink.writeIntLe(2835) // Vertical print resolution in pixels/meter. (72 dpi). // sink.writeIntLe(0) // Palette color count. // sink.writeIntLe(0) // 0 important colors. // // // Pixel data. // for (y in height - 1 downTo 0) { // for (x in 0 until width) { // sink.writeByte(bitmap.blue(x, y)) // sink.writeByte(bitmap.green(x, y)) // sink.writeByte(bitmap.red(x, y)) // } // // // Padding for 4-byte alignment. // for (p in rowByteCountWithoutPadding until rowByteCount) { // sink.writeByte(0) // } // } // } ``` -------------------------------- ### Compute and Print Golden Value (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Computes a golden value by serializing a Point object and printing its base64 representation. This base64 string can be embedded in tests. ```Kotlin val point = Point(8.0, 15.0) val pointBytes = serialize(point) println(pointBytes.base64()) ``` -------------------------------- ### Hashing Functions in Okio Source: https://github.com/square/okio/blob/master/docs/recipes.md Details the cryptographic hash functions supported by Okio: MD5, SHA-1, SHA-256, and SHA-512. It explains the properties of hash functions (deterministic, uniform, non-reversible, well-known) and provides guidance on choosing appropriate hash functions, recommending SHA-256 for most use cases. ```APIDOC Hashing Functions: Okio supports the following cryptographic hash functions: - MD5: 128-bit hash. Insecure and obsolete, but available for legacy systems. - SHA-1: 160-bit hash. Feasible to create collisions, consider upgrading. - SHA-256: 256-bit hash. Widely understood, expensive to reverse, recommended for most systems. - SHA-512: 512-bit hash. Expensive to reverse. Each hash function creates a ByteString of the specified length. Use `hex()` to get the conventional string representation. ``` -------------------------------- ### Generate HMAC-SHA256 from ByteString Source: https://github.com/square/okio/blob/master/docs/recipes.md Shows how to compute an HMAC-SHA256 hash using a secret key and a ByteString with Okio. The result is the hex representation of the HMAC. ```Java ByteString secret = ByteString.decodeHex("7065616e7574627574746572"); System.out.println("hmacSha256: " + byteString.hmacSha256(secret).hex()); ``` ```Kotlin val secret = "7065616e7574627574746572".decodeHex() println("hmacSha256: " + byteString.hmacSha256(secret).hex()) ``` -------------------------------- ### Encode Bitmap to BMP File Source: https://github.com/square/okio/blob/master/docs/recipes.md Encodes a Bitmap object into a BMP file format using Okio's BufferedSink in Java. It handles BMP header, DIB header, and pixel data, including padding and endianness considerations. ```Java void encode(Bitmap bitmap, BufferedSink sink) throws IOException { int height = bitmap.height(); int width = bitmap.width(); int bytesPerPixel = 3; int rowByteCountWithoutPadding = (bytesPerPixel * width); int rowByteCount = ((rowByteCountWithoutPadding + 3) / 4) * 4; int pixelDataSize = rowByteCount * height; int bmpHeaderSize = 14; int dibHeaderSize = 40; // BMP Header sink.writeUtf8("BM"); // ID. sink.writeIntLe(bmpHeaderSize + dibHeaderSize + pixelDataSize); // File size. sink.writeShortLe(0); // Unused. sink.writeShortLe(0); // Unused. sink.writeIntLe(bmpHeaderSize + dibHeaderSize); // Offset of pixel data. // DIB Header sink.writeIntLe(dibHeaderSize); sink.writeIntLe(width); sink.writeIntLe(height); sink.writeShortLe(1); // Color plane count. sink.writeShortLe(bytesPerPixel * Byte.SIZE); sink.writeIntLe(0); // No compression. sink.writeIntLe(16); // Size of bitmap data including padding. sink.writeIntLe(2835); // Horizontal print resolution in pixels/meter. (72 dpi). sink.writeIntLe(2835); // Vertical print resolution in pixels/meter. (72 dpi). sink.writeIntLe(0); // Palette color count. sink.writeIntLe(0); // 0 important colors. // Pixel data. for (int y = height - 1; y >= 0; y--) { ``` -------------------------------- ### Compute and Print Golden Value (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Computes a golden value by serializing a Point object and printing its base64 representation. This base64 string can be embedded in tests. ```Java Point point = new Point(8.0, 15.0); ByteString pointBytes = serialize(point); System.out.println(pointBytes.base64()); ``` -------------------------------- ### Decode Base64 Golden Value (Kotlin) Source: https://github.com/square/okio/blob/master/docs/recipes.md Decodes a base64 encoded string back into a ByteString. This is used to embed golden values directly into test cases. ```Kotlin val goldenBytes = ("rO0ABXNyACRva2lvLnNhbXBsZXMuS290bGluR29sZGVuVmFsdWUkUG9pbnRF9yaY7cJ9EwIAA" + "kQAAXhEAAF5eHBAIAAAAAAAAEAuAAAAAAAA").decodeBase64() ``` -------------------------------- ### Kotlin Serialization Golden Value Source: https://github.com/square/okio/blob/master/docs/recipes.md Serializes an object to a ByteString using Java Serialization and Okio's Buffer. This is useful for golden value testing to ensure data compatibility across versions. ```Kotlin @Throws(IOException::class) private fun serialize(o: Any?): ByteString { val buffer = Buffer() ObjectOutputStream(buffer.outputStream()).use { objectOut -> objectOut.writeObject(o) } return buffer.readByteString() } ``` -------------------------------- ### Kotlin Deserialization Golden Value Source: https://github.com/square/okio/blob/master/docs/recipes.md Deserializes a ByteString back into an object using Java Serialization and Okio's Buffer. This verifies that serialized data can be correctly read. ```Kotlin @Throws(IOException::class, ClassNotFoundException::class) private fun deserialize(byteString: ByteString): Any? { val buffer = Buffer() buffer.write(byteString) ObjectInputStream(buffer.inputStream()).use { objectIn -> return objectIn.readObject() } } ``` -------------------------------- ### Deserialize Golden Value Source: https://github.com/square/okio/blob/master/docs/recipes.md Tests the deserialization of a golden value using ByteString in Java and Kotlin. It asserts that the decoded object matches the expected Point value. ```Java ByteString goldenBytes = ByteString.decodeBase64("rO0ABXNyAB5va2lvLnNhbXBsZXMuR29sZGVuVmFsdWUkUG9pbnTdUW8rMji1IwIAAkQAAXhEAAF5eHBAIAAAAAAAAEAuAAAAAAAA"); Point decoded = (Point) deserialize(goldenBytes); assertEquals(new Point(8.0, 15.0), decoded); ``` ```Kotlin val goldenBytes = ("rO0ABXNyACRva2lvLnNhbXBsZXMuS290bGluR29sZGVuVmFsdWUkUG9pbnRF9yaY7cJ9EwIAA kQAAXhEAAF5eHBAIAAAAAAAAEAuAAAAAAAA").decodeBase64()!! val decoded = deserialize(goldenBytes) as Point assertEquals(point, decoded) ``` -------------------------------- ### Streaming Test Logs with adb logcat Source: https://github.com/square/okio/blob/master/android-test/README.md Streams error and test-related logs from an Android device using adb logcat. This is crucial for debugging test failures, especially process crashes. ```bash adb logcat '*:E' TestRunner:D TaskRunner:D GnssHAL_GnssInterface:F DeviceStateChecker:F memtrack:F ``` -------------------------------- ### Decode Base64 Golden Value (Java) Source: https://github.com/square/okio/blob/master/docs/recipes.md Decodes a base64 encoded string back into a ByteString. This is used to embed golden values directly into test cases. ```Java ByteString goldenBytes = ByteString.decodeBase64("rO0ABXNyAB5va2lvLnNhbXBsZ" + "XMuR29sZGVuVmFsdWUkUG9pbnTdUW8rMji1IwIAAkQAAXhEAAF5eHBAIAAAAAAAAEAuA" + "AAAAAAA"); ``` -------------------------------- ### Java Serialization Golden Value Source: https://github.com/square/okio/blob/master/docs/recipes.md Serializes an object to a ByteString using Java Serialization and Okio's Buffer. This is useful for golden value testing to ensure data compatibility across versions. ```Java private ByteString serialize(Object o) throws IOException { Buffer buffer = new Buffer(); try (ObjectOutputStream objectOut = new ObjectOutputStream(buffer.outputStream())) { objectOut.writeObject(o); } return buffer.readByteString(); } ``` -------------------------------- ### Java Deserialization Golden Value Source: https://github.com/square/okio/blob/master/docs/recipes.md Deserializes a ByteString back into an object using Java Serialization and Okio's Buffer. This verifies that serialized data can be correctly read. ```Java private Object deserialize(ByteString byteString) throws IOException, ClassNotFoundException { Buffer buffer = new Buffer(); buffer.write(byteString); try (ObjectInputStream objectIn = new ObjectInputStream(buffer.inputStream())) { return objectIn.readObject(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.