### Solving LeetCode 875 Koko Eating Bananas with BinarySearch Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This example demonstrates how to find the minimum eating speed for Koko to finish all bananas within a given time `h`. It uses `BinarySearch.forInts` with a condition-based search (`canFinish`) to guide the search towards the smallest speed that satisfies the condition, then uses `.ceiling()` to get the result. ```Java int minSpeed(List piles, int h) { return BinarySearch.forInts(Range.closed(1, max(piles))) // if Koko can finish, eat slower, else eat faster .insertionPointFor((lo, speed, hi) -> canFinish(piles, speed, h) ? -1 : 1) // floor() is the max speed that can't finish; ceiling() is the min that can .ceiling(); } boolean canFinish(List piles, int speed, int h) { int time = 0; for (int pile : piles) { time += (pile + speed - 1) / speed; } return time <= h; } ``` -------------------------------- ### Formatting with DateTimeFormats using Example String (Full Date/Time) Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This snippet demonstrates using `DateTimeFormats.formatOf()` to create a `DateTimeFormatter` by providing a full example string. This approach simplifies formatter definition by inferring the pattern from the human-readable example, equivalent to `DateTimeFormatter.ofPattern("EEEE, LLLL dd yyyy HH:mm:ss.SSS VV")`. ```java import static com.google.mu.time.DateTimeFormats.formatOf; // Equivalent to DateTimeFormatter.ofPattern("EEEE, LLLL dd yyyy HH:mm:ss.SSS VV") private static final DateTimeFormatter FORMATTER = formatOf( "Friday, October 20 2023 10:30:05.000 America/New_York"); ``` -------------------------------- ### Parse DateTimes by Example with Java DateTimeFormats Source: https://github.com/google/mug/blob/master/README.md Shows how to create a DateTimeFormatter using formatOf by providing an example string. This utility simplifies parsing various date and time formats based on a given pattern. ```Java DateTimeFormatter format = formatOf("2024-03-14 10:00:00.123 America/New_York") ``` -------------------------------- ### Solving LeetCode 410 Split Array Largest Sum with BinarySearch Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This example addresses the problem of splitting an array `nums` into `k` parts such that the largest sum among these parts is minimized. It uses `BinarySearch.forInts` with a condition-based search (`canSplit`) to find the smallest feasible maximum subarray sum, and then applies `.ceiling()` to get the result. ```Java int splitArray(int[] nums, int k) { int total = Arrays.stream(nums).sum(); int max = Arrays.stream(nums).max().getAsInt(); return BinarySearch.forInts(Range.closed(max, total)) // if canSplit, try smaller sum, else try larger sum .insertionPointFor((lo, maxSum, hi) -> canSplit(nums, maxSum, k) ? -1 : 1) // floor is the largest that can't split, ceiling is the min that can .ceiling(); } boolean canSplit(int[] nums, int maxSum, int k) { int count = 1, sum = 0; for (int num : nums) { if (sum + num > maxSum) { count++; sum = 0; } sum += num; } return count <= k; } ``` -------------------------------- ### SafeSql Example: Dynamic Columns and LIKE Clause Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This SafeSql example demonstrates how to safely construct a query with dynamic column names and a `LIKE` clause. The `{columns}` placeholder ensures identifier safety through strict validation, and `SafeSql` automatically escapes special characters (`%`, `_`, `\`) in the `keyword` for `LIKE` patterns. ```java SafeSql query = SafeSql.of( "SELECT `{columns}` FROM users WHERE name LIKE '%{keyword}%'", /* columns */ List.of("id", "email"), /* keyword */ "100%"); ``` -------------------------------- ### Zipping Collections or Streams into BiStream Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example shows how to create a BiStream by zipping two separate collections or streams together, pairing elements based on their order, useful for combining related data like requests and responses. ```java // If you have a list of requests and responses to pair up: BiStream.zip(requests, responses) .mapKeys(Request::fingerprint) ...; ``` -------------------------------- ### Matching the First of Multiple Patterns in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md This Java example shows how to create a `Substring.Pattern` that matches the first occurrence of any keyword from a stream. It maps each keyword to a `Substring::first` pattern and then collects them using `firstOccurrence()`. ```java Substring.Pattern keyword = keywords.stream() .map(Substring::first) .collect(firstOccurrence()); ``` -------------------------------- ### Understanding BinarySearch.Table.insertionPointFor Method Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This snippet introduces the core `insertionPointFor` method of `BinarySearch.Table`. It explains that the user is responsible for guiding the search direction at each probe point `mid` by providing a lambda expression. It also notes that simpler methods like `find()` and `rangeOf()` exist for everyday use, while `insertionPointFor()` is for advanced problems. ```Java insertionPointFor((lo, mid, hi) -> ...) ``` -------------------------------- ### Defining DateTimeFormatter Patterns in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md These examples illustrate the traditional way of defining date and time formats using `DateTimeFormatter.ofPattern()` in Java. They showcase the use of various format specifiers, highlighting the complexity and the need for memorization of the pattern syntax. ```java DateTimeFormatter.ofPattern("EEEE, LLLL dd MM HH:mm:ss.SSSa VV"); DateTimeFormatter.ofPattern("EEEE, yyyy-MM-dd hh:mm:ss.SSSa ZZZZZ"); ``` -------------------------------- ### Mapping BiStream Elements by Key, Value, or Both Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md Illustrates how to transform elements in a BiStream using map operations. Examples include mapping keys, mapping values, and mapping values based on both key and value. ```Java Map households = ...; // by key BiStream.from(households) .mapKeys(Address::state) ...; // by value BiStream.from(households) .mapValues(Household::income) ...; // from both key and value BiStream.from(households) .mapValues((address, household) -> fiveYearAverageIncome(address, household)) ...; ``` -------------------------------- ### Creating BiStream with groupingBy Collector Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example demonstrates using BiStream's `groupingBy` collector, which is more convenient than JDK's `groupingBy` for reducing group members, to aggregate data into a Map. ```java import static com.google.mu.util.stream.BiStream.groupingBy; import java.util.stream.Collectors.counting; Map cityHouseholds = addresses.stream() .collect(groupingBy(Address::city, counting())); // Using a BiFunction to reduce group members is more convenient than JDK's groupingBy() Map richestHouseholds = households.stream() .collect(groupingBy(Household::city, this::richerHousehold)); ``` -------------------------------- ### SafeSql Generated SQL Query Example Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This SQL output shows the query generated by SafeSql from the previous Java example. Notice how the column names are correctly quoted (`id`, `email`) and the `LIKE` value is parameterized (`?`), ensuring both identifier and value safety. ```sql SELECT `id`, `email` FROM users WHERE name LIKE ? ``` -------------------------------- ### Obtain topological ordering of a DAG in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/README.md Illustrates how to use Walker to get a topological ordering of nodes in a Directed Acyclic Graph (DAG) based on their dependencies. ```Java List sorted = Walker.inGraph(Node::getDependencies) .topologicalOrderFrom(nodes); ``` -------------------------------- ### Formatting with DateTimeFormats for ISO Date Time Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This snippet demonstrates using `DateTimeFormats.formatOf()` to generate a formatter equivalent to `DateTimeFormatter.ISO_DATE_TIME` by providing an ISO-formatted example string. It highlights the library's ability to handle standard formats intuitively. ```java // Equivalent to DateTimeFormatter.ISO_DATE_TIME private static final DateTimeFormatter FORMATTER = formatOf( "2023-10-09T11:12:13.1+01:00[Europe/Paris]"); ``` -------------------------------- ### Create Safe SQL Templates with Java SafeSql Source: https://github.com/google/mug/blob/master/README.md Provides an example of using SafeSql to construct SQL queries safely, preventing injection vulnerabilities. It demonstrates embedding column names and IDs securely into a SQL statement. ```Java SafeSql.of("select id, `{col}` from Users where id = {id}", col, id) ``` -------------------------------- ### Formatting with DateTimeFormats using Example String (Abbreviated Date/Time) Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This example shows how `DateTimeFormats.formatOf()` can infer a formatter from an abbreviated date and time string, such as 'Fri, 2023 Oct 20 10:30-08:00'. This is equivalent to `ofPattern("E, yyyy LLL dd HH:mm:ssZZZZZ")`, showcasing the library's flexibility. ```java // Equivalent to ofPattern("E, yyyy LLL dd HH:mm:ssZZZZZ") private static final DateTimeFormatter FORMATTER = formatOf( "Fri, 2023 Oct 20 10:30-08:00"); ``` -------------------------------- ### Collecting BiStream to Custom Data Structure Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example demonstrates the flexibility of BiStream by showing how to collect its elements into a custom data structure, such as a `Ledger`, by providing a compatible `BiCollector` signature. ```java // compatible with BiCollector signature Collector> toLedger( Function toTime, Function toValue) {...} Ledger ledger = ledger.timeseries() .filterKeys(...) .collect(this::toLedger); // method-ref as a BiCollector ``` -------------------------------- ### Filtering BiStream Elements by Key, Value, or Both Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md Demonstrates various ways to filter elements in a BiStream. Examples include filtering by key, by value, and by both key and value using a custom predicate. ```Java Map phoneBook = ...; // by key BiStream.from(phoneBook) .filterKeys(phoneNumber -> phoneNumber.startsWith("312")) ... // by value BiStream.from(phoneBook) .filterValues(address -> address.state().equals("IL")) ... // by both key and value BiStream.from(phoneBook) .filterValues((phoneNumber, address) -> isExpired(phoneNumber, address)) ...; ``` -------------------------------- ### Formatting with DateTimeFormats for RFC 1123 Date Time Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This example illustrates how `DateTimeFormats.formatOf()` can infer a formatter for RFC 1123 date and time strings, equivalent to `DateTimeFormatter.RFC_1123_DATE_TIME`. This simplifies handling common web-standard date formats. ```java // Equivalent to DateTimeFormatter.RFC_1123_DATE_TIME private static final DateTimeFormatter FORMATTER = formatOf( "Tue, 10 Jun 2008 11:05:30 GMT"); ``` -------------------------------- ### Extract and Manipulate Substrings with Java Substring Utility Source: https://github.com/google/mug/blob/master/README.md Shows how to use the Substring utility for composable substring extraction and manipulation. This example extracts content between specific delimiters, such as parentheses. ```Java Substring.between("(", ")").from("call(foo)") ``` -------------------------------- ### Transforming and Filtering Map Entries with BiStream vs Java 8 Stream Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example demonstrates the boilerplate involved in transforming and filtering map entries using Java 8's Stream API compared to the more concise and readable approach with BiStream. It shows how to map keys and then filter them based on a condition. ```Java map.entrySet().stream() .map(e -> Map.entry(transform(e.getKey()), e.getValue())) .filter(e -> isGood(e.getKey()) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); ``` ```Java BiStream.from(map) .mapKeys(this::transform) .filterKeys(this::isGood) .toMap(); ``` -------------------------------- ### BinarySearch Target-Based Search Pattern Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This pattern represents the traditional form of binary search, used for finding an exact match in a sorted collection. The lambda function returns `0` for a match, `< 0` to search left, and `> 0` to search right, guiding the search towards a specific target value. ```Java insertionPointFor((lo, mid, hi) -> compare(target, mid)); ``` -------------------------------- ### Collecting BiStream to Guava ImmutableMap Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example demonstrates collecting a BiStream into a Guava ImmutableMap using a method reference to `ImmutableMap::toImmutableMap`, leveraging BiCollector's compatible method signature. ```java ImmutableMap all = BiStream.concat(cached, onDemand) .collect(ImmutableMap::toImmutableMap); ``` -------------------------------- ### Perform breadth-first search with filtering in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/README.md Demonstrates how to use Walker to perform a breadth-first search (BFS) starting from a node, then filter the results based on a condition and limit the number of returned nodes. ```Java List reachableSamples = Walker.inGraph(Node::getNeighborNodes) .breadthFirstFrom(startNode) .filter(this::isAcceptable) .limit(10) .toList(); ``` -------------------------------- ### SafeSql Example: Dynamic Table Name Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This SafeSql snippet illustrates how to safely incorporate a dynamic table name into a query. By using the `{table}` placeholder, SafeSql ensures that the table name is properly handled and validated, preventing identifier injection. ```java SafeSql query = SafeSql.of( "SELECT * FROM `{table}` WHERE status = {status}", table, status); ``` -------------------------------- ### Initial Mug Walker Graph Traversal Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/find_path_in_graph.md Demonstrates the initial usage of Mug's `Walker.inGraph()` for breadth-first traversal starting from a list of root pages. It filters for pages that are known phishing sites. This version has a limitation where `VisitedPage`'s default equality check (which includes the referrer) leads to re-exploring the same URL if visited from different parent pages, wasting resources. ```java List rootPages = officialCompanyUrls.stream().map(VisitedPage::from).toList(); Optional result = Walker.inGraph(VisitedPage::exploreLinks) .breadthFirstFrom(rootPages) // assume we have a small helper to parse the domain from a url .filter(page -> knownPhishingSites.contains(parseDomain(page))) .findFirst(); ``` -------------------------------- ### HTTP Request Exploiting Identifier Injection Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This HTTP GET request shows a malicious payload targeting the `sort` parameter. The injected string `name desc; DROP TABLE users --` attempts to execute an additional SQL command by terminating the `ORDER BY` clause and adding a `DROP TABLE` statement. ```http GET /users?sort=name desc; DROP TABLE users -- ``` -------------------------------- ### Flattening BiStream Elements with flatMap by Key, Value, or Both Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md Shows how to use flatMap operations in BiStream to flatten nested structures. Examples include flattening keys, flattening values, and flattening based on both key and value. ```Java Map households = ...; // by key BiStream.from(households) .flatMapKeys(address -> address.getPhoneNumbers().stream()) ...; // by value BiStream.from(households) .flatMapValues(household -> household.members().stream()) ...; // by both key and value BiStream.from(phoneBook) .flatMap((address, household) -> BiStream.from(household.getMemberMap())) ...; ``` -------------------------------- ### Extract and manipulate repeated patterns with Substring in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Demonstrates advanced usage of `Substring.repeatedly()` to extract all occurrences of a pattern, remove all occurrences, or replace all occurrences based on a transformation function. Examples include extracting values, removing comments, and replacing placeholders. ```Java // Extract all values between { and } in a snippet List values = Substring.between("{", "}").repeatedly().from(snippet).toList(); // Remove all block comments from code String noComments = Substring.spanningInOrder("/*", "*/").repeatedly().removeAllFrom(code); // Replace all placeholders in template String output = Substring.spanningInOrder("{", "}").repeatedly().replaceAllFrom( template, placeholder -> resolve(placeholder.skip(1, 1).toString())); ``` -------------------------------- ### Fibonacci Sequence Generation with Iteration Class Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md Shows an advanced use case where `whileNotNull()` drives the `Iteration` class, enabling lazy, stack-safe stream pipelines for recursive logic. This example generates a Fibonacci sequence without consuming the whole tree or causing stack overflows. ```Java class Fibonacci extends Iteration { Fibonacci fib(int a, int b) { this.yield(a); this.yield(() -> fib(b, a + b)); return this; } } Stream sequence = new Fibonacci().fib(0, 1).iterate().limit(10); ``` -------------------------------- ### Customizing DateTimeFormatter with formatOf in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This Java code snippet demonstrates how to create a flexible `DateTimeFormatter` using the `formatOf` method. It illustrates the use of square brackets `[.SSS]` to make the microsecond part optional, only printing it if non-zero. The method combines explicit pattern specifiers with example strings (enclosed in pointy brackets) to infer the desired format. ```Java // Equivalent to DateTimeFormatter.ofPattern("EEEE, dd/MM/yyyy HH:mm:ss[.SSS] VV") private static final DateTimeFormatter FORMATTER = formatOf( ", <30/01/2014 10:30:05>[.SSS] "); ``` -------------------------------- ### Resolving Ambiguity in Date Formats with DateTimeFormats Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md These examples demonstrate how to resolve ambiguity in date formats like '01/02/2023' (which could be January 2nd or February 1st) using `DateTimeFormats.formatOf()`. By providing an unambiguous day-of-month (e.g., 30), the library can correctly infer the desired month/day order. ```java formatOf("01/30/2023") ``` ```java formatOf("30/01/2023") ``` -------------------------------- ### Flattening Nested Maps with BiStream vs Java 8 Stream Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This example illustrates the complexity of flattening a nested Map (e.g., Map> to Map) using Java 8 Stream API, and contrasts it with the simpler BiStream equivalent. It shows how to concatenate keys from nested maps. ```Java map.entrySet().stream() .flatMap(e -> e.getValue().entrySet().stream() .map(innerEntry -> Map.entry(e.getKey() + innerEntry.getKey(), innerEntry.getValue()))) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); ``` ```Java BiStream.from(map) .flatMap((r, m) -> BiStream.from(m).mapKeys(r::concat)) .toMap(); ``` -------------------------------- ### Vulnerable Spring JDBC Dynamic Table Name Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This Spring JDBC example demonstrates identifier injection when a table name is constructed from user input. Even though `?` is used for value binding, the table name itself is concatenated unsafely, allowing an attacker to inject malicious table names or other SQL structures. ```java String table = request.getParameter("table"); String sql = "SELECT * FROM " + table + " WHERE status = ?"; jdbcTemplate.query(sql, status); ``` -------------------------------- ### Parse and format strings with StringFormat in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Demonstrates how to use `StringFormat` to both parse a string into components and format components back into a string using named placeholders. Shows bi-directional functionality. ```Java StringFormat format = new StringFormat("User {id} - {name}"); Optional formatted = format.parse("User 42 - Alice", (id, name) -> id + ":" + name); // => Optional.of("42:Alice") String output = format.format(/* id */ 42, /* name */ "Alice"); // => "User 42 - Alice" ``` -------------------------------- ### Creating BiStream from JDK Collections and Streams Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This snippet demonstrates how to initialize a BiStream from existing Java collections such as Map, Multimap, or any generic collection/stream, allowing for flexible key-value pairing. ```java // From Map BiStream.from(map); // From Multimap BiStream.from(multimap.entries()); // From any collection or stream Map idToName = BiStream.from(students, Student::id, Student::name).toMap(); Map studentMap = BiStream.biStream(students) .mapKeys(Student::id) .toMap(); ``` -------------------------------- ### Regex vs. Substring/StringFormat Comparison Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md This table illustrates common text manipulation use cases, comparing their implementation using traditional Regular Expressions against the more readable and composable `Substring` and `StringFormat` methods from the Google Mug library. It highlights how Mug prioritizes clear intent. ```APIDOC Use case: After `=` Regex pattern: `(?<=\u003d).*` Substring / StringFormat: `after("=")` Use case: Inside square brackets Regex pattern: `\[(.*?)]` Substring / StringFormat: `between("[", "]")` Use case: Path segments Regex pattern: `[^/]+` with `split("/")` Substring / StringFormat: `all("/").split(path)` Use case: Parse `id=value` string Regex pattern: `id=(\w+)` Substring / StringFormat: `new StringFormat("id={value}")` Use case: Replace `{...}` placeholders Regex pattern: `\{.*?\}` with matcher.replaceAll Substring / StringFormat: `spanningInOrder("{", "}").replaceAllFrom(template, ...)` ``` -------------------------------- ### Find shortest paths from a source node in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/README.md Shows how to use ShortestPath utility to find shortest paths from a given source location, then map the results, filter them based on a condition, and limit the number of returned paths. ```Java List nearbySushiPlaces = ShortestPath.shortestPathsFrom(myLocation, Location::locationsAroundMe) .map(ShortestPath::to) .filter(this::isSushiRestaurant) .limit(3) .toList(); ``` -------------------------------- ### StringFormat vs. Substring Feature Comparison Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md This table outlines the key differences and complementary aspects of `Substring` and `StringFormat` classes within the Google Mug library. It details their composition styles, readability, and primary use cases, emphasizing their distinct strengths in text processing. ```APIDOC Feature: Composition Substring: Fine-grained StringFormat: Template-driven Feature: Readability Substring: Expression-like StringFormat: Sentence-like Feature: Use case Substring: Supports dynamic values StringFormat: Compile-time pattern like "User {id} - {name}" ``` -------------------------------- ### Initialize Graph Walker with Guava BloomFilter Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/walking_massive_graph.md This Java code demonstrates how to initialize a `Walker` for graph traversal, integrating a Guava `BloomFilter` to track visited nodes. The `Walker` uses a lambda for exploring links and another lambda to check if a page's URL might have been visited using the Bloom filter. This approach optimizes memory for large graphs by trading a controlled false positive rate for sublinear memory usage. ```Java BloomFilter visited = ...; Walker walker = Walker.inGraph( webPage -> webPage.exploreLinks(), page -> visited.mightContain(page.url())); ``` -------------------------------- ### Solving LeetCode 69 Integer Square Root with BinarySearch Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This snippet shows how to compute the floor of the square root of an integer `x` without using built-in functions. It uses `BinarySearch.forInts` with a target-based comparison (`Long.compare(x, (long) mid * mid)`) to find the largest number whose square is less than or equal to `x`, then uses `.floor()` to retrieve it. ```Java int mySqrt(int x) { return BinarySearch.forInts(Range.closed(0, x)) // if square is larger, try smaller sqrt .insertionPointFor((lo, mid, hi) -> Long.compare(x, (long) mid * mid)) // floor() is the max whose square <= x .floor(); } ``` -------------------------------- ### Implement Simple Structured Concurrency with Java Virtual Threads Source: https://github.com/google/mug/blob/master/README.md Illustrates a simple structured concurrency pattern using 'concurrently' for parallel execution of tasks on virtual threads, allowing for easy combination of their results. ```Java concurrently(() -> fetchArm(), () -> fetchLeg(), (arm, leg) -> makeRobot(arm, leg)) ``` -------------------------------- ### Performing Concurrent IO Operations with Java Fanout Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/concurrent/README.md This snippet demonstrates how to use the `Fanout.concurrently` API to execute multiple IO-bound operations (like database reads and RPC calls) concurrently using Java virtual threads. It shows how the results from concurrent operations are passed to a lambda for combination, and how exceptions or interruptions are handled automatically, ensuring efficient resource utilization and simplified asynchronous code. ```java import static com.google.mu.util.concurrent.Fanout.concurrently; ... Result calculateBilling() { return concurrently( () -> readJobTimelineFromDb(...), () -> callServiceForLatestAccountInfo(...), (timeline, accountInfo) -> ...); } ``` -------------------------------- ### Add Mug Dependencies to Gradle Project Source: https://github.com/google/mug/blob/master/README.md Provides the Gradle Groovy snippet for adding core, Guava, and Protobuf Mug dependencies to a build.gradle file using the 'implementation' configuration. ```Groovy implementation 'com.google.mug:mug:8.6' implementation 'com.google.mug:mug-guava:8.6' implementation 'com.google.mug:mug-protobuf:8.6' ``` -------------------------------- ### BinarySearch Condition-Based Optimization Search Pattern Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/collect/README.md This pattern is used for optimization problems, where the goal is to find the minimum or maximum value for which a certain condition holds true. The condition must be monotonic. The lambda returns `-1` to search left (try smaller values) or `1` to search right (try larger values), without needing to return `0` for an exact match. ```Java insertionPointFor((lo, mid, hi) -> condition(mid) ? -1 : 1); ``` ```Java insertionPointFor((lo, mid, hi) -> canShipWithinDays(mid) ? -1 : 1); ``` -------------------------------- ### Parse into typed objects with StringFormat in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Shows how `StringFormat` can directly parse a string into a Java record (or any typed object with a matching constructor), simplifying data mapping. ```Java record User(int id, String name) {} Optional user = new StringFormat("User {id} - {name}") .parse("User 42 - Alice", User::new); ``` -------------------------------- ### Creating BiStream by Splitting Strings Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This snippet shows how to generate a BiStream by parsing strings, splitting them into key-value pairs using a delimiter, either directly or as part of a stream pipeline with `toBiStream`. ```java Map keyValues = BiStream.from(flags, flag -> Substring.first('=').splitThenTrim(flag).orElseThrow(...)); // or via a Collector in the middle of a stream pipeline import static com.google.mu.util.stream.BiStream.toBiStream; Map keyValues = lines.stream() ... .collect(toBiStream(kv -> Substring.first('=').splitThenTrim(kv).orElseThrow(...))) .toMap(); ``` -------------------------------- ### Handle Optional Values with Java Optionals Utility Source: https://github.com/google/mug/blob/master/README.md Demonstrates using 'optionally' to create an Optional based on a boolean condition and a supplier, providing a concise way to handle optional values and avoid null checks. ```Java return optionally(obj.hasFoo(), obj::getFoo); ``` -------------------------------- ### Configure Maven Compiler Plugin for Mug Error Prone Source: https://github.com/google/mug/blob/master/mug-errorprone/README.md This Maven POM snippet configures the `maven-compiler-plugin` to include the `error_prone_core` and `mug-errorprone` annotation processors. This enables compile-time checks for `StringFormat` and `SafeQuery` classes, enhancing code safety. Add this configuration within the `` tag of your `maven-compiler-plugin`. ```XML com.google.errorprone error_prone_core 2.23.0 com.google.mug mug-errorprone 7.0 ``` -------------------------------- ### Matching BiStream Elements with anyMatch, allMatch, noneMatch Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md Demonstrates the use of terminal operations like anyMatch, allMatch, and noneMatch to check if elements in a BiStream satisfy a given predicate involving both key and value. ```Java Map phoneBook = ...; BiStream.from(phoneBook) .anyMatch((phoneNumber, address) -> isInvalid(phoneNumber, address)); ... ``` -------------------------------- ### Splitting Strings into Words in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md This Java snippet demonstrates how to split a string into words using `Substring.word().repeatedly()`. It effectively handles various word separators like underscores and hyphens, returning a list of individual words. ```java Substring.word().repeatedly().from("quick_brown-fox").toList(); // => ["quick", "brown", "fox"] ``` -------------------------------- ### Process Streams with Java MoreStreams Utility Source: https://github.com/google/mug/blob/master/README.md Shows how to create a stream from a polling source using 'whileNotNull' and then apply standard stream operations like filter and map, useful for processing elements from queues. ```Java whileNotNull(queue::poll).filter(...).map(...) ``` -------------------------------- ### Java VisitedPage Record for Graph Traversal Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/find_path_in_graph.md Defines a `VisitedPage` record in Java to model web pages during graph traversal. It tracks the current URL and its referrer, provides a static factory method for root pages, an `exploreLinks` method to fetch child links, and a `urlPath` method to reconstruct the full path from the root. The `urlPath` method has a time complexity of O(path length). ```java record VisitedPage(String url, VisitedPage referrer) { static VisitedPage from(String root) { return new VisitedPage(root, null); } /** RPC: explore the links from this page. */ Stream exploreLinks() { return fetchLinks(url).stream() .map(child -> new VisitedPage(child, this)); } /** Reconstruct the url path from the root. This is O(path length). */ List urlPath() { List path = new ArrayList<>(); for (VisitedPage p = this; p != null; p = p.referrer) { path.add(p.url); } Collections.reverse(path); return path; } } ``` -------------------------------- ### Print Reconstructed Path on Phishing Site Discovery Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/find_path_in_graph.md Illustrates how to print the full URL path once a phishing site is discovered. It leverages the `urlPath()` method of the `VisitedPage` object returned by the `Walker` to reconstruct and display the sequence of URLs leading to the phishing domain. ```java result.ifPresent( page -> System.out.println("Found a path: " + page.urlPath())); ``` -------------------------------- ### Add Mug Guava Add-ons Dependency to Maven Project Source: https://github.com/google/mug/blob/master/README.md Provides the Maven XML snippet for including the 'mug-guava' artifact, which contains Guava add-ons and safe SQL utilities like SafeSql, SafeQuery, and GoogleSql. ```XML com.google.mug mug-guava 8.6 ``` -------------------------------- ### SQL Query After Identifier Injection Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This SQL snippet illustrates the final query string that results from the concatenation of the malicious HTTP payload. It clearly shows how the `DROP TABLE` command is appended and would be executed, demonstrating the success of the identifier injection. ```sql SELECT * FROM users ORDER BY name desc; DROP TABLE users -- ``` -------------------------------- ### Add Mug Protobuf Utility Dependency to Maven Project Source: https://github.com/google/mug/blob/master/README.md Provides the Maven XML snippet for including the 'mug-protobuf' artifact as a dependency, useful for Protobuf-related utilities within your project. ```XML com.google.mug mug-protobuf 8.6 ``` -------------------------------- ### Compile-Time Safe Bidirectional Parsing/Formatting with Java StringFormat Source: https://github.com/google/mug/blob/master/README.md Illustrates the use of StringFormat for safe parsing and formatting of strings based on a pattern. It allows extracting structured data from a path string with compile-time safety. ```Java new StringFormat("/home/{user}/{date}").parse(filePath, (user, date) -> ...) ``` -------------------------------- ### Chain Substring operations with Optional safety in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Shows how `Substring` operations can be chained together and integrated with Java's `Optional` to handle potential absence of results gracefully, allowing for transformations like `map` and default values with `orElse`. ```Java Substring.between("/", "/").from("/users/alice/") .map(String::toUpperCase) .orElse("default"); ``` -------------------------------- ### Scan repeated records with StringFormat in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Illustrates using `StringFormat` to scan a string for multiple occurrences of a defined pattern, extracting structured data into a list of results. ```Java List results = new StringFormat("[{title}]({url})") .scan("[One](link1) and [Two](link2)", (title, url) -> title + ":" + url); .toList() // => ["One:link1", "Two:link2"] ``` -------------------------------- ### Stream Map and Pair-wise Collections with Java BiStream Source: https://github.com/google/mug/blob/master/README.md Demonstrates how to use BiStream to zip two collections (keys and values) into a map. BiStream extends Java streams for working with pairs, simplifying operations on key-value data. ```Java BiStream.zip(keys, values).toMap() ``` -------------------------------- ### SafeSql Generated JDBC Parameter for LIKE Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This Java snippet demonstrates how SafeSql prepares the parameter for the `LIKE` clause. It automatically escapes special characters like `%` and `\` in the input string (`%100\%%`), ensuring that the pattern matching behaves as intended without unintended SQL behavior. ```java statement.setObject(1, "%100\\%%") ``` -------------------------------- ### Tokenizing Complex Structures with consecutive() and firstOccurrence() in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md This Java snippet demonstrates how to tokenize complex string structures using `Substring.RepeatingPattern` with `consecutive()` for sequences of digits or alphas, and `first()` for punctuation. It collects these patterns using `firstOccurrence()` to create a repeatable tokenization logic. ```java Substring.RepeatingPattern tokens = Stream.of(consecutive(DIGIT), consecutive(ALPHA), first(PUNCTUATION)) .collect(firstOccurrence()) .repeatedly(); ``` -------------------------------- ### Add Mug Core Dependency to Maven Project Source: https://github.com/google/mug/blob/master/README.md Provides the Maven XML snippet required to add the core Mug library as a dependency to a pom.xml file, enabling its utilities in your project. ```XML com.google.mug mug 8.6 ``` -------------------------------- ### Extract substring between dynamic delimiters with Substring in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Illustrates creating a reusable method to extract content between specified opening and closing delimiters using `Substring.between(...)`. ```Java Optional quotedBy(String open, String close) { return between(open, close).from("call(foo)"); } ``` -------------------------------- ### Mug Walker with Functional Equivalence for Visited URLs Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/find_path_in_graph.md Corrects the `Walker` usage by introducing functional equivalence. It uses a `HashSet` to track visited URLs based solely on the URL string, rather than the entire `VisitedPage` object. This prevents redundant service calls and ensures efficient traversal even when the same page is reached via multiple paths, solving the re-exploration problem. ```java List rootPages = officialCompanyUrls.stream().map(VisitedPage::from).toList(); Set visitedUrls = new HashSet<>(); Optional result = Walker.inGraph(VisitedPage::exploreLinks, page -> visitedUrls.add(page.url())) .breadthFirstFrom(rootPages) // assume we have a small helper to parse the domain from a url .filter(page -> knownPhishingSites.contains(parseDomain(page))) .findFirst(); ``` -------------------------------- ### Declarative Optional Query Construction with SafeSql Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md Shows how SafeSql's optionally() utility enables declarative and type-safe construction of SQL queries with optional clauses. This method prevents injection by guarding the entire SQL query through Java's strong type and SQL template semantic analysis, enhancing readability and refactorability. ```java SafeSql query = SafeSql.of( "SELECT * FROM Users WHERE 1=1 {optionally_and_name}", optionally("AND name LIKE '%{keyword}%'", keyword)); ``` -------------------------------- ### Consuming Paginated APIs with whileNotNull Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md Illustrates how `whileNotNull()` can simplify the consumption of paginated APIs. The supplier fetches a page, updates an external token for the next page, and returns `null` when the page is empty, effectively replacing `do/while` loops. ```Java Stream pages = whileNotNull(() -> { Page page = fetch(token); token = page.nextToken(); // update external state return page.isEmpty() ? null : page; }); ``` -------------------------------- ### Further Grouping with BiStream and BiCollectors Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This snippet illustrates advanced data extraction from a BiStream, demonstrating how to perform further grouping operations and collect the results into nested immutable maps using `BiCollectors.groupingBy`. ```java Multimap phoneBook = ...; ImmutableMap> stateAreaCodes = BiStream.from(phoneBook) .mapValues(PhoneNumber::areaCode) .collect(BiCollectors.groupingBy(Address::state, toImmutableSet())) .collect(toImmutableMap()); ``` -------------------------------- ### Parsing Timestamp to Instant with DateTimeFormats Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This snippet demonstrates how to use the `parseToInstant` method from `DateTimeFormats` to convert a timestamp string into an `Instant` object. While slower due to formatter inference, it's convenient for performance-insensitive code such as tests. ```java Instant timestamp = DateTimeFormats.parseToInstant(timestampString); ``` -------------------------------- ### WebPageUrlService Interface Definition Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/graph/find_path_in_graph.md Defines a service interface for fetching URLs linked from a given web page. This service is a core dependency for the graph traversal logic, providing the means to explore the web graph. ```APIDOC List fetchPageUrls(String url); ``` -------------------------------- ### Extract file extension with Substring in Java Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/README.md Demonstrates using the `Substring` API to safely extract the portion of a string after the last occurrence of a character, such as a file extension. ```Java after(last('.')).from("report.csv").orElse(""); // => "csv" ``` -------------------------------- ### Java Code Calling Vulnerable MyBatis Query Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This Java code snippet shows how parameters are passed to the vulnerable MyBatis `listUsers` query. The `sortField` parameter, if user-controlled, will be unsafely injected into the SQL via the `${}` placeholder in the XML. ```java Map params = Map.of("name", name, "sortField", sort); List users = sqlSession.selectList("listUsers", params); ``` -------------------------------- ### Conditional SQL Logic in MyBatis XML Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md Illustrates how MyBatis handles conditional SQL using XML-based tags. While #{} safely binds values, the conditional logic is entangled with markup, making it less composable and harder to abstract or reuse subqueries without duplication. ```xml ``` -------------------------------- ### Configure Mug Error Prone Annotation Processor in Maven Source: https://github.com/google/mug/blob/master/README.md Shows the Maven XML configuration for adding 'mug-errorprone' to the annotationProcessorPaths within the maven-compiler-plugin build section, enabling error-prone checks. ```XML maven-compiler-plugin com.google.errorprone error_prone_core 2.23.0 com.google.mug mug-errorprone 8.6 ``` -------------------------------- ### Concatenating BiStreams from Multiple Sources Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This snippet illustrates how to combine multiple BiStream instances or streams of maps/multimaps into a single BiStream using concatenation, useful for merging data from various sources. ```java // a handful of Maps Map cached = ...; Map onDemand = ...; Map all = BiStream.concat(cached, onDemand).toMap(); // a stream of maps BiStream biStream = maps.stream() .collect(concatenating(BiStream::from)); // a stream of multimaps BiStream biStream = multimaps.stream() .collect(concatenating(multimap -> BiStream.from(multimap.entries())); ``` -------------------------------- ### Collecting BiStream to Guava ImmutableSetMultimap Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This snippet shows how to collect a BiStream into a Guava ImmutableSetMultimap, similar to ImmutableMap, by using the appropriate method reference as a BiCollector. ```java ImmutableSetMultimap all = BiStream.concat(cached, onDemand) .collect(ImmutableSetMultimap::toImmutableSetMultimap); ``` -------------------------------- ### Standard Java Infinite Stream Generation Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md The standard Java library provides methods to generate streams, but they are inherently infinite, requiring external control logic for termination. ```Java Stream.generate(() -> ...) Stream.iterate(seed, unaryOperator) ``` -------------------------------- ### Conceptual BiCollectors Utility for Guava-specific Collectors Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/README.md This conceptual snippet illustrates how a utility class like `BiCollectors` could provide static-import friendly `BiCollector` methods for Guava types, enhancing discoverability and compiler inference. ```java class BiCollectors { public static BiCollector toImmutableMap() { return ImmutableMap::toImmutableMap; } } ``` -------------------------------- ### Vulnerable MyBatis XML for Dynamic Sorting Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This MyBatis XML configuration demonstrates a common anti-pattern using `${sortField}`. Unlike `#{name}` which safely binds values, `${}` directly injects the user-provided `sortField` value without escaping, making the query vulnerable to identifier injection. ```xml ``` -------------------------------- ### `whileNotNull(Supplier)` Method Signature Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md This utility method repeatedly calls the provided supplier until it returns `null`, collecting all non-null results into a lazy `Stream`. It provides a single construct for generation and termination. ```Java Stream whileNotNull(Supplier next) ``` -------------------------------- ### Find Elements in Sorted Arrays with Java BinarySearch Source: https://github.com/google/mug/blob/master/README.md Demonstrates using BinarySearch to find a target value within a sorted double array with a specified tolerance. This is useful for numerical searches where exact matches may not be possible. ```Java BinarySearch.inSortedArrayWithTolerance(doubleArray, 0.0001).find(target) ``` -------------------------------- ### Unsafe Dynamic SQL Construction in Spring/JDBC Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md Demonstrates a common pattern in Spring or JDBC where dynamic SQL is built using string concatenation. This approach can lead to SQL injection vulnerabilities, even with parameter binding, as the conditional clause itself is dynamically generated and user-influenced. ```java String sql = "SELECT * FROM users WHERE 1=1"; if (keyword != null) { sql += " AND name LIKE '%" + keyword + "%'"; } ``` -------------------------------- ### Formatting with DateTimeFormats for Custom Date Time with Timezone Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/time/README.md This snippet shows `DateTimeFormats.formatOf()` inferring a formatter for a custom date and time string including a timezone abbreviation, equivalent to `ofPattern("yyyy-MM-dd HH:mm:ss zzz")`. It demonstrates the library's capability to handle various timezone representations. ```java // Equivalent to ofPattern("yyyy-MM-dd HH:mm:ss zzz") private static final DateTimeFormatter FORMATTER = formatOf( "2023-10-30 11:05:30 PST"); ``` -------------------------------- ### Reading Lines from BufferedReader with whileNotNull Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md Demonstrates using `whileNotNull()` to read lines from a `BufferedReader` until the `readLine()` method returns `null`, indicating the end of the stream. This is similar to `reader.lines()` but works with any API using `null` for EOF. ```Java Stream lines = whileNotNull(reader::readLine); ``` -------------------------------- ### Vulnerable Java SQL Query Construction Source: https://github.com/google/mug/blob/master/mug-guava/src/main/java/com/google/mu/safesql/README.md This Java snippet demonstrates a common mistake where user-controlled input (`orderBy`) is directly concatenated into an `ORDER BY` clause. While `PreparedStatement` protects values, it does not protect SQL structure, making this vulnerable to identifier injection. ```java String orderBy = request.getParameter("sort"); String sql = "SELECT * FROM users ORDER BY " + orderBy; ``` -------------------------------- ### Terminating a Java Stream with takeWhile Source: https://github.com/google/mug/blob/master/mug/src/main/java/com/google/mu/util/stream/white_not_null.md A common pattern to terminate an infinite stream when a supplier returns `null` involves using `Stream.generate()` combined with `takeWhile(Objects::nonNull)`. This approach, however, splits the termination logic and evaluates one extra element. ```Java Stream.generate(supplier) .takeWhile(Objects::nonNull) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.