repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
google/mug
mug/src/main/java/com/google/mu/util/stream/Cases.java
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // }
import java.util.stream.Collector; import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.toList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * Collectors for short streams with 0, 1 or 2 elements using a {@link Supplier}, {@link Function} * or {@link BiFunction} respectively. * * <p>For example, if the input collection must have only 2 elements: * * <pre>{@code * Foo result = input.stream().collect(onlyElements((a, b) -> ...)); * }</pre> * * <p>Or, if the input may or may not have two elements: * * <pre>{@code * Optional<Foo> result = input.stream().collect(when((a, b) -> ...)); * }</pre> * * <p>Or, if the input could have zero, one or two elements: * * <pre>{@code * Foo result = input.stream().collect( * cases( * when(() -> ...), * when(a -> ...), * when((a, b) -> ...))); * }</pre> * * @since 3.6 * @deprecated Use {@link com.google.mu.util.MoreCollections#findFirstElements findFirstElements()} * and/or {@link com.google.mu.util.MoreCollections#findOnlyElements findOnlyElements()} methods * together with {@link Optional#or} instead. */ @Deprecated public final class Cases { /** * A collector that collects the only element from the input, * or else throws {@link IllegalArgumentException}. */ public static <T> Collector<T, ?, T> onlyElement() {
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java import java.util.stream.Collector; import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.toList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * Collectors for short streams with 0, 1 or 2 elements using a {@link Supplier}, {@link Function} * or {@link BiFunction} respectively. * * <p>For example, if the input collection must have only 2 elements: * * <pre>{@code * Foo result = input.stream().collect(onlyElements((a, b) -> ...)); * }</pre> * * <p>Or, if the input may or may not have two elements: * * <pre>{@code * Optional<Foo> result = input.stream().collect(when((a, b) -> ...)); * }</pre> * * <p>Or, if the input could have zero, one or two elements: * * <pre>{@code * Foo result = input.stream().collect( * cases( * when(() -> ...), * when(a -> ...), * when((a, b) -> ...))); * }</pre> * * @since 3.6 * @deprecated Use {@link com.google.mu.util.MoreCollections#findFirstElements findFirstElements()} * and/or {@link com.google.mu.util.MoreCollections#findOnlyElements findOnlyElements()} methods * together with {@link Optional#or} instead. */ @Deprecated public final class Cases { /** * A collector that collects the only element from the input, * or else throws {@link IllegalArgumentException}. */ public static <T> Collector<T, ?, T> onlyElement() {
return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne);
google/mug
mug-algorithms/src/test/java/com/google/mu/algorithms/FibonacciTest.java
// Path: mug-algorithms/src/main/java/com/google/mu/algorithms/Fibonacci.java // public static Stream<Long> fibonacci() { // return new Fibonacci().from(0L, 1L).iterate(); // }
import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.algorithms.Fibonacci.fibonacci; import org.junit.Test;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.algorithms; public class FibonacciTest { @Test public void fibonacciStream() {
// Path: mug-algorithms/src/main/java/com/google/mu/algorithms/Fibonacci.java // public static Stream<Long> fibonacci() { // return new Fibonacci().from(0L, 1L).iterate(); // } // Path: mug-algorithms/src/test/java/com/google/mu/algorithms/FibonacciTest.java import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.algorithms.Fibonacci.fibonacci; import org.junit.Test; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.algorithms; public class FibonacciTest { @Test public void fibonacciStream() {
assertThat(fibonacci().limit(7))
google/mug
mug/src/test/java/com/google/mu/util/concurrent/ParallelizerTest.java
// Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static <T> Stream<Runnable> forAll(Stream<? extends T> inputs, Consumer<? super T> consumer) { // requireNonNull(consumer); // return inputs.map(input -> () -> consumer.accept(input)); // } // // Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static class UncheckedExecutionException extends RuntimeException { // UncheckedExecutionException(Throwable cause) { // super(cause); // } // private static final long serialVersionUID = 1L; // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.concurrent.Parallelizer.forAll; import static java.util.Arrays.asList; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Verifier; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.google.common.truth.IterableSubject; import com.google.common.util.concurrent.MoreExecutors; import com.google.mu.util.concurrent.Parallelizer.UncheckedExecutionException;
} @Test public void testOneInFlight() throws Exception { maxInFlight = 1; List<Integer> numbers = asList(1, 2, 3, 4, 5, 6, 7, 8, 9); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testFastTasks() throws Exception { List<Integer> numbers = asList(1, 2, 3, 4, 5, 6, 7, 8, 9); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testSlowTasks() throws Exception { List<Integer> numbers = asList(1, 2, 3, 4, 5); parallelize(numbers.stream(), delayed(Duration.ofMillis(2), this::translateToString)); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testLargeMaxInFlight() throws Exception { maxInFlight = Integer.MAX_VALUE; List<Integer> numbers = asList(1, 2, 3); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testTaskExceptionDismissesPendingTasks() { maxInFlight = 2;
// Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static <T> Stream<Runnable> forAll(Stream<? extends T> inputs, Consumer<? super T> consumer) { // requireNonNull(consumer); // return inputs.map(input -> () -> consumer.accept(input)); // } // // Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static class UncheckedExecutionException extends RuntimeException { // UncheckedExecutionException(Throwable cause) { // super(cause); // } // private static final long serialVersionUID = 1L; // } // Path: mug/src/test/java/com/google/mu/util/concurrent/ParallelizerTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.concurrent.Parallelizer.forAll; import static java.util.Arrays.asList; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Verifier; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.google.common.truth.IterableSubject; import com.google.common.util.concurrent.MoreExecutors; import com.google.mu.util.concurrent.Parallelizer.UncheckedExecutionException; } @Test public void testOneInFlight() throws Exception { maxInFlight = 1; List<Integer> numbers = asList(1, 2, 3, 4, 5, 6, 7, 8, 9); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testFastTasks() throws Exception { List<Integer> numbers = asList(1, 2, 3, 4, 5, 6, 7, 8, 9); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testSlowTasks() throws Exception { List<Integer> numbers = asList(1, 2, 3, 4, 5); parallelize(numbers.stream(), delayed(Duration.ofMillis(2), this::translateToString)); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testLargeMaxInFlight() throws Exception { maxInFlight = Integer.MAX_VALUE; List<Integer> numbers = asList(1, 2, 3); parallelize(numbers.stream(), this::translateToString); assertThat(translated).containsExactlyEntriesIn(mapToString(numbers)); } @Test public void testTaskExceptionDismissesPendingTasks() { maxInFlight = 2;
UncheckedExecutionException exception = assertThrows(
google/mug
mug/src/test/java/com/google/mu/util/concurrent/ParallelizerTest.java
// Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static <T> Stream<Runnable> forAll(Stream<? extends T> inputs, Consumer<? super T> consumer) { // requireNonNull(consumer); // return inputs.map(input -> () -> consumer.accept(input)); // } // // Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static class UncheckedExecutionException extends RuntimeException { // UncheckedExecutionException(Throwable cause) { // super(cause); // } // private static final long serialVersionUID = 1L; // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.concurrent.Parallelizer.forAll; import static java.util.Arrays.asList; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Verifier; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.google.common.truth.IterableSubject; import com.google.common.util.concurrent.MoreExecutors; import com.google.mu.util.concurrent.Parallelizer.UncheckedExecutionException;
UncheckedExecutionException.class, () -> parallelize(Stream.of(() -> raise(exception)))); assertThat(caught.getCause()).isSameAs(exception); } private void translateToString(int i) { translated.put(i, Integer.toString(i)); } private static <K> Map<K, String> mapToString(Collection<K> keys) { return keys.stream().collect(Collectors.toMap(k -> k, Object::toString)); } /** Keeps track of active threads and makes sure it doesn't exceed {@link #maxInFlight}. */ private void runTask(Runnable task) { try { try { assertThat(activeThreads.incrementAndGet()).isAtMost(maxInFlight); } catch (Throwable e) { thrown.add(e); return; } task.run(); } finally { activeThreads.decrementAndGet(); } } private <T> void parallelize(Stream<? extends T> inputs, Consumer<? super T> consumer) throws InterruptedException, TimeoutException {
// Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static <T> Stream<Runnable> forAll(Stream<? extends T> inputs, Consumer<? super T> consumer) { // requireNonNull(consumer); // return inputs.map(input -> () -> consumer.accept(input)); // } // // Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java // static class UncheckedExecutionException extends RuntimeException { // UncheckedExecutionException(Throwable cause) { // super(cause); // } // private static final long serialVersionUID = 1L; // } // Path: mug/src/test/java/com/google/mu/util/concurrent/ParallelizerTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.concurrent.Parallelizer.forAll; import static java.util.Arrays.asList; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Verifier; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.google.common.truth.IterableSubject; import com.google.common.util.concurrent.MoreExecutors; import com.google.mu.util.concurrent.Parallelizer.UncheckedExecutionException; UncheckedExecutionException.class, () -> parallelize(Stream.of(() -> raise(exception)))); assertThat(caught.getCause()).isSameAs(exception); } private void translateToString(int i) { translated.put(i, Integer.toString(i)); } private static <K> Map<K, String> mapToString(Collection<K> keys) { return keys.stream().collect(Collectors.toMap(k -> k, Object::toString)); } /** Keeps track of active threads and makes sure it doesn't exceed {@link #maxInFlight}. */ private void runTask(Runnable task) { try { try { assertThat(activeThreads.incrementAndGet()).isAtMost(maxInFlight); } catch (Throwable e) { thrown.add(e); return; } task.run(); } finally { activeThreads.decrementAndGet(); } } private <T> void parallelize(Stream<? extends T> inputs, Consumer<? super T> consumer) throws InterruptedException, TimeoutException {
parallelize(forAll(inputs, consumer));
google/mug
mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Iterable<T> iterateOnce(Stream<T> stream) { // return stream::iterator; // }
import static com.google.mu.util.stream.MoreStreams.iterateOnce; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.Iterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; import java.util.stream.StreamSupport;
* @throws InterruptedException if the thread is interrupted while waiting. * @throws TimeoutException if timeout exceeded while waiting. */ public void parallelize( Stream<? extends Runnable> tasks, Duration heartbeatTimeout) throws TimeoutException, InterruptedException { parallelize(tasks, heartbeatTimeout.toMillis(), TimeUnit.MILLISECONDS); } /** * Runs {@code tasks} in parallel and blocks uninterruptibly until either all tasks have finished, * timeout is triggered, or any exception is thrown upon which all pending tasks are canceled * (but the method returns without waiting for the tasks to respond to cancellation). * * <p>The {@code tasks} stream is consumed only in the calling thread in iteration order. * * @param tasks the tasks to be parallelized * @param heartbeatTimeout at least one task needs to complete every {@code heartbeatTimeout}. * @param timeUnit the unit of {@code heartbeatTimeout} * @throws InterruptedException if the thread is interrupted while waiting. * @throws TimeoutException if timeout exceeded while waiting. */ public void parallelize( Stream<? extends Runnable> tasks, long heartbeatTimeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException { requireNonNull(tasks); requireNonNull(timeUnit); if (heartbeatTimeout <= 0) throw new IllegalArgumentException("timeout = " + heartbeatTimeout); Flight flight = new Flight(); try {
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Iterable<T> iterateOnce(Stream<T> stream) { // return stream::iterator; // } // Path: mug/src/main/java/com/google/mu/util/concurrent/Parallelizer.java import static com.google.mu.util.stream.MoreStreams.iterateOnce; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.Iterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; import java.util.stream.StreamSupport; * @throws InterruptedException if the thread is interrupted while waiting. * @throws TimeoutException if timeout exceeded while waiting. */ public void parallelize( Stream<? extends Runnable> tasks, Duration heartbeatTimeout) throws TimeoutException, InterruptedException { parallelize(tasks, heartbeatTimeout.toMillis(), TimeUnit.MILLISECONDS); } /** * Runs {@code tasks} in parallel and blocks uninterruptibly until either all tasks have finished, * timeout is triggered, or any exception is thrown upon which all pending tasks are canceled * (but the method returns without waiting for the tasks to respond to cancellation). * * <p>The {@code tasks} stream is consumed only in the calling thread in iteration order. * * @param tasks the tasks to be parallelized * @param heartbeatTimeout at least one task needs to complete every {@code heartbeatTimeout}. * @param timeUnit the unit of {@code heartbeatTimeout} * @throws InterruptedException if the thread is interrupted while waiting. * @throws TimeoutException if timeout exceeded while waiting. */ public void parallelize( Stream<? extends Runnable> tasks, long heartbeatTimeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException { requireNonNull(tasks); requireNonNull(timeUnit); if (heartbeatTimeout <= 0) throw new IllegalArgumentException("timeout = " + heartbeatTimeout); Flight flight = new Flight(); try {
for (Runnable task : iterateOnce(tasks)) {
google/mug
mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreStructs.java
// Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java // static Value valueOf(double n) { // return Value.newBuilder().setNumberValue(n).build(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/BiCollector.java // @FunctionalInterface // public interface BiCollector<K, V, R> { // /** // * Returns a {@code Collector} that will first split the input elements using {@code toKey} and // * {@code toValue} and subsequently collect the bisected parts through this {@code BiCollector}. // * // * @param toKey // * The function to read the key from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param toValue // * The function to read the value from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param <E> used to abstract away the underlying pair/entry type used by {@link BiStream}. // */ // // Deliberately avoid wildcards for toKey and toValue, because we don't expect // // users to call this method. Instead, users will typically provide method references matching // // this signature. // // Signatures with or without wildcards should both match. // // In other words, this signature optimizes flexibility for implementors, not callers. // <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue); // }
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.mu.protobuf.util.MoreValues.valueOf; import java.util.Map; import java.util.function.Function; import java.util.stream.Collector; import com.google.common.collect.Maps; import com.google.errorprone.annotations.CheckReturnValue; import com.google.mu.util.stream.BiCollector; import com.google.protobuf.ListValue; import com.google.protobuf.Struct; import com.google.protobuf.StructOrBuilder; import com.google.protobuf.Value;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.protobuf.util; /** * Additional utilities to help create {@link Struct} messages. * * <p>The {@code struct(name, value)} helpers can be used to create {@code Struct} conveniently, * for example: {@code struct("age", 10)}. * * <p>To build {@code Struct} with more than one fields, use {@link StructBuilder}; or use * {@link #toStruct()} to collect from a {@code BiStream}. * * <p>If you have complex nested data structures such as {@code Multimap<String, Optional<Integer>>}, * consider to use {@link Structor}, which translates POJO to Struct for common primitive types and * collection types. * * @since 5.8 */ @CheckReturnValue public final class MoreStructs { /** * Returns a Struct with {@code name} and {@code value}. * * @throws NullPointerException if {@code name} is null */ public static Struct struct(String name, boolean value) {
// Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java // static Value valueOf(double n) { // return Value.newBuilder().setNumberValue(n).build(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/BiCollector.java // @FunctionalInterface // public interface BiCollector<K, V, R> { // /** // * Returns a {@code Collector} that will first split the input elements using {@code toKey} and // * {@code toValue} and subsequently collect the bisected parts through this {@code BiCollector}. // * // * @param toKey // * The function to read the key from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param toValue // * The function to read the value from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param <E> used to abstract away the underlying pair/entry type used by {@link BiStream}. // */ // // Deliberately avoid wildcards for toKey and toValue, because we don't expect // // users to call this method. Instead, users will typically provide method references matching // // this signature. // // Signatures with or without wildcards should both match. // // In other words, this signature optimizes flexibility for implementors, not callers. // <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue); // } // Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreStructs.java import static com.google.common.base.Preconditions.checkNotNull; import static com.google.mu.protobuf.util.MoreValues.valueOf; import java.util.Map; import java.util.function.Function; import java.util.stream.Collector; import com.google.common.collect.Maps; import com.google.errorprone.annotations.CheckReturnValue; import com.google.mu.util.stream.BiCollector; import com.google.protobuf.ListValue; import com.google.protobuf.Struct; import com.google.protobuf.StructOrBuilder; import com.google.protobuf.Value; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.protobuf.util; /** * Additional utilities to help create {@link Struct} messages. * * <p>The {@code struct(name, value)} helpers can be used to create {@code Struct} conveniently, * for example: {@code struct("age", 10)}. * * <p>To build {@code Struct} with more than one fields, use {@link StructBuilder}; or use * {@link #toStruct()} to collect from a {@code BiStream}. * * <p>If you have complex nested data structures such as {@code Multimap<String, Optional<Integer>>}, * consider to use {@link Structor}, which translates POJO to Struct for common primitive types and * collection types. * * @since 5.8 */ @CheckReturnValue public final class MoreStructs { /** * Returns a Struct with {@code name} and {@code value}. * * @throws NullPointerException if {@code name} is null */ public static Struct struct(String name, boolean value) {
return struct(name, valueOf(value));
google/mug
mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreStructs.java
// Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java // static Value valueOf(double n) { // return Value.newBuilder().setNumberValue(n).build(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/BiCollector.java // @FunctionalInterface // public interface BiCollector<K, V, R> { // /** // * Returns a {@code Collector} that will first split the input elements using {@code toKey} and // * {@code toValue} and subsequently collect the bisected parts through this {@code BiCollector}. // * // * @param toKey // * The function to read the key from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param toValue // * The function to read the value from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param <E> used to abstract away the underlying pair/entry type used by {@link BiStream}. // */ // // Deliberately avoid wildcards for toKey and toValue, because we don't expect // // users to call this method. Instead, users will typically provide method references matching // // this signature. // // Signatures with or without wildcards should both match. // // In other words, this signature optimizes flexibility for implementors, not callers. // <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue); // }
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.mu.protobuf.util.MoreValues.valueOf; import java.util.Map; import java.util.function.Function; import java.util.stream.Collector; import com.google.common.collect.Maps; import com.google.errorprone.annotations.CheckReturnValue; import com.google.mu.util.stream.BiCollector; import com.google.protobuf.ListValue; import com.google.protobuf.Struct; import com.google.protobuf.StructOrBuilder; import com.google.protobuf.Value;
* Returns a Struct with {@code name} and {@code value}. * * @throws NullPointerException if {@code name} or {@code value} is null */ public static Struct struct(String name, ListValue value) { return struct(name, valueOf(value)); } /** * Returns a {@link Collector} that collects input key-value pairs into {@link Struct}. * * <p>Duplicate keys (according to {@link CharSequence#toString()}) are not allowed. */ public static <T> Collector<T, ?, Struct> toStruct( Function<? super T, ? extends CharSequence> keyFunction, Function<? super T, Value> valueFunction) { checkNotNull(keyFunction); checkNotNull(valueFunction); return Collector.of( StructBuilder::new, (builder, input) -> builder.add(keyFunction.apply(input).toString(), valueFunction.apply(input)), StructBuilder::addAllFields, StructBuilder::build); } /** * Returns a {@link BiCollector} that collects the input key-value pairs into {@link Struct}. * * <p>Duplicate keys (according to {@link CharSequence#toString()}) are not allowed. */
// Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreValues.java // static Value valueOf(double n) { // return Value.newBuilder().setNumberValue(n).build(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/BiCollector.java // @FunctionalInterface // public interface BiCollector<K, V, R> { // /** // * Returns a {@code Collector} that will first split the input elements using {@code toKey} and // * {@code toValue} and subsequently collect the bisected parts through this {@code BiCollector}. // * // * @param toKey // * The function to read the key from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param toValue // * The function to read the value from the input entry. // * May be applied on the same input entry multiple times. // * Because input entries could be ephemeral like {@link java.util.Map.Entry}, // * applying the function on a previous input entry has undefined result. // * @param <E> used to abstract away the underlying pair/entry type used by {@link BiStream}. // */ // // Deliberately avoid wildcards for toKey and toValue, because we don't expect // // users to call this method. Instead, users will typically provide method references matching // // this signature. // // Signatures with or without wildcards should both match. // // In other words, this signature optimizes flexibility for implementors, not callers. // <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue); // } // Path: mug-protobuf/src/main/java/com/google/mu/protobuf/util/MoreStructs.java import static com.google.common.base.Preconditions.checkNotNull; import static com.google.mu.protobuf.util.MoreValues.valueOf; import java.util.Map; import java.util.function.Function; import java.util.stream.Collector; import com.google.common.collect.Maps; import com.google.errorprone.annotations.CheckReturnValue; import com.google.mu.util.stream.BiCollector; import com.google.protobuf.ListValue; import com.google.protobuf.Struct; import com.google.protobuf.StructOrBuilder; import com.google.protobuf.Value; * Returns a Struct with {@code name} and {@code value}. * * @throws NullPointerException if {@code name} or {@code value} is null */ public static Struct struct(String name, ListValue value) { return struct(name, valueOf(value)); } /** * Returns a {@link Collector} that collects input key-value pairs into {@link Struct}. * * <p>Duplicate keys (according to {@link CharSequence#toString()}) are not allowed. */ public static <T> Collector<T, ?, Struct> toStruct( Function<? super T, ? extends CharSequence> keyFunction, Function<? super T, Value> valueFunction) { checkNotNull(keyFunction); checkNotNull(valueFunction); return Collector.of( StructBuilder::new, (builder, input) -> builder.add(keyFunction.apply(input).toString(), valueFunction.apply(input)), StructBuilder::addAllFields, StructBuilder::build); } /** * Returns a {@link BiCollector} that collects the input key-value pairs into {@link Struct}. * * <p>Duplicate keys (according to {@link CharSequence#toString()}) are not allowed. */
public static BiCollector<CharSequence, Value, Struct> toStruct() {
google/mug
mug/src/main/java/com/google/mu/util/MoreCollections.java
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // }
import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary;
package com.google.mu.util; /** * Utilities pertaining to {@link Collection}. * * @since 5.3 */ public final class MoreCollections { /** * If {@code collection} has at least two elements, passes the first two elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 2) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next())); } /** * If {@code collection} has at least 3 elements, passes the first 3 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // } // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary; package com.google.mu.util; /** * Utilities pertaining to {@link Collection}. * * @since 5.3 */ public final class MoreCollections { /** * If {@code collection} has at least two elements, passes the first two elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 2) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next())); } /** * If {@code collection} has at least 3 elements, passes the first 3 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
Collection<T> collection, Ternary<? super T, ? extends R> found) {
google/mug
mug/src/main/java/com/google/mu/util/MoreCollections.java
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // }
import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary;
package com.google.mu.util; /** * Utilities pertaining to {@link Collection}. * * @since 5.3 */ public final class MoreCollections { /** * If {@code collection} has at least two elements, passes the first two elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 2) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next())); } /** * If {@code collection} has at least 3 elements, passes the first 3 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Ternary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 3) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 4 elements, passes the first 4 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // } // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary; package com.google.mu.util; /** * Utilities pertaining to {@link Collection}. * * @since 5.3 */ public final class MoreCollections { /** * If {@code collection} has at least two elements, passes the first two elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 2) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next())); } /** * If {@code collection} has at least 3 elements, passes the first 3 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Ternary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 3) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 4 elements, passes the first 4 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
Collection<T> collection, Quarternary<? super T, ? extends R> found) {
google/mug
mug/src/main/java/com/google/mu/util/MoreCollections.java
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // }
import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary;
/** * If {@code collection} has at least 4 elements, passes the first 4 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Quarternary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 4) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2), list.get(3))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 5 elements, passes the first 5 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // } // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary; /** * If {@code collection} has at least 4 elements, passes the first 4 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Quarternary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 4) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2), list.get(3))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 5 elements, passes the first 5 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
Collection<T> collection, Quinary<? super T, ? extends R> found) {
google/mug
mug/src/main/java/com/google/mu/util/MoreCollections.java
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // }
import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary;
/** * If {@code collection} has at least 5 elements, passes the first 5 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Quinary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 5) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 6 elements, passes the first 6 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
// Path: mug/src/main/java/com/google/mu/function/Quarternary.java // public interface Quarternary<T, R> { // R apply(T a, T b, T c, T d); // } // // Path: mug/src/main/java/com/google/mu/function/Quinary.java // public interface Quinary<T, R> { // R apply(T a, T b, T c, T d, T e); // } // // Path: mug/src/main/java/com/google/mu/function/Senary.java // public interface Senary<T, R> { // R apply(T a, T b, T c, T d, T e, T f); // } // // Path: mug/src/main/java/com/google/mu/function/Ternary.java // @FunctionalInterface // public interface Ternary<T, R> { // R apply(T a, T b, T c); // } // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.RandomAccess; import java.util.function.BiFunction; import com.google.mu.function.Quarternary; import com.google.mu.function.Quinary; import com.google.mu.function.Senary; import com.google.mu.function.Ternary; /** * If {@code collection} has at least 5 elements, passes the first 5 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements( Collection<T> collection, Quinary<? super T, ? extends R> found) { requireNonNull(found); if (collection.size() < 5) return Optional.empty(); if (collection instanceof List && collection instanceof RandomAccess) { List<T> list = (List<T>) collection; return Optional.of(found.apply(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4))); } Iterator<T> it = collection.iterator(); return Optional.of(found.apply(it.next(), it.next(), it.next(), it.next(), it.next())); } /** * If {@code collection} has at least 6 elements, passes the first 6 elements to {@code found} function * and returns the non-null result wrapped in an {@link Optional}, or else returns {@code * Optional.empty()}. * * @throws NullPointerException if {@code collection} or {@code found} function is null, or if * {@code found} function returns null. */ public static <T, R> Optional<R> findFirstElements(
Collection<T> collection, Senary<? super T, ? extends R> found) {
google/mug
mug/src/main/java/com/google/mu/util/Maybe.java
// Path: mug/src/main/java/com/google/mu/function/CheckedBiFunction.java // @FunctionalInterface // public interface CheckedBiFunction<A, B, T, E extends Throwable> { // T apply(A a, B b) throws E; // // /** // * Returns a new {@code CheckedBiFunction} that maps the return value using {@code mapper}. // * For example: {@code ((a, b) -> a + b).andThen(Object::toString).apply(1, 2) => "3"}. // */ // default <R> CheckedBiFunction<A, B, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return (a, b) -> mapper.apply(apply(a, b)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedConsumer.java // @FunctionalInterface // public interface CheckedConsumer<T, E extends Throwable> { // void accept(T input) throws E; // // /** // * Returns a new {@code CheckedConsumer} that also passes the input to {@code that}. // * For example: {@code out::writeObject.andThen(logger::info).accept("message")}. // */ // default CheckedConsumer<T, E> andThen(CheckedConsumer<? super T, E> that) { // requireNonNull(that); // return input -> { // accept(input); // that.accept(input); // }; // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // }
import com.google.mu.function.CheckedConsumer; import com.google.mu.function.CheckedFunction; import com.google.mu.function.CheckedSupplier; import static java.util.Objects.requireNonNull; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import com.google.mu.function.CheckedBiFunction;
* {@code Stream}. This is specially useful in a {@link Stream} chain to handle and then ignore * exceptional results. */ public final <X extends Throwable> Stream<T> catching( CheckedConsumer<? super E, ? extends X> handler) throws X { requireNonNull(handler); return map(Stream::of).orElse(e -> { handler.accept(e); return Stream.empty(); }); } /** * Turns {@code condition} to a {@code Predicate} over {@code Maybe}. The returned predicate * matches any {@code Maybe} with a matching value, as well as any exceptional {@code Maybe} so * as not to accidentally swallow exceptions. */ public static <T, E extends Throwable> Predicate<Maybe<T, E>> byValue( Predicate<? super T> condition) { requireNonNull(condition); return maybe -> maybe.map(condition::test).orElse(e -> true); } /** * Invokes {@code supplier} and wraps the returned object or thrown exception in a * {@code Maybe<T, E>}. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <T, E extends Throwable> Maybe<T, E> maybe(
// Path: mug/src/main/java/com/google/mu/function/CheckedBiFunction.java // @FunctionalInterface // public interface CheckedBiFunction<A, B, T, E extends Throwable> { // T apply(A a, B b) throws E; // // /** // * Returns a new {@code CheckedBiFunction} that maps the return value using {@code mapper}. // * For example: {@code ((a, b) -> a + b).andThen(Object::toString).apply(1, 2) => "3"}. // */ // default <R> CheckedBiFunction<A, B, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return (a, b) -> mapper.apply(apply(a, b)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedConsumer.java // @FunctionalInterface // public interface CheckedConsumer<T, E extends Throwable> { // void accept(T input) throws E; // // /** // * Returns a new {@code CheckedConsumer} that also passes the input to {@code that}. // * For example: {@code out::writeObject.andThen(logger::info).accept("message")}. // */ // default CheckedConsumer<T, E> andThen(CheckedConsumer<? super T, E> that) { // requireNonNull(that); // return input -> { // accept(input); // that.accept(input); // }; // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // } // Path: mug/src/main/java/com/google/mu/util/Maybe.java import com.google.mu.function.CheckedConsumer; import com.google.mu.function.CheckedFunction; import com.google.mu.function.CheckedSupplier; import static java.util.Objects.requireNonNull; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import com.google.mu.function.CheckedBiFunction; * {@code Stream}. This is specially useful in a {@link Stream} chain to handle and then ignore * exceptional results. */ public final <X extends Throwable> Stream<T> catching( CheckedConsumer<? super E, ? extends X> handler) throws X { requireNonNull(handler); return map(Stream::of).orElse(e -> { handler.accept(e); return Stream.empty(); }); } /** * Turns {@code condition} to a {@code Predicate} over {@code Maybe}. The returned predicate * matches any {@code Maybe} with a matching value, as well as any exceptional {@code Maybe} so * as not to accidentally swallow exceptions. */ public static <T, E extends Throwable> Predicate<Maybe<T, E>> byValue( Predicate<? super T> condition) { requireNonNull(condition); return maybe -> maybe.map(condition::test).orElse(e -> true); } /** * Invokes {@code supplier} and wraps the returned object or thrown exception in a * {@code Maybe<T, E>}. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <T, E extends Throwable> Maybe<T, E> maybe(
CheckedSupplier<? extends T, ? extends E> supplier) {
google/mug
mug/src/main/java/com/google/mu/util/Maybe.java
// Path: mug/src/main/java/com/google/mu/function/CheckedBiFunction.java // @FunctionalInterface // public interface CheckedBiFunction<A, B, T, E extends Throwable> { // T apply(A a, B b) throws E; // // /** // * Returns a new {@code CheckedBiFunction} that maps the return value using {@code mapper}. // * For example: {@code ((a, b) -> a + b).andThen(Object::toString).apply(1, 2) => "3"}. // */ // default <R> CheckedBiFunction<A, B, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return (a, b) -> mapper.apply(apply(a, b)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedConsumer.java // @FunctionalInterface // public interface CheckedConsumer<T, E extends Throwable> { // void accept(T input) throws E; // // /** // * Returns a new {@code CheckedConsumer} that also passes the input to {@code that}. // * For example: {@code out::writeObject.andThen(logger::info).accept("message")}. // */ // default CheckedConsumer<T, E> andThen(CheckedConsumer<? super T, E> that) { // requireNonNull(that); // return input -> { // accept(input); // that.accept(input); // }; // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // }
import com.google.mu.function.CheckedConsumer; import com.google.mu.function.CheckedFunction; import com.google.mu.function.CheckedSupplier; import static java.util.Objects.requireNonNull; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import com.google.mu.function.CheckedBiFunction;
* Wraps {@code function} to be used for a stream of Maybe. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <F, T, E extends Throwable> Function<F, Maybe<T, E>> maybe( CheckedFunction<? super F, ? extends T, E> function) { requireNonNull(function); return from -> maybe(()->function.apply(from)); } /** * Wraps {@code function} that returns {@code Stream<T>} to one that returns * {@code Stream<Maybe<T, E>>} with exceptions of type {@code E} wrapped. * * <p>Useful to be passed to {@link Stream#flatMap}. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <F, T, E extends Throwable> Function<F, Stream<Maybe<T, E>>> maybeStream( CheckedFunction<? super F, ? extends Stream<? extends T>, E> function) { Function<F, Maybe<Stream<? extends T>, E>> wrapped = maybe(function); return wrapped.andThen(Maybe::maybeStream); } /** * Wraps {@code function} to be used for a stream of Maybe. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <A, B, T, E extends Throwable> BiFunction<A, B, Maybe<T, E>> maybe(
// Path: mug/src/main/java/com/google/mu/function/CheckedBiFunction.java // @FunctionalInterface // public interface CheckedBiFunction<A, B, T, E extends Throwable> { // T apply(A a, B b) throws E; // // /** // * Returns a new {@code CheckedBiFunction} that maps the return value using {@code mapper}. // * For example: {@code ((a, b) -> a + b).andThen(Object::toString).apply(1, 2) => "3"}. // */ // default <R> CheckedBiFunction<A, B, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return (a, b) -> mapper.apply(apply(a, b)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedConsumer.java // @FunctionalInterface // public interface CheckedConsumer<T, E extends Throwable> { // void accept(T input) throws E; // // /** // * Returns a new {@code CheckedConsumer} that also passes the input to {@code that}. // * For example: {@code out::writeObject.andThen(logger::info).accept("message")}. // */ // default CheckedConsumer<T, E> andThen(CheckedConsumer<? super T, E> that) { // requireNonNull(that); // return input -> { // accept(input); // that.accept(input); // }; // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // } // Path: mug/src/main/java/com/google/mu/util/Maybe.java import com.google.mu.function.CheckedConsumer; import com.google.mu.function.CheckedFunction; import com.google.mu.function.CheckedSupplier; import static java.util.Objects.requireNonNull; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import com.google.mu.function.CheckedBiFunction; * Wraps {@code function} to be used for a stream of Maybe. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <F, T, E extends Throwable> Function<F, Maybe<T, E>> maybe( CheckedFunction<? super F, ? extends T, E> function) { requireNonNull(function); return from -> maybe(()->function.apply(from)); } /** * Wraps {@code function} that returns {@code Stream<T>} to one that returns * {@code Stream<Maybe<T, E>>} with exceptions of type {@code E} wrapped. * * <p>Useful to be passed to {@link Stream#flatMap}. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <F, T, E extends Throwable> Function<F, Stream<Maybe<T, E>>> maybeStream( CheckedFunction<? super F, ? extends Stream<? extends T>, E> function) { Function<F, Maybe<Stream<? extends T>, E>> wrapped = maybe(function); return wrapped.andThen(Maybe::maybeStream); } /** * Wraps {@code function} to be used for a stream of Maybe. * * <p>Unchecked exceptions will be immediately propagated without being wrapped. */ public static <A, B, T, E extends Throwable> BiFunction<A, B, Maybe<T, E>> maybe(
CheckedBiFunction<? super A, ? super B, ? extends T, ? extends E> function) {
google/mug
mug/src/test/java/com/google/mu/util/OptionalsTest.java
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester;
package com.google.mu.util; @RunWith(JUnit4.class) public class OptionalsTest { @Mock private BiAction action; @Mock private Consumer<Object> consumer; @Mock private Runnable otherwise; @Before public void setUpMocks() { MockitoAnnotations.initMocks(this); } @Test public void optionally_empty() { assertThat(
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // } // Path: mug/src/test/java/com/google/mu/util/OptionalsTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester; package com.google.mu.util; @RunWith(JUnit4.class) public class OptionalsTest { @Mock private BiAction action; @Mock private Consumer<Object> consumer; @Mock private Runnable otherwise; @Before public void setUpMocks() { MockitoAnnotations.initMocks(this); } @Test public void optionally_empty() { assertThat(
optionally(
google/mug
mug/src/test/java/com/google/mu/util/OptionalsTest.java
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester;
package com.google.mu.util; @RunWith(JUnit4.class) public class OptionalsTest { @Mock private BiAction action; @Mock private Consumer<Object> consumer; @Mock private Runnable otherwise; @Before public void setUpMocks() { MockitoAnnotations.initMocks(this); } @Test public void optionally_empty() { assertThat( optionally( false, () -> { throw new AssertionError(); })) .isEmpty(); } @Test public void optionally_supplierReturnsNull() { assertThat(optionally(true, () -> null)).isEmpty(); } @Test public void optionally_notEmpty() { assertThat(optionally(true, () -> "v")).hasValue("v"); } @Test public void optional_empty() {
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // } // Path: mug/src/test/java/com/google/mu/util/OptionalsTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester; package com.google.mu.util; @RunWith(JUnit4.class) public class OptionalsTest { @Mock private BiAction action; @Mock private Consumer<Object> consumer; @Mock private Runnable otherwise; @Before public void setUpMocks() { MockitoAnnotations.initMocks(this); } @Test public void optionally_empty() { assertThat( optionally( false, () -> { throw new AssertionError(); })) .isEmpty(); } @Test public void optionally_supplierReturnsNull() { assertThat(optionally(true, () -> null)).isEmpty(); } @Test public void optionally_notEmpty() { assertThat(optionally(true, () -> "v")).hasValue("v"); } @Test public void optional_empty() {
assertThat(optional(false, "whatever")).isEmpty();
google/mug
mug/src/test/java/com/google/mu/util/OptionalsTest.java
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester;
optionally( false, () -> { throw new AssertionError(); })) .isEmpty(); } @Test public void optionally_supplierReturnsNull() { assertThat(optionally(true, () -> null)).isEmpty(); } @Test public void optionally_notEmpty() { assertThat(optionally(true, () -> "v")).hasValue("v"); } @Test public void optional_empty() { assertThat(optional(false, "whatever")).isEmpty(); assertThat(optional(false, null)).isEmpty(); } @Test public void optional_nullValueIsTranslatedToEmpty() { assertThat(optional(true, null)).isEmpty(); } @Test public void optional_notEmpty() { assertThat(optional(true, "v")).hasValue("v"); } @Test public void ifPresent_or_firstIsAbsent_secondSupplierIsPresent() {
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // } // Path: mug/src/test/java/com/google/mu/util/OptionalsTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester; optionally( false, () -> { throw new AssertionError(); })) .isEmpty(); } @Test public void optionally_supplierReturnsNull() { assertThat(optionally(true, () -> null)).isEmpty(); } @Test public void optionally_notEmpty() { assertThat(optionally(true, () -> "v")).hasValue("v"); } @Test public void optional_empty() { assertThat(optional(false, "whatever")).isEmpty(); assertThat(optional(false, null)).isEmpty(); } @Test public void optional_nullValueIsTranslatedToEmpty() { assertThat(optional(true, null)).isEmpty(); } @Test public void optional_notEmpty() { assertThat(optional(true, "v")).hasValue("v"); } @Test public void ifPresent_or_firstIsAbsent_secondSupplierIsPresent() {
ifPresent(Optional.empty(), consumer::accept)
google/mug
mug/src/test/java/com/google/mu/util/OptionalsTest.java
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester;
verify(consumer).accept("foo"); verify(otherwise, never()).run(); } @Test public void ifPresent_leftIsEmpty() { ifPresent(Optional.empty(), Optional.of("bar"), action::run); verify(action, never()).run(any(), any()); } @Test public void ifPresent_rightIsEmpty() { ifPresent(Optional.of("foo"), Optional.empty(), action::run); verify(action, never()).run(any(), any()); } @Test public void ifPresent_bothPresent() { ifPresent(Optional.of("foo"), Optional.of("bar"), action::run); verify(action).run("foo", "bar"); } @Test public void ifPresent_biOptional_empty() { assertThat(ifPresent(BiOptional.empty(), action::run)).isEqualTo(Conditional.FALSE); verify(action, never()).run(any(), any()); } @Test public void ifPresent_biOptional_notEmpty() { assertThat(ifPresent(BiOptional.of("foo", "bar"), action::run)).isEqualTo(Conditional.TRUE); verify(action).run("foo", "bar"); } @Test public void map_leftIsEmpty() {
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // } // Path: mug/src/test/java/com/google/mu/util/OptionalsTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester; verify(consumer).accept("foo"); verify(otherwise, never()).run(); } @Test public void ifPresent_leftIsEmpty() { ifPresent(Optional.empty(), Optional.of("bar"), action::run); verify(action, never()).run(any(), any()); } @Test public void ifPresent_rightIsEmpty() { ifPresent(Optional.of("foo"), Optional.empty(), action::run); verify(action, never()).run(any(), any()); } @Test public void ifPresent_bothPresent() { ifPresent(Optional.of("foo"), Optional.of("bar"), action::run); verify(action).run("foo", "bar"); } @Test public void ifPresent_biOptional_empty() { assertThat(ifPresent(BiOptional.empty(), action::run)).isEqualTo(Conditional.FALSE); verify(action, never()).run(any(), any()); } @Test public void ifPresent_biOptional_notEmpty() { assertThat(ifPresent(BiOptional.of("foo", "bar"), action::run)).isEqualTo(Conditional.TRUE); verify(action).run("foo", "bar"); } @Test public void map_leftIsEmpty() {
assertThat(mapBoth(Optional.empty(), Optional.of("bar"), action::run)).isEqualTo(Optional.empty());
google/mug
mug/src/test/java/com/google/mu/util/OptionalsTest.java
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester;
assertThat(ifPresent(BiOptional.empty(), action::run)).isEqualTo(Conditional.FALSE); verify(action, never()).run(any(), any()); } @Test public void ifPresent_biOptional_notEmpty() { assertThat(ifPresent(BiOptional.of("foo", "bar"), action::run)).isEqualTo(Conditional.TRUE); verify(action).run("foo", "bar"); } @Test public void map_leftIsEmpty() { assertThat(mapBoth(Optional.empty(), Optional.of("bar"), action::run)).isEqualTo(Optional.empty()); verify(action, never()).run(any(), any()); } @Test public void map_rightIsEmpty() { assertThat(mapBoth(Optional.of("foo"), Optional.empty(), action::run)).isEqualTo(Optional.empty()); verify(action, never()).run(any(), any()); } @Test public void map_bothArePresent_mapperReturnsNull() { assertThat(mapBoth(Optional.of("foo"), Optional.empty(), (a, b) -> null)) .isEqualTo(Optional.empty()); } @Test public void map_bothArePresent_mapperReturnsNonNull() { assertThat(mapBoth(Optional.of("foo"), Optional.of("bar"), (a, b) -> a + b)) .isEqualTo(Optional.of("foobar")); } @Test public void flatMap_leftIsEmpty() {
// Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> flatMapBoth( // Optional<A> left, Optional<B> right, // CheckedBiFunction<? super A, ? super B, ? extends Optional<R>, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return requireNonNull(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <E extends Throwable> Premise ifPresent( // OptionalInt optional, CheckedIntConsumer<E> consumer) throws E { // requireNonNull(optional); // requireNonNull(consumer); // if (optional.isPresent()) { // consumer.accept(optional.getAsInt()); // return Conditional.TRUE; // } else { // return Conditional.FALSE; // } // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // @Deprecated // public static <A, B, R, E extends Throwable> Optional<R> mapBoth( // Optional<A> left, Optional<B> right, CheckedBiFunction<? super A, ? super B, ? extends R, E> mapper) // throws E { // requireNonNull(left); // requireNonNull(right); // requireNonNull(mapper); // if (left.isPresent() && right.isPresent()) { // return Optional.ofNullable(mapper.apply(left.get(), right.get())); // } // return Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T> Optional<T> optional(boolean condition, T value) { // return condition ? Optional.ofNullable(value) : Optional.empty(); // } // // Path: mug/src/main/java/com/google/mu/util/Optionals.java // public static <T, E extends Throwable> Optional<T> optionally( // boolean condition, CheckedSupplier<? extends T, E> supplier) throws E { // requireNonNull(supplier); // return condition ? Optional.ofNullable(supplier.get()) : Optional.empty(); // } // Path: mug/src/test/java/com/google/mu/util/OptionalsTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.Optionals.flatMapBoth; import static com.google.mu.util.Optionals.ifPresent; import static com.google.mu.util.Optionals.mapBoth; import static com.google.mu.util.Optionals.optional; import static com.google.mu.util.Optionals.optionally; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.google.common.testing.NullPointerTester; assertThat(ifPresent(BiOptional.empty(), action::run)).isEqualTo(Conditional.FALSE); verify(action, never()).run(any(), any()); } @Test public void ifPresent_biOptional_notEmpty() { assertThat(ifPresent(BiOptional.of("foo", "bar"), action::run)).isEqualTo(Conditional.TRUE); verify(action).run("foo", "bar"); } @Test public void map_leftIsEmpty() { assertThat(mapBoth(Optional.empty(), Optional.of("bar"), action::run)).isEqualTo(Optional.empty()); verify(action, never()).run(any(), any()); } @Test public void map_rightIsEmpty() { assertThat(mapBoth(Optional.of("foo"), Optional.empty(), action::run)).isEqualTo(Optional.empty()); verify(action, never()).run(any(), any()); } @Test public void map_bothArePresent_mapperReturnsNull() { assertThat(mapBoth(Optional.of("foo"), Optional.empty(), (a, b) -> null)) .isEqualTo(Optional.empty()); } @Test public void map_bothArePresent_mapperReturnsNonNull() { assertThat(mapBoth(Optional.of("foo"), Optional.of("bar"), (a, b) -> a + b)) .isEqualTo(Optional.of("foobar")); } @Test public void flatMap_leftIsEmpty() {
assertThat(flatMapBoth(
google/mug
mug/src/main/java/com/google/mu/util/graph/GraphWalker.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // }
import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream;
private final Deque<Spliterator<? extends N>> horizon = new ArrayDeque<>(); private N visited; Walk( Function<? super N, ? extends Stream<? extends N>> findSuccessors, Predicate<? super N> tracker) { this.findSuccessors = findSuccessors; this.tracker = tracker; } @Override public void accept(N value) { this.visited = requireNonNull(value); } Stream<N> breadthFirst(Iterable<? extends N> startNodes) { horizon.add(startNodes.spliterator()); return topDown(Queue::add); } Stream<N> preOrder(Iterable<? extends N> startNodes) { horizon.push(startNodes.spliterator()); return topDown(Deque::push); } Stream<N> postOrder(Iterable<? extends N> startNodes) { return postOrder(startNodes, new ArrayDeque<>()); } private Stream<N> postOrder(Iterable<? extends N> startNodes, Deque<N> roots) { horizon.push(startNodes.spliterator());
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // } // Path: mug/src/main/java/com/google/mu/util/graph/GraphWalker.java import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; private final Deque<Spliterator<? extends N>> horizon = new ArrayDeque<>(); private N visited; Walk( Function<? super N, ? extends Stream<? extends N>> findSuccessors, Predicate<? super N> tracker) { this.findSuccessors = findSuccessors; this.tracker = tracker; } @Override public void accept(N value) { this.visited = requireNonNull(value); } Stream<N> breadthFirst(Iterable<? extends N> startNodes) { horizon.add(startNodes.spliterator()); return topDown(Queue::add); } Stream<N> preOrder(Iterable<? extends N> startNodes) { horizon.push(startNodes.spliterator()); return topDown(Deque::push); } Stream<N> postOrder(Iterable<? extends N> startNodes) { return postOrder(startNodes, new ArrayDeque<>()); } private Stream<N> postOrder(Iterable<? extends N> startNodes, Deque<N> roots) { horizon.push(startNodes.spliterator());
return whileNotNull(() -> {
google/mug
mug/src/main/java/com/google/mu/util/graph/GraphWalker.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // }
import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream;
}); } private Stream<N> topDown(InsertionOrder order) { return whileNotNull(() -> { do { if (visitNext()) { N next = visited; Stream<? extends N> successors = findSuccessors.apply(next); if (successors != null) order.insertInto(horizon, successors.spliterator()); return next; } } while (!horizon.isEmpty()); return null; // no more element }); } private boolean visitNext() { Spliterator<? extends N> top = horizon.getFirst(); while (top.tryAdvance(this)) { if (tracker.test(visited)) return true; } horizon.removeFirst(); return false; } List<N> topologicalOrder(Iterable<? extends N> startNodes) { CycleTracker cycleDetector = new CycleTracker(); return cycleDetector.startPostOrder(startNodes, n -> { throw new CyclicGraphException(
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // } // Path: mug/src/main/java/com/google/mu/util/graph/GraphWalker.java import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; }); } private Stream<N> topDown(InsertionOrder order) { return whileNotNull(() -> { do { if (visitNext()) { N next = visited; Stream<? extends N> successors = findSuccessors.apply(next); if (successors != null) order.insertInto(horizon, successors.spliterator()); return next; } } while (!horizon.isEmpty()); return null; // no more element }); } private boolean visitNext() { Spliterator<? extends N> top = horizon.getFirst(); while (top.tryAdvance(this)) { if (tracker.test(visited)) return true; } horizon.removeFirst(); return false; } List<N> topologicalOrder(Iterable<? extends N> startNodes) { CycleTracker cycleDetector = new CycleTracker(); return cycleDetector.startPostOrder(startNodes, n -> { throw new CyclicGraphException(
cycleDetector.currentPath().collect(toListAndThen(l -> l.add(n))));
google/mug
mug/src/main/java/com/google/mu/util/graph/GraphWalker.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // }
import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream;
throw new CyclicGraphException( cycleDetector.currentPath().collect(toListAndThen(l -> l.add(n)))); }).collect(toListAndThen(Collections::reverse)); } Optional<Stream<N>> detectCycle(Iterable<? extends N> startNodes) { AtomicReference<N> cyclic = new AtomicReference<>(); CycleTracker detector = new CycleTracker(); return detector.startPostOrder(startNodes, n -> cyclic.compareAndSet(null, n)) .filter(n -> cyclic.get() != null) .findFirst() .map(last -> Stream.concat(detector.currentPath(), Stream.of(last, cyclic.getAndSet(null)))); } private final class CycleTracker { private final LinkedHashSet<N> currentPath = new LinkedHashSet<>(); Stream<N> startPostOrder(Iterable<? extends N> startNodes, Consumer<N> foundCycle) { Walk<N> walk = new Walk<>( findSuccessors, node -> { boolean newNode = tracker.test(node); if (newNode) { currentPath.add(node); } else if (currentPath.contains(node)) { foundCycle.accept(node); } return newNode; });
// Path: mug/src/main/java/com/google/mu/util/stream/MoreCollectors.java // public static <T> Collector<T, ?, List<T>> toListAndThen(Consumer<? super List<T>> arranger) { // requireNonNull(arranger); // Collector<T, ?, List<T>> rejectingNulls = // Collectors.mapping(Objects::requireNonNull, Collectors.toCollection(ArrayList::new)); // return Collectors.collectingAndThen(rejectingNulls, list -> { // arranger.accept(list); // return Collections.unmodifiableList(list); // }); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // } // Path: mug/src/main/java/com/google/mu/util/graph/GraphWalker.java import static com.google.mu.util.stream.MoreCollectors.toListAndThen; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; throw new CyclicGraphException( cycleDetector.currentPath().collect(toListAndThen(l -> l.add(n)))); }).collect(toListAndThen(Collections::reverse)); } Optional<Stream<N>> detectCycle(Iterable<? extends N> startNodes) { AtomicReference<N> cyclic = new AtomicReference<>(); CycleTracker detector = new CycleTracker(); return detector.startPostOrder(startNodes, n -> cyclic.compareAndSet(null, n)) .filter(n -> cyclic.get() != null) .findFirst() .map(last -> Stream.concat(detector.currentPath(), Stream.of(last, cyclic.getAndSet(null)))); } private final class CycleTracker { private final LinkedHashSet<N> currentPath = new LinkedHashSet<>(); Stream<N> startPostOrder(Iterable<? extends N> startNodes, Consumer<N> foundCycle) { Walk<N> walk = new Walk<>( findSuccessors, node -> { boolean newNode = tracker.test(node); if (newNode) { currentPath.add(node); } else if (currentPath.contains(node)) { foundCycle.accept(node); } return newNode; });
return withSideEffect(walk.postOrder(startNodes), currentPath::remove);
google/mug
mug/src/main/java/com/google/mu/util/Conditional.java
// Path: mug/src/main/java/com/google/mu/function/CheckedRunnable.java // @FunctionalInterface // public interface CheckedRunnable<E extends Throwable> { // void run() throws E; // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // }
import static java.util.Objects.requireNonNull; import com.google.mu.function.CheckedRunnable; import com.google.mu.function.CheckedSupplier;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * Provides instances of {@link Premise}. * * @since 1.14 */ enum Conditional implements Premise { TRUE {
// Path: mug/src/main/java/com/google/mu/function/CheckedRunnable.java // @FunctionalInterface // public interface CheckedRunnable<E extends Throwable> { // void run() throws E; // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // } // Path: mug/src/main/java/com/google/mu/util/Conditional.java import static java.util.Objects.requireNonNull; import com.google.mu.function.CheckedRunnable; import com.google.mu.function.CheckedSupplier; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * Provides instances of {@link Premise}. * * @since 1.14 */ enum Conditional implements Premise { TRUE {
@Override public <E extends Throwable> void orElse(CheckedRunnable<E> block) {
google/mug
mug/src/main/java/com/google/mu/util/Conditional.java
// Path: mug/src/main/java/com/google/mu/function/CheckedRunnable.java // @FunctionalInterface // public interface CheckedRunnable<E extends Throwable> { // void run() throws E; // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // }
import static java.util.Objects.requireNonNull; import com.google.mu.function.CheckedRunnable; import com.google.mu.function.CheckedSupplier;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * Provides instances of {@link Premise}. * * @since 1.14 */ enum Conditional implements Premise { TRUE { @Override public <E extends Throwable> void orElse(CheckedRunnable<E> block) { requireNonNull(block); }
// Path: mug/src/main/java/com/google/mu/function/CheckedRunnable.java // @FunctionalInterface // public interface CheckedRunnable<E extends Throwable> { // void run() throws E; // } // // Path: mug/src/main/java/com/google/mu/function/CheckedSupplier.java // @FunctionalInterface // public interface CheckedSupplier<T, E extends Throwable> { // T get() throws E; // // /** // * Returns a new {@code CheckedSupplier} that maps the return value using {@code mapper}. // * For example: {@code (x -> 1).andThen(Object::toString).get() => "1"}. // */ // default <R> CheckedSupplier<R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return () -> mapper.apply(get()); // } // } // Path: mug/src/main/java/com/google/mu/util/Conditional.java import static java.util.Objects.requireNonNull; import com.google.mu.function.CheckedRunnable; import com.google.mu.function.CheckedSupplier; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * Provides instances of {@link Premise}. * * @since 1.14 */ enum Conditional implements Premise { TRUE { @Override public <E extends Throwable> void orElse(CheckedRunnable<E> block) { requireNonNull(block); }
@Override public <E extends Throwable> Premise or(CheckedSupplier<? extends Premise, E> alternative) {
google/mug
mug/src/main/java/com/google/mu/util/stream/BiCollectors.java
// Path: mug/src/main/java/com/google/mu/util/Both.java // @FunctionalInterface // public interface Both<A, B> { // /** // * Returns an instance with both {@code a} and {@code b}. // * // * @since 5.8 // */ // public static <A, B> Both<A, B> of(A a, B b) { // return new BiOptional.Present<>(a, b); // } // // /** // * Applies the {@code mapper} function with this pair of two things as arguments. // * // * @throws NullPointerException if {@code mapper} is null // */ // <T> T andThen(BiFunction<? super A, ? super B, T> mapper); // // /** // * If the pair {@link #matches matches()} {@code condition}, returns a {@link BiOptional} containing // * the pair, or else returns empty. // * // * @throws NullPointerException if {@code condition} is null, or if {@code condition} matches but // * either value in this pair is null // */ // default BiOptional<A, B> filter(BiPredicate<? super A, ? super B> condition) { // requireNonNull(condition); // return andThen((a, b) -> condition.test(a, b) ? BiOptional.of(a, b) : BiOptional.empty()); // } // // /** // * Returns true if the pair matches {@code condition}. // * // * @throws NullPointerException if {@code condition} is null // */ // default boolean matches(BiPredicate<? super A, ? super B> condition) { // return andThen(condition::test); // } // // /** // * Invokes {@code consumer} with this pair and returns this object as is. // * // * @throws NullPointerException if {@code consumer} is null // */ // default Both<A, B> peek(BiConsumer<? super A, ? super B> consumer) { // requireNonNull(consumer); // return andThen((a, b) -> { // consumer.accept(a, b); // return this; // }); // } // }
import static java.util.Objects.requireNonNull; import java.util.AbstractMap; import java.util.Collections; import java.util.DoubleSummaryStatistics; import java.util.IntSummaryStatistics; import java.util.LinkedHashMap; import java.util.LongSummaryStatistics; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.mu.util.Both;
/** * Returns a {@link BiCollector} that first maps the input pair using {@code keyMapper} and {@code valueMapper} * respectively, then collects the results using {@code downstream} collector. * * @since 3.6 */ public static <K, V, K1, V1, R> BiCollector<K, V, R> mapping( BiFunction<? super K, ? super V, ? extends K1> keyMapper, BiFunction<? super K, ? super V, ? extends V1> valueMapper, BiCollector<K1, V1, R> downstream) { requireNonNull(keyMapper); requireNonNull(valueMapper); requireNonNull(downstream); return new BiCollector<K, V, R>() { @Override public <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue) { return downstream.splitting( e -> keyMapper.apply(toKey.apply(e), toValue.apply(e)), e -> valueMapper.apply(toKey.apply(e), toValue.apply(e))); } }; } /** * Returns a {@link BiCollector} that first maps the input pair into another pair using {@code mapper}. * and then collects the results using {@code downstream} collector. * * @since 5.2 */ public static <K, V, K1, V1, R> BiCollector<K, V, R> mapping(
// Path: mug/src/main/java/com/google/mu/util/Both.java // @FunctionalInterface // public interface Both<A, B> { // /** // * Returns an instance with both {@code a} and {@code b}. // * // * @since 5.8 // */ // public static <A, B> Both<A, B> of(A a, B b) { // return new BiOptional.Present<>(a, b); // } // // /** // * Applies the {@code mapper} function with this pair of two things as arguments. // * // * @throws NullPointerException if {@code mapper} is null // */ // <T> T andThen(BiFunction<? super A, ? super B, T> mapper); // // /** // * If the pair {@link #matches matches()} {@code condition}, returns a {@link BiOptional} containing // * the pair, or else returns empty. // * // * @throws NullPointerException if {@code condition} is null, or if {@code condition} matches but // * either value in this pair is null // */ // default BiOptional<A, B> filter(BiPredicate<? super A, ? super B> condition) { // requireNonNull(condition); // return andThen((a, b) -> condition.test(a, b) ? BiOptional.of(a, b) : BiOptional.empty()); // } // // /** // * Returns true if the pair matches {@code condition}. // * // * @throws NullPointerException if {@code condition} is null // */ // default boolean matches(BiPredicate<? super A, ? super B> condition) { // return andThen(condition::test); // } // // /** // * Invokes {@code consumer} with this pair and returns this object as is. // * // * @throws NullPointerException if {@code consumer} is null // */ // default Both<A, B> peek(BiConsumer<? super A, ? super B> consumer) { // requireNonNull(consumer); // return andThen((a, b) -> { // consumer.accept(a, b); // return this; // }); // } // } // Path: mug/src/main/java/com/google/mu/util/stream/BiCollectors.java import static java.util.Objects.requireNonNull; import java.util.AbstractMap; import java.util.Collections; import java.util.DoubleSummaryStatistics; import java.util.IntSummaryStatistics; import java.util.LinkedHashMap; import java.util.LongSummaryStatistics; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.ToDoubleBiFunction; import java.util.function.ToIntBiFunction; import java.util.function.ToLongBiFunction; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.mu.util.Both; /** * Returns a {@link BiCollector} that first maps the input pair using {@code keyMapper} and {@code valueMapper} * respectively, then collects the results using {@code downstream} collector. * * @since 3.6 */ public static <K, V, K1, V1, R> BiCollector<K, V, R> mapping( BiFunction<? super K, ? super V, ? extends K1> keyMapper, BiFunction<? super K, ? super V, ? extends V1> valueMapper, BiCollector<K1, V1, R> downstream) { requireNonNull(keyMapper); requireNonNull(valueMapper); requireNonNull(downstream); return new BiCollector<K, V, R>() { @Override public <E> Collector<E, ?, R> splitting(Function<E, K> toKey, Function<E, V> toValue) { return downstream.splitting( e -> keyMapper.apply(toKey.apply(e), toValue.apply(e)), e -> valueMapper.apply(toKey.apply(e), toValue.apply(e))); } }; } /** * Returns a {@link BiCollector} that first maps the input pair into another pair using {@code mapper}. * and then collects the results using {@code downstream} collector. * * @since 5.2 */ public static <K, V, K1, V1, R> BiCollector<K, V, R> mapping(
BiFunction<? super K, ? super V, ? extends Both<? extends K1, ? extends V1>> mapper,
google/mug
mug/src/main/java/com/google/mu/util/graph/BinaryTreeWalker.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // }
import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Queue; import java.util.function.UnaryOperator; import java.util.stream.Stream;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; /** * Walker for binary tree topology (see {@link Walker#inBinaryTree Walker.inBinaryTree()}). * * <p>Besides {@link #preOrderFrom pre-order}, {@link #postOrderFrom post-order} and {@link * #breadthFirstFrom breadth-first} traversals, also supports {@link #inOrderFrom in-order}. * * @param <N> the tree node type * @since 4.2 */ public final class BinaryTreeWalker<N> extends Walker<N> { private final UnaryOperator<N> getLeft; private final UnaryOperator<N> getRight; BinaryTreeWalker(UnaryOperator<N> getLeft, UnaryOperator<N> getRight) { this.getLeft = requireNonNull(getLeft); this.getRight = requireNonNull(getRight); } /** * Returns a lazy stream for breadth-first traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> breadthFirstFrom(Iterable<? extends N> roots) { return topDown(roots, Queue::add); } /** * Returns a lazy stream for pre-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> preOrderFrom(Iterable<? extends N> roots) { return inBinaryTree(getRight, getLeft).topDown(roots, Deque::push); } /** * Returns a lazy stream for post-order traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. * * <p>For small or medium sized in-memory trees, it's equivalent and more efficient to first * collect the nodes into a list in "reverse post order", and then use {@code * Collections.reverse()}, as in: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) // 1. flip left to right * .preOrderFrom(root) // 2. pre-order * .collect(toCollection(ArrayList::new)); // 3. in reverse-post-order * Collections.reverse(nodes); // 4. reverse to get post-order * }</pre> * * Or, use the {@link com.google.mu.util.stream.MoreStreams#toListAndThen toListAndThen()} * collector to do it in one-liner: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) * .preOrderFrom(root) * .collect(toListAndThen(Collections::reverse)); * }</pre> */ @Override public Stream<N> postOrderFrom(Iterable<? extends N> roots) {
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // } // Path: mug/src/main/java/com/google/mu/util/graph/BinaryTreeWalker.java import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Queue; import java.util.function.UnaryOperator; import java.util.stream.Stream; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; /** * Walker for binary tree topology (see {@link Walker#inBinaryTree Walker.inBinaryTree()}). * * <p>Besides {@link #preOrderFrom pre-order}, {@link #postOrderFrom post-order} and {@link * #breadthFirstFrom breadth-first} traversals, also supports {@link #inOrderFrom in-order}. * * @param <N> the tree node type * @since 4.2 */ public final class BinaryTreeWalker<N> extends Walker<N> { private final UnaryOperator<N> getLeft; private final UnaryOperator<N> getRight; BinaryTreeWalker(UnaryOperator<N> getLeft, UnaryOperator<N> getRight) { this.getLeft = requireNonNull(getLeft); this.getRight = requireNonNull(getRight); } /** * Returns a lazy stream for breadth-first traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> breadthFirstFrom(Iterable<? extends N> roots) { return topDown(roots, Queue::add); } /** * Returns a lazy stream for pre-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> preOrderFrom(Iterable<? extends N> roots) { return inBinaryTree(getRight, getLeft).topDown(roots, Deque::push); } /** * Returns a lazy stream for post-order traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. * * <p>For small or medium sized in-memory trees, it's equivalent and more efficient to first * collect the nodes into a list in "reverse post order", and then use {@code * Collections.reverse()}, as in: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) // 1. flip left to right * .preOrderFrom(root) // 2. pre-order * .collect(toCollection(ArrayList::new)); // 3. in reverse-post-order * Collections.reverse(nodes); // 4. reverse to get post-order * }</pre> * * Or, use the {@link com.google.mu.util.stream.MoreStreams#toListAndThen toListAndThen()} * collector to do it in one-liner: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) * .preOrderFrom(root) * .collect(toListAndThen(Collections::reverse)); * }</pre> */ @Override public Stream<N> postOrderFrom(Iterable<? extends N> roots) {
return whileNotNull(new PostOrder(roots)::nextOrNull);
google/mug
mug/src/main/java/com/google/mu/util/graph/BinaryTreeWalker.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // }
import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Queue; import java.util.function.UnaryOperator; import java.util.stream.Stream;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; /** * Walker for binary tree topology (see {@link Walker#inBinaryTree Walker.inBinaryTree()}). * * <p>Besides {@link #preOrderFrom pre-order}, {@link #postOrderFrom post-order} and {@link * #breadthFirstFrom breadth-first} traversals, also supports {@link #inOrderFrom in-order}. * * @param <N> the tree node type * @since 4.2 */ public final class BinaryTreeWalker<N> extends Walker<N> { private final UnaryOperator<N> getLeft; private final UnaryOperator<N> getRight; BinaryTreeWalker(UnaryOperator<N> getLeft, UnaryOperator<N> getRight) { this.getLeft = requireNonNull(getLeft); this.getRight = requireNonNull(getRight); } /** * Returns a lazy stream for breadth-first traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> breadthFirstFrom(Iterable<? extends N> roots) { return topDown(roots, Queue::add); } /** * Returns a lazy stream for pre-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> preOrderFrom(Iterable<? extends N> roots) { return inBinaryTree(getRight, getLeft).topDown(roots, Deque::push); } /** * Returns a lazy stream for post-order traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. * * <p>For small or medium sized in-memory trees, it's equivalent and more efficient to first * collect the nodes into a list in "reverse post order", and then use {@code * Collections.reverse()}, as in: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) // 1. flip left to right * .preOrderFrom(root) // 2. pre-order * .collect(toCollection(ArrayList::new)); // 3. in reverse-post-order * Collections.reverse(nodes); // 4. reverse to get post-order * }</pre> * * Or, use the {@link com.google.mu.util.stream.MoreStreams#toListAndThen toListAndThen()} * collector to do it in one-liner: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) * .preOrderFrom(root) * .collect(toListAndThen(Collections::reverse)); * }</pre> */ @Override public Stream<N> postOrderFrom(Iterable<? extends N> roots) { return whileNotNull(new PostOrder(roots)::nextOrNull); } /** * Returns a lazy stream for in-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @SafeVarargs public final Stream<N> inOrderFrom(N... roots) { return inOrderFrom(asList(roots)); } /** * Returns a lazy stream for in-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ public Stream<N> inOrderFrom(Iterable<? extends N> roots) { return whileNotNull(new InOrder(roots)::nextOrNull); } private Stream<N> topDown(Iterable<? extends N> roots, InsertionOrder order) { Deque<N> horizon = toDeque(roots);
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> withSideEffect(Stream<T> stream, Consumer<? super T> sideEffect) { // requireNonNull(stream); // requireNonNull(sideEffect); // return StreamSupport.stream(() -> withSideEffect(stream.spliterator(), sideEffect), 0, false); // } // Path: mug/src/main/java/com/google/mu/util/graph/BinaryTreeWalker.java import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static com.google.mu.util.stream.MoreStreams.withSideEffect; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.Queue; import java.util.function.UnaryOperator; import java.util.stream.Stream; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; /** * Walker for binary tree topology (see {@link Walker#inBinaryTree Walker.inBinaryTree()}). * * <p>Besides {@link #preOrderFrom pre-order}, {@link #postOrderFrom post-order} and {@link * #breadthFirstFrom breadth-first} traversals, also supports {@link #inOrderFrom in-order}. * * @param <N> the tree node type * @since 4.2 */ public final class BinaryTreeWalker<N> extends Walker<N> { private final UnaryOperator<N> getLeft; private final UnaryOperator<N> getRight; BinaryTreeWalker(UnaryOperator<N> getLeft, UnaryOperator<N> getRight) { this.getLeft = requireNonNull(getLeft); this.getRight = requireNonNull(getRight); } /** * Returns a lazy stream for breadth-first traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> breadthFirstFrom(Iterable<? extends N> roots) { return topDown(roots, Queue::add); } /** * Returns a lazy stream for pre-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @Override public Stream<N> preOrderFrom(Iterable<? extends N> roots) { return inBinaryTree(getRight, getLeft).topDown(roots, Deque::push); } /** * Returns a lazy stream for post-order traversal from {@code root}. * Empty stream is returned if {@code roots} is empty. * * <p>For small or medium sized in-memory trees, it's equivalent and more efficient to first * collect the nodes into a list in "reverse post order", and then use {@code * Collections.reverse()}, as in: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) // 1. flip left to right * .preOrderFrom(root) // 2. pre-order * .collect(toCollection(ArrayList::new)); // 3. in reverse-post-order * Collections.reverse(nodes); // 4. reverse to get post-order * }</pre> * * Or, use the {@link com.google.mu.util.stream.MoreStreams#toListAndThen toListAndThen()} * collector to do it in one-liner: * <pre>{@code * List<Node> nodes = * Walker.inBinaryTree(Tree::right, Tree::left) * .preOrderFrom(root) * .collect(toListAndThen(Collections::reverse)); * }</pre> */ @Override public Stream<N> postOrderFrom(Iterable<? extends N> roots) { return whileNotNull(new PostOrder(roots)::nextOrNull); } /** * Returns a lazy stream for in-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ @SafeVarargs public final Stream<N> inOrderFrom(N... roots) { return inOrderFrom(asList(roots)); } /** * Returns a lazy stream for in-order traversal from {@code roots}. * Empty stream is returned if {@code roots} is empty. */ public Stream<N> inOrderFrom(Iterable<? extends N> roots) { return whileNotNull(new InOrder(roots)::nextOrNull); } private Stream<N> topDown(Iterable<? extends N> roots, InsertionOrder order) { Deque<N> horizon = toDeque(roots);
return withSideEffect(
google/mug
mug/src/main/java/com/google/mu/util/Selection.java
// Path: mug/src/main/java/com/google/mu/util/InternalCollectors.java // static <T> Collector<T, ?, Set<T>> toImmutableSet() { // return checkingNulls( // collectingAndThen(toCollection(LinkedHashSet::new), Collections::unmodifiableSet)); // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // }
import static com.google.mu.util.InternalCollectors.toImmutableSet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.reducing; import static java.util.stream.Collectors.toCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collector; import com.google.mu.function.CheckedFunction;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * An immutable selection of choices supporting both {@link #only limited} and {@link #all * unlimited} selections. * * <p>Useful when you need to disambiguate and enforce correct handling of the * <b>implicitly selected all</b> concept, in replacement of the common and error prone * <em>empty-means-all</em> hack. That is, instead of adding (or forgetting to add) special * handling like: * * <pre>{@code * Set<String> choices = getChoices(); * if (choices.isEmpty() || choices.contains("foo")) { * // foo is selected. * } * }</pre> * * Use {@code Selection} so your code is intuitive and hard to get wrong: * * <pre>{@code * Selection<String> choices = getChoices(); * if (choices.has("foo")) { * // foo is selected. * } * }</pre> * * <p>To gradually migrate from legacy code where empty sets need to be special handled all over, * use {@link #nonEmptyOrAll nonEmptyOrAll(set)} to convert to a {@code Selection} object: * * <pre>{@code * public class FoodDeliveryService { * private final Selection<Driver> eligibleDrivers; * * // Too much code churn to change this public constructor signature. * public FoodDeliveryService(Set<Driver> eligibleDrivers) { * // But we can migrate internal implementation to using Selection: * this.eligibleDrivers = Selection.nonEmptyOrAll(eligibleDrivers); * } * * ... * } * }</pre> * * <p>While an unlimited selection is conceptually close to a trivially-true predicate, the {@code * Selection} type provides access to the explicitly selected choices via the {@link #limited} * method. It also implements {@link #equals}, {@link #hashCode} and {@link #toString} sensibly. * * <p>Nulls are prohibited throughout this class. * * @since 4.1 */ public interface Selection<T> { /** Returns an unlimited selection of all (unspecified) choices. */ @SuppressWarnings("unchecked") static <T> Selection<T> all() { return (Selection<T>) Selections.ALL; } /** Returns an empty selection. */ @SuppressWarnings("unchecked") static <T> Selection<T> none() { return (Selection<T>) Selections.NONE; } /** Returns a selection of {@code choices}. Null is not allowed. */ @SafeVarargs static <T> Selection<T> only(T... choices) { return Arrays.stream(choices).collect(toSelection()); } /** * Converts to {@code Selection} from legacy code where an empty collection means <b>all</b>. * After converted to {@code Selection}, user code no longer need special handling of the * <em>empty</em> case. * * <p>This method is mainly for migrating legacy code. If you have a set where empty just means * "none" with no special handling needed, you should use {@link #toSelection * set.stream().collect(toSelection())} instead. */ static <T> Selection<T> nonEmptyOrAll(Collection<? extends T> choices) { return choices.isEmpty() ? all() : choices.stream().collect(toSelection()); } /** Returns a collector that collects input elements into a limited selection. */ static <T> Collector<T, ?, Selection<T>> toSelection() {
// Path: mug/src/main/java/com/google/mu/util/InternalCollectors.java // static <T> Collector<T, ?, Set<T>> toImmutableSet() { // return checkingNulls( // collectingAndThen(toCollection(LinkedHashSet::new), Collections::unmodifiableSet)); // } // // Path: mug/src/main/java/com/google/mu/function/CheckedFunction.java // @FunctionalInterface // public interface CheckedFunction<F, T, E extends Throwable> { // T apply(F from) throws E; // // /** // * Returns a new {@code CheckedFunction} that maps the return value using {@code mapper}. // * For example: {@code (x -> x).andThen(Object::toString).apply(1) => "1"}. // */ // default <R> CheckedFunction<F, R, E> andThen( // CheckedFunction<? super T, ? extends R, ? extends E> mapper) { // requireNonNull(mapper); // return f -> mapper.apply(apply(f)); // } // } // Path: mug/src/main/java/com/google/mu/util/Selection.java import static com.google.mu.util.InternalCollectors.toImmutableSet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.reducing; import static java.util.stream.Collectors.toCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collector; import com.google.mu.function.CheckedFunction; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; /** * An immutable selection of choices supporting both {@link #only limited} and {@link #all * unlimited} selections. * * <p>Useful when you need to disambiguate and enforce correct handling of the * <b>implicitly selected all</b> concept, in replacement of the common and error prone * <em>empty-means-all</em> hack. That is, instead of adding (or forgetting to add) special * handling like: * * <pre>{@code * Set<String> choices = getChoices(); * if (choices.isEmpty() || choices.contains("foo")) { * // foo is selected. * } * }</pre> * * Use {@code Selection} so your code is intuitive and hard to get wrong: * * <pre>{@code * Selection<String> choices = getChoices(); * if (choices.has("foo")) { * // foo is selected. * } * }</pre> * * <p>To gradually migrate from legacy code where empty sets need to be special handled all over, * use {@link #nonEmptyOrAll nonEmptyOrAll(set)} to convert to a {@code Selection} object: * * <pre>{@code * public class FoodDeliveryService { * private final Selection<Driver> eligibleDrivers; * * // Too much code churn to change this public constructor signature. * public FoodDeliveryService(Set<Driver> eligibleDrivers) { * // But we can migrate internal implementation to using Selection: * this.eligibleDrivers = Selection.nonEmptyOrAll(eligibleDrivers); * } * * ... * } * }</pre> * * <p>While an unlimited selection is conceptually close to a trivially-true predicate, the {@code * Selection} type provides access to the explicitly selected choices via the {@link #limited} * method. It also implements {@link #equals}, {@link #hashCode} and {@link #toString} sensibly. * * <p>Nulls are prohibited throughout this class. * * @since 4.1 */ public interface Selection<T> { /** Returns an unlimited selection of all (unspecified) choices. */ @SuppressWarnings("unchecked") static <T> Selection<T> all() { return (Selection<T>) Selections.ALL; } /** Returns an empty selection. */ @SuppressWarnings("unchecked") static <T> Selection<T> none() { return (Selection<T>) Selections.NONE; } /** Returns a selection of {@code choices}. Null is not allowed. */ @SafeVarargs static <T> Selection<T> only(T... choices) { return Arrays.stream(choices).collect(toSelection()); } /** * Converts to {@code Selection} from legacy code where an empty collection means <b>all</b>. * After converted to {@code Selection}, user code no longer need special handling of the * <em>empty</em> case. * * <p>This method is mainly for migrating legacy code. If you have a set where empty just means * "none" with no special handling needed, you should use {@link #toSelection * set.stream().collect(toSelection())} instead. */ static <T> Selection<T> nonEmptyOrAll(Collection<? extends T> choices) { return choices.isEmpty() ? all() : choices.stream().collect(toSelection()); } /** Returns a collector that collects input elements into a limited selection. */ static <T> Collector<T, ?, Selection<T>> toSelection() {
return collectingAndThen(toImmutableSet(), Selections::explicit);
google/mug
mug/src/main/java/com/google/mu/util/stream/BiIteration.java
// Path: mug/src/main/java/com/google/mu/util/stream/Iteration.java // @FunctionalInterface // public interface Continuation { // /** Runs the continuation. It will be called at most once throughout the stream. */ // void run(); // }
import static java.util.Objects.requireNonNull; import java.util.AbstractMap; import java.util.Map; import com.google.mu.util.stream.Iteration.Continuation;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * Similar to {@link Iteration}, but is used to iteratively {@link #yield yield()} pairs into a * lazy {@link BiStream}. */ public class BiIteration<L, R> { private final Iteration<Map.Entry<L, R>> iteration = new Iteration<>(); /** Yields the pair of {@code left} and {@code right} to the result {@code BiStream}. */ public final BiIteration<L, R> yield(L left, R right) { iteration.yield( new AbstractMap.SimpleImmutableEntry<>(requireNonNull(left), requireNonNull(right))); return this; } /** * Yields to the result {@code BiStream} a recursive iteration or lazy side-effect wrapped in * {@code continuation}. */
// Path: mug/src/main/java/com/google/mu/util/stream/Iteration.java // @FunctionalInterface // public interface Continuation { // /** Runs the continuation. It will be called at most once throughout the stream. */ // void run(); // } // Path: mug/src/main/java/com/google/mu/util/stream/BiIteration.java import static java.util.Objects.requireNonNull; import java.util.AbstractMap; import java.util.Map; import com.google.mu.util.stream.Iteration.Continuation; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * Similar to {@link Iteration}, but is used to iteratively {@link #yield yield()} pairs into a * lazy {@link BiStream}. */ public class BiIteration<L, R> { private final Iteration<Map.Entry<L, R>> iteration = new Iteration<>(); /** Yields the pair of {@code left} and {@code right} to the result {@code BiStream}. */ public final BiIteration<L, R> yield(L left, R right) { iteration.yield( new AbstractMap.SimpleImmutableEntry<>(requireNonNull(left), requireNonNull(right))); return this; } /** * Yields to the result {@code BiStream} a recursive iteration or lazy side-effect wrapped in * {@code continuation}. */
public final BiIteration<L, R> yield(Continuation continuation) {
google/mug
mug/src/main/java/com/google/mu/util/stream/BiCollection.java
// Path: mug/src/main/java/com/google/mu/util/stream/BiStream.java // static <K, V> Map.Entry<K, V> kv(K key, V value) { // return new AbstractMap.SimpleImmutableEntry<>(key, value); // }
import static com.google.mu.util.stream.BiStream.kv; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * {@code BiCollection} to {@link BiStream} is like {@code Iterable} to {@code Iterator}: * a re-streamable collection of pairs. Suitable when the pairs aren't logically a {@code Map} * or {@code Multimap}. * * @since 1.4 */ public final class BiCollection<L, R> { private static final BiCollection<?, ?> EMPTY = new BiCollection<>(Collections.emptyList()); private final Collection<? extends Map.Entry<L, R>> entries; private BiCollection(Collection<? extends Entry<L, R>> underlying) { this.entries = requireNonNull(underlying); } /** Returns an empty {@code BiCollection}. */ @SuppressWarnings("unchecked") public static <L, R> BiCollection<L, R> of() { return (BiCollection<L, R>) EMPTY; } /** Returns a {@code BiCollection} for {@code left} and {@code right}. */ public static <L, R> BiCollection<L, R> of(L left, R right) {
// Path: mug/src/main/java/com/google/mu/util/stream/BiStream.java // static <K, V> Map.Entry<K, V> kv(K key, V value) { // return new AbstractMap.SimpleImmutableEntry<>(key, value); // } // Path: mug/src/main/java/com/google/mu/util/stream/BiCollection.java import static com.google.mu.util.stream.BiStream.kv; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; /** * {@code BiCollection} to {@link BiStream} is like {@code Iterable} to {@code Iterator}: * a re-streamable collection of pairs. Suitable when the pairs aren't logically a {@code Map} * or {@code Multimap}. * * @since 1.4 */ public final class BiCollection<L, R> { private static final BiCollection<?, ?> EMPTY = new BiCollection<>(Collections.emptyList()); private final Collection<? extends Map.Entry<L, R>> entries; private BiCollection(Collection<? extends Entry<L, R>> underlying) { this.entries = requireNonNull(underlying); } /** Returns an empty {@code BiCollection}. */ @SuppressWarnings("unchecked") public static <L, R> BiCollection<L, R> of() { return (BiCollection<L, R>) EMPTY; } /** Returns a {@code BiCollection} for {@code left} and {@code right}. */ public static <L, R> BiCollection<L, R> of(L left, R right) {
return new BiCollection<>(asList(kv(left, right)));
google/mug
mug/src/test/java/com/google/mu/util/stream/BiCollectionTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/BiCollection.java // public static <T, L, R> Collector<T, ?, BiCollection<L, R>> toBiCollection( // Function<? super T, ? extends L> leftFunction, // Function<? super T, ? extends R> rightFunction) { // requireNonNull(leftFunction); // requireNonNull(rightFunction); // Function<T, Map.Entry<L, R>> toEntry = x -> kv(leftFunction.apply(x), rightFunction.apply(x)); // Collector<T, ?, ? extends Collection<Map.Entry<L, R>>> entryCollector = // Collectors.mapping(toEntry, Collectors.toList()); // return Collectors.collectingAndThen(entryCollector, BiCollection::new); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.stream.BiCollection.toBiCollection; import static java.util.Arrays.asList; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import com.google.common.truth.MultimapSubject;
} @Test public void twoPairsSameKey() { assertKeyValues(BiCollection.of(1, "1.1", 1, "1.2")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1.1", 1, "1.2")) .inOrder(); } @Test public void threePairs() { assertKeyValues(BiCollection.of(1, "one", 2, "two", 3, "three")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "one", 2, "two", 3, "three")) .inOrder(); } @Test public void fourPairs() { assertKeyValues(BiCollection.of(1, "1", 2, "2", 3, "3", 4, "4")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1", 2, "2", 3, "3", 4, "4")) .inOrder(); } @Test public void fivePairs() { assertKeyValues(BiCollection.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5")) .inOrder(); } @Test public void toBiCollectionWithoutCollectorStrategy() { BiCollection<Integer, String> biCollection = ImmutableMap.of(1, "one", 2, "two") .entrySet() .stream()
// Path: mug/src/main/java/com/google/mu/util/stream/BiCollection.java // public static <T, L, R> Collector<T, ?, BiCollection<L, R>> toBiCollection( // Function<? super T, ? extends L> leftFunction, // Function<? super T, ? extends R> rightFunction) { // requireNonNull(leftFunction); // requireNonNull(rightFunction); // Function<T, Map.Entry<L, R>> toEntry = x -> kv(leftFunction.apply(x), rightFunction.apply(x)); // Collector<T, ?, ? extends Collection<Map.Entry<L, R>>> entryCollector = // Collectors.mapping(toEntry, Collectors.toList()); // return Collectors.collectingAndThen(entryCollector, BiCollection::new); // } // Path: mug/src/test/java/com/google/mu/util/stream/BiCollectionTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.util.stream.BiCollection.toBiCollection; import static java.util.Arrays.asList; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import com.google.common.truth.MultimapSubject; } @Test public void twoPairsSameKey() { assertKeyValues(BiCollection.of(1, "1.1", 1, "1.2")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1.1", 1, "1.2")) .inOrder(); } @Test public void threePairs() { assertKeyValues(BiCollection.of(1, "one", 2, "two", 3, "three")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "one", 2, "two", 3, "three")) .inOrder(); } @Test public void fourPairs() { assertKeyValues(BiCollection.of(1, "1", 2, "2", 3, "3", 4, "4")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1", 2, "2", 3, "3", 4, "4")) .inOrder(); } @Test public void fivePairs() { assertKeyValues(BiCollection.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5")) .containsExactlyEntriesIn(ImmutableListMultimap.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5")) .inOrder(); } @Test public void toBiCollectionWithoutCollectorStrategy() { BiCollection<Integer, String> biCollection = ImmutableMap.of(1, "one", 2, "two") .entrySet() .stream()
.collect(toBiCollection(Map.Entry::getKey, Map.Entry::getValue));
google/mug
mug/src/test/java/com/google/mu/util/stream/CasesTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // }
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
package com.google.mu.util.stream; @RunWith(JUnit4.class) public final class CasesTest { @Test public void when_zeroElement() {
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // } // Path: mug/src/test/java/com/google/mu/util/stream/CasesTest.java import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; package com.google.mu.util.stream; @RunWith(JUnit4.class) public final class CasesTest { @Test public void when_zeroElement() {
assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty();
google/mug
mug/src/test/java/com/google/mu/util/stream/CasesTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // }
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
package com.google.mu.util.stream; @RunWith(JUnit4.class) public final class CasesTest { @Test public void when_zeroElement() { assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty(); assertThat(Stream.empty().collect(when(() -> "zero"))).hasValue("zero"); } @Test public void when_oneElement() { assertThat(Stream.of(1).collect(when(i -> i + 1))).hasValue(2); assertThat(Stream.of(1, 2).collect(when(i -> i + 1))).isEmpty(); assertThat(Stream.of(1).collect(when(x -> x == 1, i -> i + 1))).hasValue(2); assertThat(Stream.of(1).collect(when(x -> x == 2, i -> i + 1))).isEmpty(); } @Test public void when_twoElements() { assertThat(Stream.of(2, 3).collect(when((a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3, 4).collect(when((a, b) -> a * b))).isEmpty(); assertThat(Stream.of(2, 3).collect(when((x, y) -> x < y, (a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3).collect(when((x, y) -> x > y, (a, b) -> a * b))).isEmpty(); } @Test public void only_oneElement() {
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // } // Path: mug/src/test/java/com/google/mu/util/stream/CasesTest.java import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; package com.google.mu.util.stream; @RunWith(JUnit4.class) public final class CasesTest { @Test public void when_zeroElement() { assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty(); assertThat(Stream.empty().collect(when(() -> "zero"))).hasValue("zero"); } @Test public void when_oneElement() { assertThat(Stream.of(1).collect(when(i -> i + 1))).hasValue(2); assertThat(Stream.of(1, 2).collect(when(i -> i + 1))).isEmpty(); assertThat(Stream.of(1).collect(when(x -> x == 1, i -> i + 1))).hasValue(2); assertThat(Stream.of(1).collect(when(x -> x == 2, i -> i + 1))).isEmpty(); } @Test public void when_twoElements() { assertThat(Stream.of(2, 3).collect(when((a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3, 4).collect(when((a, b) -> a * b))).isEmpty(); assertThat(Stream.of(2, 3).collect(when((x, y) -> x < y, (a, b) -> a * b))).hasValue(6); assertThat(Stream.of(2, 3).collect(when((x, y) -> x > y, (a, b) -> a * b))).isEmpty(); } @Test public void only_oneElement() {
String result = Stream.of("foo").collect(onlyElement());
google/mug
mug/src/test/java/com/google/mu/util/stream/CasesTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // }
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
} @Test public void only_twoElements() { int result = Stream.of(2, 3).collect(onlyElements((a, b) -> a * b)); assertThat(result).isEqualTo(6); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1).collect(onlyElements((a, b) -> a * b))); assertThat(thrown).hasMessageThat().contains("size: 1"); } @Test public void cases_firstCaseMatch() { String result = Stream.of("foo", "bar").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foobar"); } @Test public void cases_secondCaseMatch() { String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foo"); } @Test public void cases_noMatchingCase() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a)))); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void toTinyContainer_empty() {
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // } // Path: mug/src/test/java/com/google/mu/util/stream/CasesTest.java import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; } @Test public void only_twoElements() { int result = Stream.of(2, 3).collect(onlyElements((a, b) -> a * b)); assertThat(result).isEqualTo(6); IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1).collect(onlyElements((a, b) -> a * b))); assertThat(thrown).hasMessageThat().contains("size: 1"); } @Test public void cases_firstCaseMatch() { String result = Stream.of("foo", "bar").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foobar"); } @Test public void cases_secondCaseMatch() { String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foo"); } @Test public void cases_noMatchingCase() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a)))); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void toTinyContainer_empty() {
assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0);
google/mug
mug/src/test/java/com/google/mu/util/stream/CasesTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // }
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
} @Test public void cases_secondCaseMatch() { String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foo"); } @Test public void cases_noMatchingCase() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a)))); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void toTinyContainer_empty() { assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0); } @Test public void toTinyContainer_oneElement() { assertThat(Stream.of("foo").collect(toTinyContainer()).when(x -> true, "got:"::concat)) .hasValue("got:foo"); } @Test public void toTinyContainer_twoElements() { assertThat(Stream.of(2, 3).collect(toTinyContainer()).when((x, y) -> true, Integer::max)) .hasValue(3); } @Test public void tinyContainer_addAll_fromEmpty() {
// Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T> Collector<T, ?, T> onlyElement() { // return collectingAndThen(toTinyContainer(), TinyContainer::onlyOne); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <T, R> Collector<T, ?, R> onlyElements( // BiFunction<? super T, ? super T, ? extends R> twoElements) { // requireNonNull(twoElements); // return collectingAndThen(toTinyContainer(), c -> c.only(twoElements)); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // @SafeVarargs // public static <T, R> Collector<T, ?, R> cases( // Collector<? super T, ?, ? extends Optional<? extends R>>... cases) { // List<Collector<? super T, ?, ? extends Optional<? extends R>>> caseList = // Arrays.stream(cases).peek(Objects::requireNonNull).collect(toList()); // return collectingAndThen( // toList(), // input -> // caseList.stream() // .map(c -> input.stream().collect(c).orElse(null)) // .filter(v -> v != null) // .findFirst() // .orElseThrow(() -> unexpectedSize(input.size()))); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // public static <R> Collector<Object, ?, Optional<R>> when(Supplier<? extends R> noElement) { // requireNonNull(noElement); // return collectingAndThen( // counting(), c -> c == 0 ? Optional.of(noElement.get()) : Optional.empty()); // } // // Path: mug/src/main/java/com/google/mu/util/stream/Cases.java // static final class TinyContainer<T> { // private T first; // private T second; // private int size = 0; // // static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() { // return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll); // } // // void add(T value) { // if (size == 0) { // first = value; // } else if (size == 1) { // second = value; // } // size++; // } // // // Hate to write this code! But a combiner is upon us whether we want parallel or not. // TinyContainer<T> addAll(TinyContainer<? extends T> that) { // int newSize = size + that.size; // if (that.size > 0) { // add(that.first); // } // if (that.size > 1) { // add(that.second); // } // size = newSize; // return this; // } // // int size() { // return size; // } // // <R> Optional<R> when( // Predicate<? super T> condition, Function<? super T, ? extends R> oneElement) { // return size == 1 && condition.test(first) // ? Optional.of(oneElement.apply(first)) // : Optional.empty(); // } // // <R> Optional<R> when( // BiPredicate<? super T, ? super T> condition, // BiFunction<? super T, ? super T, ? extends R> twoElements) { // return size == 2 && condition.test(first, second) // ? Optional.of(twoElements.apply(first, second)) // : Optional.empty(); // } // // <R> R only(BiFunction<? super T, ? super T, ? extends R> twoElements) { // return when((x, y) -> true, twoElements).orElseThrow(() -> unexpectedSize(size)); // } // // T onlyOne() { // return when(x -> true, identity()).orElseThrow(() -> unexpectedSize(size)); // } // } // Path: mug/src/test/java/com/google/mu/util/stream/CasesTest.java import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer; import static com.google.mu.util.stream.Cases.onlyElement; import static com.google.mu.util.stream.Cases.onlyElements; import static com.google.mu.util.stream.Cases.cases; import static com.google.mu.util.stream.Cases.when; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.NullPointerTester; import com.google.mu.util.stream.Cases.TinyContainer; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; } @Test public void cases_secondCaseMatch() { String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a))); assertThat(result).isEqualTo("foo"); } @Test public void cases_noMatchingCase() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a)))); assertThat(thrown).hasMessageThat().contains("size: 3"); } @Test public void toTinyContainer_empty() { assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0); } @Test public void toTinyContainer_oneElement() { assertThat(Stream.of("foo").collect(toTinyContainer()).when(x -> true, "got:"::concat)) .hasValue("got:foo"); } @Test public void toTinyContainer_twoElements() { assertThat(Stream.of(2, 3).collect(toTinyContainer()).when((x, y) -> true, Integer::max)) .hasValue(3); } @Test public void tinyContainer_addAll_fromEmpty() {
TinyContainer<String> empty = new TinyContainer<>();
google/mug
mug/src/test/java/com/google/mu/util/FunnelTest.java
// Path: mug/src/main/java/com/google/mu/util/Funnel.java // public final class Funnel<T> { // // private int size = 0; // private final List<Batch<?, T>> batches = new ArrayList<>(); // private final Batch<T, T> passthrough = through(Function.identity()); // // /** // * Holds the elements to be converted through a single batch conversion. // * // * @param <F> batch input element type // * @param <T> batch output element type // */ // public static final class Batch<F, T> implements Consumer<F> { // private final Funnel<T> funnel; // private final Function<? super List<F>, ? extends Collection<? extends T>> converter; // private final List<Indexed<F, T>> indexedSources = new ArrayList<>(); // // Batch(Funnel<T> funnel, Function<? super List<F>, ? extends Collection<? extends T>> converter) { // this.funnel = funnel; // this.converter = requireNonNull(converter); // } // // /** Adds {@code source} to be converted. */ // @Override public void accept(F source) { // accept(source, Function.identity()); // } // // /** // * Adds {@code source} to be converted. // * {@code postConversion} will be applied after the batch conversion completes, // * to compute the final result for this input. // */ // public void accept(F source, Function<? super T, ? extends T> postConversion) { // indexedSources.add(new Indexed<>(funnel.size++, source, postConversion)); // } // // /** // * Adds {@code source} to be converted. // * {@code aftereffect} will be applied against the conversion result after the batch completes. // */ // public void accept(F source, Consumer<? super T> aftereffect) { // requireNonNull(aftereffect); // accept(source, v -> { // aftereffect.accept(v); // return v; // }); // } // // void convertInto(ArrayList<T> output) { // if (indexedSources.isEmpty()) { // return; // } // List<F> params = indexedSources.stream().map(i -> i.value).collect(toList()); // List<T> results = new ArrayList<>(converter.apply(params)); // if (params.size() != results.size()) { // throw new IllegalStateException( // converter + " expected to return " + params.size() + " elements for input " // + params + ", but got " + results + " of size " + results.size() + "."); // } // for (int i = 0; i < indexedSources.size(); i++) { // indexedSources.get(i).setAtIndex(results.get(i), output); // } // } // } // // /** // * Returns a {@link Batch} accepting elements that, when {@link #run} is called, // * will be converted together in a batch through {@code converter}. // */ // public <F> Batch<F, T> through( // Function<? super List<F>, ? extends Collection<? extends T>> converter) { // Batch<F, T> batch = new Batch<>(this, converter); // batches.add(batch); // return batch; // } // // /** Adds {@code element} to the funnel. */ // public void add(T element) { // passthrough.accept(element); // } // // /** // * Runs all batch conversions and returns conversion results together with elements {@link #add // * added} as is, in encounter order. // */ // public List<T> run() { // ArrayList<T> output = new ArrayList<>(Collections.nCopies(size, null)); // for (Batch<?, T> batch : batches) { // batch.convertInto(output); // } // return output; // } // // private static final class Indexed<F, T> { // private final int index; // final F value; // private final Function<? super T, ? extends T> converter; // // Indexed(int index, F value, Function<? super T, ? extends T> converter) { // this.index = index; // this.value = requireNonNull(value); // this.converter = requireNonNull(converter); // } // // void setAtIndex(T from, List<? super T> to) { // to.set(index, converter.apply(from)); // } // } // }
import org.mockito.MockitoAnnotations; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.mu.util.Funnel; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; @RunWith(JUnit4.class) public final class FunnelTest {
// Path: mug/src/main/java/com/google/mu/util/Funnel.java // public final class Funnel<T> { // // private int size = 0; // private final List<Batch<?, T>> batches = new ArrayList<>(); // private final Batch<T, T> passthrough = through(Function.identity()); // // /** // * Holds the elements to be converted through a single batch conversion. // * // * @param <F> batch input element type // * @param <T> batch output element type // */ // public static final class Batch<F, T> implements Consumer<F> { // private final Funnel<T> funnel; // private final Function<? super List<F>, ? extends Collection<? extends T>> converter; // private final List<Indexed<F, T>> indexedSources = new ArrayList<>(); // // Batch(Funnel<T> funnel, Function<? super List<F>, ? extends Collection<? extends T>> converter) { // this.funnel = funnel; // this.converter = requireNonNull(converter); // } // // /** Adds {@code source} to be converted. */ // @Override public void accept(F source) { // accept(source, Function.identity()); // } // // /** // * Adds {@code source} to be converted. // * {@code postConversion} will be applied after the batch conversion completes, // * to compute the final result for this input. // */ // public void accept(F source, Function<? super T, ? extends T> postConversion) { // indexedSources.add(new Indexed<>(funnel.size++, source, postConversion)); // } // // /** // * Adds {@code source} to be converted. // * {@code aftereffect} will be applied against the conversion result after the batch completes. // */ // public void accept(F source, Consumer<? super T> aftereffect) { // requireNonNull(aftereffect); // accept(source, v -> { // aftereffect.accept(v); // return v; // }); // } // // void convertInto(ArrayList<T> output) { // if (indexedSources.isEmpty()) { // return; // } // List<F> params = indexedSources.stream().map(i -> i.value).collect(toList()); // List<T> results = new ArrayList<>(converter.apply(params)); // if (params.size() != results.size()) { // throw new IllegalStateException( // converter + " expected to return " + params.size() + " elements for input " // + params + ", but got " + results + " of size " + results.size() + "."); // } // for (int i = 0; i < indexedSources.size(); i++) { // indexedSources.get(i).setAtIndex(results.get(i), output); // } // } // } // // /** // * Returns a {@link Batch} accepting elements that, when {@link #run} is called, // * will be converted together in a batch through {@code converter}. // */ // public <F> Batch<F, T> through( // Function<? super List<F>, ? extends Collection<? extends T>> converter) { // Batch<F, T> batch = new Batch<>(this, converter); // batches.add(batch); // return batch; // } // // /** Adds {@code element} to the funnel. */ // public void add(T element) { // passthrough.accept(element); // } // // /** // * Runs all batch conversions and returns conversion results together with elements {@link #add // * added} as is, in encounter order. // */ // public List<T> run() { // ArrayList<T> output = new ArrayList<>(Collections.nCopies(size, null)); // for (Batch<?, T> batch : batches) { // batch.convertInto(output); // } // return output; // } // // private static final class Indexed<F, T> { // private final int index; // final F value; // private final Function<? super T, ? extends T> converter; // // Indexed(int index, F value, Function<? super T, ? extends T> converter) { // this.index = index; // this.value = requireNonNull(value); // this.converter = requireNonNull(converter); // } // // void setAtIndex(T from, List<? super T> to) { // to.set(index, converter.apply(from)); // } // } // } // Path: mug/src/test/java/com/google/mu/util/FunnelTest.java import org.mockito.MockitoAnnotations; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.mu.util.Funnel; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; @RunWith(JUnit4.class) public final class FunnelTest {
private final Funnel<String> funnel = new Funnel<>();
google/mug
mug/src/test/java/com/google/mu/util/graph/BinaryTreeWalkerTest.java
// Path: mug/src/test/java/com/google/mu/util/graph/BinaryTreeWalkerTest.java // static <T> Node<T> tree(T value) { // return new Node<>(value); // }
import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.graph.BinaryTreeWalkerTest.Tree.tree; import org.junit.Test;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; public class BinaryTreeWalkerTest { @Test public void preOrder_noRoot() { assertThat(Tree.<String>walker().preOrderFrom().map(Tree::value)) .isEmpty(); } @Test public void preOrder_singleNode() {
// Path: mug/src/test/java/com/google/mu/util/graph/BinaryTreeWalkerTest.java // static <T> Node<T> tree(T value) { // return new Node<>(value); // } // Path: mug/src/test/java/com/google/mu/util/graph/BinaryTreeWalkerTest.java import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.graph.BinaryTreeWalkerTest.Tree.tree; import org.junit.Test; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.graph; public class BinaryTreeWalkerTest { @Test public void preOrder_noRoot() { assertThat(Tree.<String>walker().preOrderFrom().map(Tree::value)) .isEmpty(); } @Test public void preOrder_singleNode() {
assertThat(Tree.<String>walker().preOrderFrom(tree("foo")).map(Tree::value))
google/mug
mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // }
import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() {
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // } // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() {
assertKeyValues(
google/mug
mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // }
import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() { assertKeyValues( BiStream.of("a", 1, "c", 2, "b", 3) .mapValues(Function.identity()) .sortedByKeys(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 3, "c", 2)) .inOrder(); } @Test public void testMappedValuesAndSortedByValues() { assertKeyValues( BiStream.of("a", 3, "b", 1, "c", 2) .mapValues(Function.identity()) .sortedByValues(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("b", 1, "c", 2, "a", 3)) .inOrder(); } @Test public void testMappedValuesAndSorted() { assertKeyValues( BiStream.of("b", 10, "a", 11, "a", 22) .mapValues(Function.identity())
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // } // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() { assertKeyValues( BiStream.of("a", 1, "c", 2, "b", 3) .mapValues(Function.identity()) .sortedByKeys(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 3, "c", 2)) .inOrder(); } @Test public void testMappedValuesAndSortedByValues() { assertKeyValues( BiStream.of("a", 3, "b", 1, "c", 2) .mapValues(Function.identity()) .sortedByValues(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("b", 1, "c", 2, "a", 3)) .inOrder(); } @Test public void testMappedValuesAndSorted() { assertKeyValues( BiStream.of("b", 10, "a", 11, "a", 22) .mapValues(Function.identity())
.sorted(comparingValue(Number::intValue).then(comparingKey(Object::toString))))
google/mug
mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // }
import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() { assertKeyValues( BiStream.of("a", 1, "c", 2, "b", 3) .mapValues(Function.identity()) .sortedByKeys(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 3, "c", 2)) .inOrder(); } @Test public void testMappedValuesAndSortedByValues() { assertKeyValues( BiStream.of("a", 3, "b", 1, "c", 2) .mapValues(Function.identity()) .sortedByValues(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("b", 1, "c", 2, "a", 3)) .inOrder(); } @Test public void testMappedValuesAndSorted() { assertKeyValues( BiStream.of("b", 10, "a", 11, "a", 22) .mapValues(Function.identity())
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamTest.java // static<K,V> MultimapSubject assertKeyValues(BiStream<K, V> stream) { // Multimap<?, ?> multimap = stream.collect(new BiCollector<K, V, Multimap<K, V>>() { // @Override // public <E> Collector<E, ?, Multimap<K, V>> splitting(Function<E, K> toKey, Function<E, V> toValue) { // return BiStreamTest.toLinkedListMultimap(toKey,toValue); // } // }); // return assertThat(multimap); // } // Path: mug/src/test/java/com/google/mu/util/stream/BiStreamCompoundTest.java import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static com.google.mu.util.stream.BiStreamTest.assertKeyValues; import static java.util.Comparator.naturalOrder; import java.util.Comparator; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableMultimap; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util.stream; @RunWith(JUnit4.class) public class BiStreamCompoundTest { @Test public void testMappedValuesAndSortedByKeys() { assertKeyValues( BiStream.of("a", 1, "c", 2, "b", 3) .mapValues(Function.identity()) .sortedByKeys(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 3, "c", 2)) .inOrder(); } @Test public void testMappedValuesAndSortedByValues() { assertKeyValues( BiStream.of("a", 3, "b", 1, "c", 2) .mapValues(Function.identity()) .sortedByValues(Comparator.naturalOrder())) .containsExactlyEntriesIn(ImmutableMultimap.of("b", 1, "c", 2, "a", 3)) .inOrder(); } @Test public void testMappedValuesAndSorted() { assertKeyValues( BiStream.of("b", 10, "a", 11, "a", 22) .mapValues(Function.identity())
.sorted(comparingValue(Number::intValue).then(comparingKey(Object::toString))))
google/mug
mug/src/test/java/com/google/mu/function/BiComparatorTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() {
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // Path: mug/src/test/java/com/google/mu/function/BiComparatorTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() {
assertThat(comparing(Integer::sum).compare(1, 3, 2, 2)).isEqualTo(0);
google/mug
mug/src/test/java/com/google/mu/function/BiComparatorTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() { assertThat(comparing(Integer::sum).compare(1, 3, 2, 2)).isEqualTo(0); assertThat(comparing(Integer::sum).compare(1, 3, 0, 5)).isLessThan(0); assertThat(comparing(Integer::sum).compare(1, 4, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByFunction() {
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // Path: mug/src/test/java/com/google/mu/function/BiComparatorTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() { assertThat(comparing(Integer::sum).compare(1, 3, 2, 2)).isEqualTo(0); assertThat(comparing(Integer::sum).compare(1, 3, 0, 5)).isLessThan(0); assertThat(comparing(Integer::sum).compare(1, 4, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByFunction() {
assertThat(comparingKey(Object::toString).compare(1, 3, 2, 2)).isLessThan(0);
google/mug
mug/src/test/java/com/google/mu/function/BiComparatorTest.java
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // }
import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() { assertThat(comparing(Integer::sum).compare(1, 3, 2, 2)).isEqualTo(0); assertThat(comparing(Integer::sum).compare(1, 3, 0, 5)).isLessThan(0); assertThat(comparing(Integer::sum).compare(1, 4, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByFunction() { assertThat(comparingKey(Object::toString).compare(1, 3, 2, 2)).isLessThan(0); assertThat(comparingKey(Object::toString).compare(2, 3, 2, 2)).isEqualTo(0); assertThat(comparingKey(Object::toString).compare(3, 3, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByComparator() { assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(1, "", 2, null)) .isGreaterThan(0); assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(2, "", 2, null)) .isEqualTo(0); assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(2, "", 1, null)) .isLessThan(0); } @Test public void comparingValueByFunction() {
// Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, V, T> BiComparator<K, V> comparing( // BiFunction<? super K, ? super V, ? extends T> function, Comparator<? super T> ordering) { // requireNonNull(function); // requireNonNull(ordering); // return (k1, v1, k2, v2) -> ordering.compare(function.apply(k1, v1), function.apply(k2, v2)); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <K, T extends Comparable<T>> BiComparator<K, Object> comparingKey( // Function<? super K, ? extends T> function) { // return comparingKey(function, naturalOrder()); // } // // Path: mug/src/main/java/com/google/mu/function/BiComparator.java // static <V, T extends Comparable<T>> BiComparator<Object, V> comparingValue( // Function<? super V, ? extends T> function) { // return comparingValue(function, naturalOrder()); // } // Path: mug/src/test/java/com/google/mu/function/BiComparatorTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.mu.function.BiComparator.comparing; import static com.google.mu.function.BiComparator.comparingKey; import static com.google.mu.function.BiComparator.comparingValue; import static java.util.Comparator.naturalOrder; import static java.util.Comparator.reverseOrder; import static java.util.Objects.requireNonNull; import java.util.Comparator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.testing.NullPointerTester; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.function; @RunWith(JUnit4.class) public class BiComparatorTest { @Test public void comparingByFunction() { assertThat(comparing(Integer::sum).compare(1, 3, 2, 2)).isEqualTo(0); assertThat(comparing(Integer::sum).compare(1, 3, 0, 5)).isLessThan(0); assertThat(comparing(Integer::sum).compare(1, 4, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByFunction() { assertThat(comparingKey(Object::toString).compare(1, 3, 2, 2)).isLessThan(0); assertThat(comparingKey(Object::toString).compare(2, 3, 2, 2)).isEqualTo(0); assertThat(comparingKey(Object::toString).compare(3, 3, 2, 2)).isGreaterThan(0); } @Test public void comparingKeyByComparator() { assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(1, "", 2, null)) .isGreaterThan(0); assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(2, "", 2, null)) .isEqualTo(0); assertThat(BiComparator.<Integer>comparingKey(reverseOrder()).compare(2, "", 1, null)) .isLessThan(0); } @Test public void comparingValueByFunction() {
assertThat(comparingValue(Object::toString).compare(1, 3, 2, 2)).isGreaterThan(0);
google/mug
mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // }
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester;
@Test public void nullElementsAreOk() { assertThat(MoreStreams.dice(asList(null, null).stream(), 2).collect(toList())) .containsExactly(asList(null, null)); } @Test public void maxSizeIsLargerThanDataSize() { assertThat(MoreStreams.dice(asList(1, 2).stream(), Integer.MAX_VALUE).collect(toList())) .containsExactly(asList(1, 2)); } @Test public void largeMaxSizeWithUnknownSize() { assumeTrue(Stream.generate(() -> 1).limit(3).spliterator().getExactSizeIfKnown() == -1); assertThat(MoreStreams.dice(Stream.generate(() -> 1).limit(3), Integer.MAX_VALUE). limit(3).collect(toList())) .containsExactly(asList(1, 1, 1)); } @Test public void invalidMaxSize() { assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), -1)); assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), 0)); } @Test public void testThrough() { List<String> to = new ArrayList<>(); MoreStreams.iterateThrough(Stream.of(1, 2).map(Object::toString), to::add); assertThat(to).containsExactly("1", "2"); } @Test public void testIndexesFrom() {
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // Path: mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; @Test public void nullElementsAreOk() { assertThat(MoreStreams.dice(asList(null, null).stream(), 2).collect(toList())) .containsExactly(asList(null, null)); } @Test public void maxSizeIsLargerThanDataSize() { assertThat(MoreStreams.dice(asList(1, 2).stream(), Integer.MAX_VALUE).collect(toList())) .containsExactly(asList(1, 2)); } @Test public void largeMaxSizeWithUnknownSize() { assumeTrue(Stream.generate(() -> 1).limit(3).spliterator().getExactSizeIfKnown() == -1); assertThat(MoreStreams.dice(Stream.generate(() -> 1).limit(3), Integer.MAX_VALUE). limit(3).collect(toList())) .containsExactly(asList(1, 1, 1)); } @Test public void invalidMaxSize() { assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), -1)); assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), 0)); } @Test public void testThrough() { List<String> to = new ArrayList<>(); MoreStreams.iterateThrough(Stream.of(1, 2).map(Object::toString), to::add); assertThat(to).containsExactly("1", "2"); } @Test public void testIndexesFrom() {
assertThat(indexesFrom(1).limit(3)).containsExactly(1, 2, 3).inOrder();
google/mug
mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // }
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester;
assertThat(MoreStreams.dice(Stream.generate(() -> 1).limit(3), Integer.MAX_VALUE). limit(3).collect(toList())) .containsExactly(asList(1, 1, 1)); } @Test public void invalidMaxSize() { assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), -1)); assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), 0)); } @Test public void testThrough() { List<String> to = new ArrayList<>(); MoreStreams.iterateThrough(Stream.of(1, 2).map(Object::toString), to::add); assertThat(to).containsExactly("1", "2"); } @Test public void testIndexesFrom() { assertThat(indexesFrom(1).limit(3)).containsExactly(1, 2, 3).inOrder(); assertThat(indexesFrom(Integer.MAX_VALUE).limit(3)) .containsExactly(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE + 1).inOrder(); } @Test public void testIndexesFrom_longIndex() { assertThat(indexesFrom(1L).limit(3)).containsExactly(1L, 2L, 3L).inOrder(); assertThat(indexesFrom(Long.MAX_VALUE).limit(3)) .containsExactly(Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE + 1).inOrder(); } @Test public void removingFromQueue_empty() { Queue<String> queue = new ArrayDeque<>();
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // Path: mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; assertThat(MoreStreams.dice(Stream.generate(() -> 1).limit(3), Integer.MAX_VALUE). limit(3).collect(toList())) .containsExactly(asList(1, 1, 1)); } @Test public void invalidMaxSize() { assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), -1)); assertThrows(IllegalArgumentException.class, () -> MoreStreams.dice(asList(1).stream(), 0)); } @Test public void testThrough() { List<String> to = new ArrayList<>(); MoreStreams.iterateThrough(Stream.of(1, 2).map(Object::toString), to::add); assertThat(to).containsExactly("1", "2"); } @Test public void testIndexesFrom() { assertThat(indexesFrom(1).limit(3)).containsExactly(1, 2, 3).inOrder(); assertThat(indexesFrom(Integer.MAX_VALUE).limit(3)) .containsExactly(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE + 1).inOrder(); } @Test public void testIndexesFrom_longIndex() { assertThat(indexesFrom(1L).limit(3)).containsExactly(1L, 2L, 3L).inOrder(); assertThat(indexesFrom(Long.MAX_VALUE).limit(3)) .containsExactly(Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE + 1).inOrder(); } @Test public void removingFromQueue_empty() { Queue<String> queue = new ArrayDeque<>();
assertThat(whileNotNull(queue::poll)).isEmpty();
google/mug
mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // }
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester;
@Test public void withSideEffect_parallel() { ImmutableList<Integer> source = indexesFrom(1).limit(100).collect(toImmutableList()); Set<Integer> set = ConcurrentHashMap.newKeySet(); Stream<Integer> stream = MoreStreams.withSideEffect(source.stream(), set::add); assertThat(stream.isParallel()).isFalse(); assertThat(set).isEmpty(); assertThat(stream.parallel()).containsExactlyElementsIn(source); assertThat(set).containsExactlyElementsIn(source); } @Test public void testNulls() throws Exception { NullPointerTester tester = new NullPointerTester(); asList(MoreStreams.class.getDeclaredMethods()).stream() .filter(m -> m.getName().equals("generate")) .forEach(tester::ignore); tester.testAllPublicStaticMethods(MoreStreams.class); new ClassSanityTester().forAllPublicStaticMethods(MoreStreams.class).testNulls(); } @Test public void withSideEffectInOrder() { int num = 10000; ImmutableList<Integer> source = indexesFrom(1).limit(num).collect(toImmutableList()); List<Integer> peeked = Collections.synchronizedList(new ArrayList<>()); List<Integer> result = Collections.synchronizedList(new ArrayList<>()); MoreStreams.withSideEffect(source.stream(), peeked::add).parallel().forEachOrdered(result::add); assertThat(result).containsExactlyElementsIn(source).inOrder(); assertThat(peeked).containsExactlyElementsIn(source).inOrder(); } @Test public void testGroupConsecutive_byPredicate() {
// Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T, R> Stream<R> groupConsecutive( // Stream<T> stream, // BiPredicate<? super T, ? super T> sameGroup, // Collector<? super T, ?, R> groupCollector) { // return biStream(stream).groupConsecutiveIf(sameGroup, groupCollector); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static Stream<Integer> indexesFrom(int firstIndex) { // return IntStream.iterate(firstIndex, i -> i + 1).boxed(); // } // // Path: mug/src/main/java/com/google/mu/util/stream/MoreStreams.java // public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) { // requireNonNull(supplier); // return StreamSupport.stream( // new Spliterator<T>() { // @Override public boolean tryAdvance(Consumer<? super T> action) { // T generated = supplier.get(); // if (generated == null) { // return false; // } // action.accept(generated); // return true; // } // @Override public int characteristics() { // return Spliterator.NONNULL | Spliterator.ORDERED; // } // @Override public long estimateSize() { // return Long.MAX_VALUE; // } // @Override public Spliterator<T> trySplit() { // return null; // } // }, // false); // } // Path: mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.stream.MoreStreams.groupConsecutive; import static com.google.mu.util.stream.MoreStreams.indexesFrom; import static com.google.mu.util.stream.MoreStreams.whileNotNull; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.Spliterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; @Test public void withSideEffect_parallel() { ImmutableList<Integer> source = indexesFrom(1).limit(100).collect(toImmutableList()); Set<Integer> set = ConcurrentHashMap.newKeySet(); Stream<Integer> stream = MoreStreams.withSideEffect(source.stream(), set::add); assertThat(stream.isParallel()).isFalse(); assertThat(set).isEmpty(); assertThat(stream.parallel()).containsExactlyElementsIn(source); assertThat(set).containsExactlyElementsIn(source); } @Test public void testNulls() throws Exception { NullPointerTester tester = new NullPointerTester(); asList(MoreStreams.class.getDeclaredMethods()).stream() .filter(m -> m.getName().equals("generate")) .forEach(tester::ignore); tester.testAllPublicStaticMethods(MoreStreams.class); new ClassSanityTester().forAllPublicStaticMethods(MoreStreams.class).testNulls(); } @Test public void withSideEffectInOrder() { int num = 10000; ImmutableList<Integer> source = indexesFrom(1).limit(num).collect(toImmutableList()); List<Integer> peeked = Collections.synchronizedList(new ArrayList<>()); List<Integer> result = Collections.synchronizedList(new ArrayList<>()); MoreStreams.withSideEffect(source.stream(), peeked::add).parallel().forEachOrdered(result::add); assertThat(result).containsExactlyElementsIn(source).inOrder(); assertThat(peeked).containsExactlyElementsIn(source).inOrder(); } @Test public void testGroupConsecutive_byPredicate() {
assertThat(groupConsecutive(Stream.of(10, 20, 9, 8), (a, b) -> a < b, toList()))
google/mug
mug/src/test/java/com/google/mu/util/MoreCollectionsTest.java
// Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findFirstElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() < 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findOnlyElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() != 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // }
import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.MoreCollections.findFirstElements; import static com.google.mu.util.MoreCollections.findOnlyElements; import static java.util.Arrays.asList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector;
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; @RunWith(TestParameterInjector.class) public class MoreCollectionsTest { @TestParameter private CollectionType makeCollection; @Test public void testFindOnlyTwoElements() {
// Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findFirstElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() < 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findOnlyElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() != 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // Path: mug/src/test/java/com/google/mu/util/MoreCollectionsTest.java import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.MoreCollections.findFirstElements; import static com.google.mu.util.MoreCollections.findOnlyElements; import static java.util.Arrays.asList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; /***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; @RunWith(TestParameterInjector.class) public class MoreCollectionsTest { @TestParameter private CollectionType makeCollection; @Test public void testFindOnlyTwoElements() {
assertThat(findOnlyElements(makeCollection.of(1, 10), Integer::sum)).hasValue(11);
google/mug
mug/src/test/java/com/google/mu/util/MoreCollectionsTest.java
// Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findFirstElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() < 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findOnlyElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() != 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // }
import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.MoreCollections.findFirstElements; import static com.google.mu.util.MoreCollections.findOnlyElements; import static java.util.Arrays.asList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector;
assertThat(findOnlyElements(makeCollection.of(1, 3, 5), (a, b, c) -> a + b + c)).hasValue(9); assertThat(findOnlyElements(makeCollection.of(1, 2), (a, b, c) -> a + b + c)).isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4), (a, b, c) -> a + b + c)).isEmpty(); } @Test public void testFindOnlyFourElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7), (a, b, c, d) -> a + b + c + d)).hasValue(16); assertThat(findOnlyElements(makeCollection.of(1, 2, 3), (a, b, c, d) -> a + b + c + d)).isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5), (a, b, c, d) -> a + b + c)).isEmpty(); } @Test public void testFindOnlyFiveElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7, 9), (a, b, c, d, e) -> a + b + c + d + e)) .hasValue(25); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4), (a, b, c, d, e) -> a + b + c + d + e)) .isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5, 6), (a, b, c, d, e) -> a + b + c + e)) .isEmpty(); } @Test public void testFindOnlySixElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7, 9, 11), (a, b, c, d, e, f) -> a + b + c + d + e + f)) .hasValue(36); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5), (a, b, c, d, e, f) -> a + b + c + d + e + f)) .isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5, 6, 7), (a, b, c, d, e, f) -> a + b + c + e + f)) .isEmpty(); } @Test public void testFindFirstTwoElements() {
// Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findFirstElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() < 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // // Path: mug/src/main/java/com/google/mu/util/MoreCollections.java // public static <T, R> Optional<R> findOnlyElements( // Collection<T> collection, BiFunction<? super T, ? super T, ? extends R> found) { // requireNonNull(found); // if (collection.size() != 2) return Optional.empty(); // if (collection instanceof List && collection instanceof RandomAccess) { // List<T> list = (List<T>) collection; // return Optional.of(found.apply(list.get(0), list.get(1))); // } // Iterator<T> it = collection.iterator(); // return Optional.of(found.apply(it.next(), it.next())); // } // Path: mug/src/test/java/com/google/mu/util/MoreCollectionsTest.java import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.MoreCollections.findFirstElements; import static com.google.mu.util.MoreCollections.findOnlyElements; import static java.util.Arrays.asList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; assertThat(findOnlyElements(makeCollection.of(1, 3, 5), (a, b, c) -> a + b + c)).hasValue(9); assertThat(findOnlyElements(makeCollection.of(1, 2), (a, b, c) -> a + b + c)).isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4), (a, b, c) -> a + b + c)).isEmpty(); } @Test public void testFindOnlyFourElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7), (a, b, c, d) -> a + b + c + d)).hasValue(16); assertThat(findOnlyElements(makeCollection.of(1, 2, 3), (a, b, c, d) -> a + b + c + d)).isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5), (a, b, c, d) -> a + b + c)).isEmpty(); } @Test public void testFindOnlyFiveElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7, 9), (a, b, c, d, e) -> a + b + c + d + e)) .hasValue(25); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4), (a, b, c, d, e) -> a + b + c + d + e)) .isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5, 6), (a, b, c, d, e) -> a + b + c + e)) .isEmpty(); } @Test public void testFindOnlySixElements() { assertThat(findOnlyElements(makeCollection.of(1, 3, 5, 7, 9, 11), (a, b, c, d, e, f) -> a + b + c + d + e + f)) .hasValue(36); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5), (a, b, c, d, e, f) -> a + b + c + d + e + f)) .isEmpty(); assertThat(findOnlyElements(makeCollection.of(1, 2, 3, 4, 5, 6, 7), (a, b, c, d, e, f) -> a + b + c + e + f)) .isEmpty(); } @Test public void testFindFirstTwoElements() {
assertThat(findFirstElements(makeCollection.of(1, 2), (a, b) -> a + b)).hasValue(3);
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/commandline/CommandLineBuilderTest.java
// Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java // public class MockShell // extends Shell // { // public Object[] args; // // public String commandName; // // public MockShell() throws CommandException { // super(new IO()); // } // // public Object execute(Object... args) throws Exception { // this.args = args; // // return 0; // } // // public Object execute(String commandName, Object[] args) throws Exception { // this.commandName = commandName; // this.args = args; // // return 0; // } // }
import junit.framework.TestCase; import org.apache.geronimo.gshell.MockShell;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Unit tests for the {@link CommandLineBuilder} class. * * @version $Rev$ $Date$ */ public class CommandLineBuilderTest extends TestCase { public void testConstructor() throws Exception { try { new CommandLineBuilder(null); fail("Accepted null argument"); } catch (IllegalArgumentException expected) { // ignore } } public void testSimple() throws Exception {
// Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java // public class MockShell // extends Shell // { // public Object[] args; // // public String commandName; // // public MockShell() throws CommandException { // super(new IO()); // } // // public Object execute(Object... args) throws Exception { // this.args = args; // // return 0; // } // // public Object execute(String commandName, Object[] args) throws Exception { // this.commandName = commandName; // this.args = args; // // return 0; // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/commandline/CommandLineBuilderTest.java import junit.framework.TestCase; import org.apache.geronimo.gshell.MockShell; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Unit tests for the {@link CommandLineBuilder} class. * * @version $Rev$ $Date$ */ public class CommandLineBuilderTest extends TestCase { public void testConstructor() throws Exception { try { new CommandLineBuilder(null); fail("Accepted null argument"); } catch (IllegalArgumentException expected) { // ignore } } public void testSimple() throws Exception {
MockShell shell = new MockShell();
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/CompletionHandlerImpl.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/MessageSource.java // public interface MessageSource // { // String getMessage(String code); // // String getMessage(String code, Object... args); // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/command/MessageSourceImpl.java // public class MessageSourceImpl // implements MessageSource // { // // // // TODO: Add a global message set that is overridden by command messages // // // // private final ResourceBundle bundle; // // public MessageSourceImpl(final String name) { // if (name == null) { // throw new NullArgumentException("name"); // } // // bundle = ResourceBundle.getBundle(name); // } // // public String getMessage(final String code) { // return bundle.getString(code); // } // // public String getMessage(final String code, final Object... args) { // String format = getMessage(code); // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format(format, args); // // return sb.toString(); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.gshell.command.MessageSource; import org.apache.geronimo.gshell.command.MessageSourceImpl; import jline.CompletionHandler; import jline.ConsoleReader; import jline.CursorBuffer; import java.util.List; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.ArrayList; import java.io.IOException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; // // NOTE: Based on jline.CandidateListCompletionHandler. CLCH that comes with // jLine 0.9.5 has a bug that never displays the completion list. When that // is fixed, then this class can be removed. // /** * A candindate list completion handler (that actually works). * * <p> * Follows the style of Bash. * * @version $Rev$ $Date$ */ public class CompletionHandlerImpl implements CompletionHandler { private static final Log log = LogFactory.getLog(CompletionHandlerImpl.class);
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/MessageSource.java // public interface MessageSource // { // String getMessage(String code); // // String getMessage(String code, Object... args); // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/command/MessageSourceImpl.java // public class MessageSourceImpl // implements MessageSource // { // // // // TODO: Add a global message set that is overridden by command messages // // // // private final ResourceBundle bundle; // // public MessageSourceImpl(final String name) { // if (name == null) { // throw new NullArgumentException("name"); // } // // bundle = ResourceBundle.getBundle(name); // } // // public String getMessage(final String code) { // return bundle.getString(code); // } // // public String getMessage(final String code, final Object... args) { // String format = getMessage(code); // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format(format, args); // // return sb.toString(); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/CompletionHandlerImpl.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.gshell.command.MessageSource; import org.apache.geronimo.gshell.command.MessageSourceImpl; import jline.CompletionHandler; import jline.ConsoleReader; import jline.CursorBuffer; import java.util.List; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.ArrayList; import java.io.IOException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; // // NOTE: Based on jline.CandidateListCompletionHandler. CLCH that comes with // jLine 0.9.5 has a bug that never displays the completion list. When that // is fixed, then this class can be removed. // /** * A candindate list completion handler (that actually works). * * <p> * Follows the style of Bash. * * @version $Rev$ $Date$ */ public class CompletionHandlerImpl implements CompletionHandler { private static final Log log = LogFactory.getLog(CompletionHandlerImpl.class);
private static MessageSource messages = new MessageSourceImpl(CompletionHandlerImpl.class.getName());
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/CompletionHandlerImpl.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/MessageSource.java // public interface MessageSource // { // String getMessage(String code); // // String getMessage(String code, Object... args); // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/command/MessageSourceImpl.java // public class MessageSourceImpl // implements MessageSource // { // // // // TODO: Add a global message set that is overridden by command messages // // // // private final ResourceBundle bundle; // // public MessageSourceImpl(final String name) { // if (name == null) { // throw new NullArgumentException("name"); // } // // bundle = ResourceBundle.getBundle(name); // } // // public String getMessage(final String code) { // return bundle.getString(code); // } // // public String getMessage(final String code, final Object... args) { // String format = getMessage(code); // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format(format, args); // // return sb.toString(); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.gshell.command.MessageSource; import org.apache.geronimo.gshell.command.MessageSourceImpl; import jline.CompletionHandler; import jline.ConsoleReader; import jline.CursorBuffer; import java.util.List; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.ArrayList; import java.io.IOException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; // // NOTE: Based on jline.CandidateListCompletionHandler. CLCH that comes with // jLine 0.9.5 has a bug that never displays the completion list. When that // is fixed, then this class can be removed. // /** * A candindate list completion handler (that actually works). * * <p> * Follows the style of Bash. * * @version $Rev$ $Date$ */ public class CompletionHandlerImpl implements CompletionHandler { private static final Log log = LogFactory.getLog(CompletionHandlerImpl.class);
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/MessageSource.java // public interface MessageSource // { // String getMessage(String code); // // String getMessage(String code, Object... args); // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/command/MessageSourceImpl.java // public class MessageSourceImpl // implements MessageSource // { // // // // TODO: Add a global message set that is overridden by command messages // // // // private final ResourceBundle bundle; // // public MessageSourceImpl(final String name) { // if (name == null) { // throw new NullArgumentException("name"); // } // // bundle = ResourceBundle.getBundle(name); // } // // public String getMessage(final String code) { // return bundle.getString(code); // } // // public String getMessage(final String code, final Object... args) { // String format = getMessage(code); // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format(format, args); // // return sb.toString(); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/CompletionHandlerImpl.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.geronimo.gshell.command.MessageSource; import org.apache.geronimo.gshell.command.MessageSourceImpl; import jline.CompletionHandler; import jline.ConsoleReader; import jline.CursorBuffer; import java.util.List; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.ArrayList; import java.io.IOException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; // // NOTE: Based on jline.CandidateListCompletionHandler. CLCH that comes with // jLine 0.9.5 has a bug that never displays the completion list. When that // is fixed, then this class can be removed. // /** * A candindate list completion handler (that actually works). * * <p> * Follows the style of Bash. * * @version $Rev$ $Date$ */ public class CompletionHandlerImpl implements CompletionHandler { private static final Log log = LogFactory.getLog(CompletionHandlerImpl.class);
private static MessageSource messages = new MessageSourceImpl(CompletionHandlerImpl.class.getName());
apache/geronimo-gshell
gshell-commands/gshell-vfs-commands/src/main/java/org/apache/geronimo/gshell/commands/vfs/CopyCommand.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Command.java // public interface Command // { // /** Standard command success status code. */ // int SUCCESS = 0; // // /** Standard command failure status code. */ // int FAILURE = -1; // // String getName(); // // void init(CommandContext context); // throws Exception ? // // Object execute(Object... args) throws Exception; // // void abort(); // throws Exception ? // // void destroy(); // throws Exception ? // // // // // 'help' command helpers to allow external inspection of command help // // // // // String usage() // single line used to render help page // // // String about() // single line to describe the command // // // String help() // full help page (includes usage + about + command line options) // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // }
import org.apache.geronimo.gshell.command.Command; import org.apache.geronimo.gshell.command.CommandException; import org.apache.commons.cli.CommandLine; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.FileUtil;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.vfs; /** * Copy files. * * @version $Rev$ $Date$ */ public class CopyCommand extends VFSCommandSupport { public CopyCommand() { super("copy"); } protected String getUsage() { return super.getUsage() + " <source> <target>"; }
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Command.java // public interface Command // { // /** Standard command success status code. */ // int SUCCESS = 0; // // /** Standard command failure status code. */ // int FAILURE = -1; // // String getName(); // // void init(CommandContext context); // throws Exception ? // // Object execute(Object... args) throws Exception; // // void abort(); // throws Exception ? // // void destroy(); // throws Exception ? // // // // // 'help' command helpers to allow external inspection of command help // // // // // String usage() // single line used to render help page // // // String about() // single line to describe the command // // // String help() // full help page (includes usage + about + command line options) // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // } // Path: gshell-commands/gshell-vfs-commands/src/main/java/org/apache/geronimo/gshell/commands/vfs/CopyCommand.java import org.apache.geronimo.gshell.command.Command; import org.apache.geronimo.gshell.command.CommandException; import org.apache.commons.cli.CommandLine; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.FileUtil; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.vfs; /** * Copy files. * * @version $Rev$ $Date$ */ public class CopyCommand extends VFSCommandSupport { public CopyCommand() { super("copy"); } protected String getUsage() { return super.getUsage() + " <source> <target>"; }
protected boolean processCommandLine(final CommandLine line) throws CommandException {
apache/geronimo-gshell
gshell-commands/gshell-vfs-commands/src/main/java/org/apache/geronimo/gshell/commands/vfs/CopyCommand.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Command.java // public interface Command // { // /** Standard command success status code. */ // int SUCCESS = 0; // // /** Standard command failure status code. */ // int FAILURE = -1; // // String getName(); // // void init(CommandContext context); // throws Exception ? // // Object execute(Object... args) throws Exception; // // void abort(); // throws Exception ? // // void destroy(); // throws Exception ? // // // // // 'help' command helpers to allow external inspection of command help // // // // // String usage() // single line used to render help page // // // String about() // single line to describe the command // // // String help() // full help page (includes usage + about + command line options) // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // }
import org.apache.geronimo.gshell.command.Command; import org.apache.geronimo.gshell.command.CommandException; import org.apache.commons.cli.CommandLine; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.FileUtil;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.vfs; /** * Copy files. * * @version $Rev$ $Date$ */ public class CopyCommand extends VFSCommandSupport { public CopyCommand() { super("copy"); } protected String getUsage() { return super.getUsage() + " <source> <target>"; } protected boolean processCommandLine(final CommandLine line) throws CommandException { assert line != null; String[] args = line.getArgs(); // Need exactly 2 args if (args.length != 2) { return true; } return false; } protected Object doExecute(Object[] args) throws Exception { assert args != null; FileSystemManager fsm = getFileSystemManager(); FileObject source = fsm.resolveFile(String.valueOf(args[0])); FileObject target = fsm.resolveFile(String.valueOf(args[1])); log.info("Copying " + source + " -> " + target); FileUtil.copyContent(source, target);
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Command.java // public interface Command // { // /** Standard command success status code. */ // int SUCCESS = 0; // // /** Standard command failure status code. */ // int FAILURE = -1; // // String getName(); // // void init(CommandContext context); // throws Exception ? // // Object execute(Object... args) throws Exception; // // void abort(); // throws Exception ? // // void destroy(); // throws Exception ? // // // // // 'help' command helpers to allow external inspection of command help // // // // // String usage() // single line used to render help page // // // String about() // single line to describe the command // // // String help() // full help page (includes usage + about + command line options) // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // } // Path: gshell-commands/gshell-vfs-commands/src/main/java/org/apache/geronimo/gshell/commands/vfs/CopyCommand.java import org.apache.geronimo.gshell.command.Command; import org.apache.geronimo.gshell.command.CommandException; import org.apache.commons.cli.CommandLine; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.FileUtil; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.vfs; /** * Copy files. * * @version $Rev$ $Date$ */ public class CopyCommand extends VFSCommandSupport { public CopyCommand() { super("copy"); } protected String getUsage() { return super.getUsage() + " <source> <target>"; } protected boolean processCommandLine(final CommandLine line) throws CommandException { assert line != null; String[] args = line.getArgs(); // Need exactly 2 args if (args.length != 2) { return true; } return false; } protected Object doExecute(Object[] args) throws Exception { assert args != null; FileSystemManager fsm = getFileSystemManager(); FileObject source = fsm.resolveFile(String.valueOf(args[0])); FileObject target = fsm.resolveFile(String.valueOf(args[1])); log.info("Copying " + source + " -> " + target); FileUtil.copyContent(source, target);
return Command.SUCCESS;
apache/geronimo-gshell
gshell-server/gshell-server-ssh/src/main/java/org/apache/geronimo/gshell/server/ssh/ConsoleFactoryImpl.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/ConsoleFactory.java // public interface ConsoleFactory // { // // // // TODO: Need to hookup ConsoleFactory to allow instances to be created by components // // (like the script command) with out needing to know which is the right flavor // // // // Console create(InputStream input, OutputStream output) throws Exception; // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/Console.java // public interface Console // { // String readLine(final String prompt) throws IOException; // // IO getIO(); // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/console/JLineConsole.java // public class JLineConsole // implements Console // { // private static final Log log = LogFactory.getLog(JLineConsole.class); // // private final IO io; // // private final ConsoleReader reader; // // public JLineConsole(final IO io, final ConsoleReader reader) throws IOException { // if (io == null) { // throw new NullArgumentException("io"); // } // if (reader == null) { // throw new NullArgumentException("reader"); // } // // this.io = io; // this.reader = reader; // } // // public JLineConsole(final IO io) throws IOException { // if (io == null) { // throw new NullArgumentException("io"); // } // // this.io = io; // this.reader = new ConsoleReader(io.inputStream, io.out); // } // // public String readLine(final String prompt) throws IOException { // assert prompt != null; // // if (log.isDebugEnabled()) { // log.debug("Reading line, w/prompt: " + prompt); // } // // return reader.readLine(prompt); // } // // public IO getIO() { // return io; // } // // public ConsoleReader getReader() { // return reader; // } // }
import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.geronimo.gshell.console.ConsoleFactory; import org.apache.geronimo.gshell.console.Console; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.console.JLineConsole; import jline.ConsoleReader;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.server.ssh; /** * ??? * * @version $Rev$ $Date$ */ public class ConsoleFactoryImpl implements ConsoleFactory { private static final Log log = LogFactory.getLog(ConsoleFactoryImpl.class);
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/ConsoleFactory.java // public interface ConsoleFactory // { // // // // TODO: Need to hookup ConsoleFactory to allow instances to be created by components // // (like the script command) with out needing to know which is the right flavor // // // // Console create(InputStream input, OutputStream output) throws Exception; // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/Console.java // public interface Console // { // String readLine(final String prompt) throws IOException; // // IO getIO(); // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/console/JLineConsole.java // public class JLineConsole // implements Console // { // private static final Log log = LogFactory.getLog(JLineConsole.class); // // private final IO io; // // private final ConsoleReader reader; // // public JLineConsole(final IO io, final ConsoleReader reader) throws IOException { // if (io == null) { // throw new NullArgumentException("io"); // } // if (reader == null) { // throw new NullArgumentException("reader"); // } // // this.io = io; // this.reader = reader; // } // // public JLineConsole(final IO io) throws IOException { // if (io == null) { // throw new NullArgumentException("io"); // } // // this.io = io; // this.reader = new ConsoleReader(io.inputStream, io.out); // } // // public String readLine(final String prompt) throws IOException { // assert prompt != null; // // if (log.isDebugEnabled()) { // log.debug("Reading line, w/prompt: " + prompt); // } // // return reader.readLine(prompt); // } // // public IO getIO() { // return io; // } // // public ConsoleReader getReader() { // return reader; // } // } // Path: gshell-server/gshell-server-ssh/src/main/java/org/apache/geronimo/gshell/server/ssh/ConsoleFactoryImpl.java import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.geronimo.gshell.console.ConsoleFactory; import org.apache.geronimo.gshell.console.Console; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.console.JLineConsole; import jline.ConsoleReader; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.server.ssh; /** * ??? * * @version $Rev$ $Date$ */ public class ConsoleFactoryImpl implements ConsoleFactory { private static final Log log = LogFactory.getLog(ConsoleFactoryImpl.class);
public Console create(final InputStream in, final OutputStream out) throws Exception {
apache/geronimo-gshell
gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/util/PumpStreamHandler.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // }
import org.apache.geronimo.gshell.console.IO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.standard.util; // // Based on Apache Ant 1.6.5 // /** * Copies standard output and error of children streams to standard output and error of the parent. * * @version $Rev$ $Date$ */ public class PumpStreamHandler { private static final Log log = LogFactory.getLog(PumpStreamHandler.class); private InputStream in; private OutputStream out; private OutputStream err; private Thread outputThread; private Thread errorThread; private StreamPumper inputPump; // // NOTE: May want to use a ThreadPool here, 3 threads per/pair seems kinda expensive :-( // public PumpStreamHandler(final InputStream in, final OutputStream out, final OutputStream err) { assert in != null; assert out != null; assert err != null; this.in = in; this.out = out; this.err = err; }
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // Path: gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/util/PumpStreamHandler.java import org.apache.geronimo.gshell.console.IO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.standard.util; // // Based on Apache Ant 1.6.5 // /** * Copies standard output and error of children streams to standard output and error of the parent. * * @version $Rev$ $Date$ */ public class PumpStreamHandler { private static final Log log = LogFactory.getLog(PumpStreamHandler.class); private InputStream in; private OutputStream out; private OutputStream err; private Thread outputThread; private Thread errorThread; private StreamPumper inputPump; // // NOTE: May want to use a ThreadPool here, 3 threads per/pair seems kinda expensive :-( // public PumpStreamHandler(final InputStream in, final OutputStream out, final OutputStream err) { assert in != null; assert out != null; assert err != null; this.in = in; this.out = out; this.err = err; }
public PumpStreamHandler(final IO io) {
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // }
import org.apache.geronimo.gshell.command.CommandException; import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Mock {@link Shell}. * * @version $Rev$ $Date$ */ public class MockShell extends Shell { public Object[] args; public String commandName;
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java import org.apache.geronimo.gshell.command.CommandException; import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Mock {@link Shell}. * * @version $Rev$ $Date$ */ public class MockShell extends Shell { public Object[] args; public String commandName;
public MockShell() throws CommandException {
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // }
import org.apache.geronimo.gshell.command.CommandException; import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Mock {@link Shell}. * * @version $Rev$ $Date$ */ public class MockShell extends Shell { public Object[] args; public String commandName; public MockShell() throws CommandException {
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandException.java // public class CommandException // extends Exception // { // ///CLOVER:OFF // // public CommandException(String msg) { // super(msg); // } // // public CommandException(String msg, Throwable cause) { // super(msg, cause); // } // // public CommandException(Throwable cause) { // super(cause); // } // // public CommandException() { // super(); // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java import org.apache.geronimo.gshell.command.CommandException; import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Mock {@link Shell}. * * @version $Rev$ $Date$ */ public class MockShell extends Shell { public Object[] args; public String commandName; public MockShell() throws CommandException {
super(new IO());
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/CommandLineBuilder.java
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java // public class Shell // { // // // // TODO: Introduce Shell interface? // // // // private static final Log log = LogFactory.getLog(Shell.class); // // private final IO io; // // private final ShellContainer shellContainer = new ShellContainer(); // // private final CommandManager commandManager; // // private final CommandLineBuilder commandLineBuilder; // // private final Variables variables = new VariablesImpl(); // // public Shell(final IO io) throws CommandException { // if (io == null) { // throw new NullArgumentException("io"); // } // // this.io = io; // // shellContainer.registerComponentInstance(this); // shellContainer.registerComponentImplementation(CommandManagerImpl.class); // shellContainer.registerComponentImplementation(CommandLineBuilder.class); // // // // // TODO: Refactor to use the container, now that we have one // // // // this.commandManager = (CommandManager) shellContainer.getComponentInstanceOfType(CommandManager.class); // this.commandLineBuilder = (CommandLineBuilder) shellContainer.getComponentInstanceOfType(CommandLineBuilder.class); // // // // // HACK: Set some default variables // // // // variables.set(StandardVariables.PROMPT, "> "); // } // // public Shell() throws CommandException { // this(new IO()); // } // // public Variables getVariables() { // return variables; // } // // public IO getIO() { // return io; // } // // public CommandManager getCommandManager() { // return commandManager; // } // // public Object execute(final String commandLine) throws Exception { // assert commandLine != null; // // if (log.isInfoEnabled()) { // log.info("Executing (String): " + commandLine); // } // // CommandLine cl = commandLineBuilder.create(commandLine); // return cl.execute(); // } // // // // // CommandExecutor // // // // private void dump(final Variables vars) { // Iterator<String> iter = vars.names(); // // if (iter.hasNext()) { // log.debug("Variables:"); // } // // while (iter.hasNext()) { // String name = iter.next(); // // log.debug(" " + name + "=" + vars.get(name)); // } // } // // public Object execute(final String commandName, final Object[] args) throws Exception { // assert commandName != null; // assert args != null; // // boolean debug = log.isDebugEnabled(); // // if (log.isInfoEnabled()) { // log.info("Executing (" + commandName + "): " + Arguments.asString(args)); // } // // // Setup the command container // ShellContainer container = new ShellContainer(shellContainer); // // final CommandDefinition def = commandManager.getCommandDefinition(commandName); // final Class type = def.loadClass(); // // // // // TODO: Pass the command instance the name it was registered with?, could be an alias // // // // container.registerComponentInstance(def); // container.registerComponentImplementation(type); // // // container.start() ? // // Command cmd = (Command) container.getComponentInstanceOfType(Command.class); // // // // // TODO: DI all bits if we can, then free up "context" to replace "category" as a term // // // // final Variables vars = new VariablesImpl(getVariables()); // // cmd.init(new CommandContext() { // public IO getIO() { // return io; // } // // public Variables getVariables() { // return vars; // } // // MessageSource messageSource; // // public MessageSource getMessageSource() { // // Lazy init the messages, commands many not need them // if (messageSource == null) { // messageSource = new MessageSourceImpl(type.getName() + "Messages"); // } // // return messageSource; // } // }); // // // Setup command timings // StopWatch watch = null; // if (debug) { // watch = new StopWatch(); // watch.start(); // } // // Object result; // try { // result = cmd.execute(args); // // if (debug) { // log.debug("Command completed in " + watch); // } // } // finally { // cmd.destroy(); // // shellContainer.removeChildContainer(container); // // container.stop() container.dispose() ? // } // // return result; // } // // public Object execute(final Object... args) throws Exception { // assert args != null; // assert args.length > 1; // // if (log.isInfoEnabled()) { // log.info("Executing (Object...): " + Arguments.asString(args)); // } // // return execute(String.valueOf(args[0]), Arguments.shift(args)); // } // }
import java.io.StringReader; import org.apache.geronimo.gshell.commandline.parser.CommandLineParser; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ParseException; import org.apache.geronimo.gshell.Shell; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import java.io.Reader;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Builds {@link CommandLine} instances ready for executing. * * @version $Rev$ $Date$ */ public class CommandLineBuilder { private static final Log log = LogFactory.getLog(CommandLineBuilder.class);
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java // public class Shell // { // // // // TODO: Introduce Shell interface? // // // // private static final Log log = LogFactory.getLog(Shell.class); // // private final IO io; // // private final ShellContainer shellContainer = new ShellContainer(); // // private final CommandManager commandManager; // // private final CommandLineBuilder commandLineBuilder; // // private final Variables variables = new VariablesImpl(); // // public Shell(final IO io) throws CommandException { // if (io == null) { // throw new NullArgumentException("io"); // } // // this.io = io; // // shellContainer.registerComponentInstance(this); // shellContainer.registerComponentImplementation(CommandManagerImpl.class); // shellContainer.registerComponentImplementation(CommandLineBuilder.class); // // // // // TODO: Refactor to use the container, now that we have one // // // // this.commandManager = (CommandManager) shellContainer.getComponentInstanceOfType(CommandManager.class); // this.commandLineBuilder = (CommandLineBuilder) shellContainer.getComponentInstanceOfType(CommandLineBuilder.class); // // // // // HACK: Set some default variables // // // // variables.set(StandardVariables.PROMPT, "> "); // } // // public Shell() throws CommandException { // this(new IO()); // } // // public Variables getVariables() { // return variables; // } // // public IO getIO() { // return io; // } // // public CommandManager getCommandManager() { // return commandManager; // } // // public Object execute(final String commandLine) throws Exception { // assert commandLine != null; // // if (log.isInfoEnabled()) { // log.info("Executing (String): " + commandLine); // } // // CommandLine cl = commandLineBuilder.create(commandLine); // return cl.execute(); // } // // // // // CommandExecutor // // // // private void dump(final Variables vars) { // Iterator<String> iter = vars.names(); // // if (iter.hasNext()) { // log.debug("Variables:"); // } // // while (iter.hasNext()) { // String name = iter.next(); // // log.debug(" " + name + "=" + vars.get(name)); // } // } // // public Object execute(final String commandName, final Object[] args) throws Exception { // assert commandName != null; // assert args != null; // // boolean debug = log.isDebugEnabled(); // // if (log.isInfoEnabled()) { // log.info("Executing (" + commandName + "): " + Arguments.asString(args)); // } // // // Setup the command container // ShellContainer container = new ShellContainer(shellContainer); // // final CommandDefinition def = commandManager.getCommandDefinition(commandName); // final Class type = def.loadClass(); // // // // // TODO: Pass the command instance the name it was registered with?, could be an alias // // // // container.registerComponentInstance(def); // container.registerComponentImplementation(type); // // // container.start() ? // // Command cmd = (Command) container.getComponentInstanceOfType(Command.class); // // // // // TODO: DI all bits if we can, then free up "context" to replace "category" as a term // // // // final Variables vars = new VariablesImpl(getVariables()); // // cmd.init(new CommandContext() { // public IO getIO() { // return io; // } // // public Variables getVariables() { // return vars; // } // // MessageSource messageSource; // // public MessageSource getMessageSource() { // // Lazy init the messages, commands many not need them // if (messageSource == null) { // messageSource = new MessageSourceImpl(type.getName() + "Messages"); // } // // return messageSource; // } // }); // // // Setup command timings // StopWatch watch = null; // if (debug) { // watch = new StopWatch(); // watch.start(); // } // // Object result; // try { // result = cmd.execute(args); // // if (debug) { // log.debug("Command completed in " + watch); // } // } // finally { // cmd.destroy(); // // shellContainer.removeChildContainer(container); // // container.stop() container.dispose() ? // } // // return result; // } // // public Object execute(final Object... args) throws Exception { // assert args != null; // assert args.length > 1; // // if (log.isInfoEnabled()) { // log.info("Executing (Object...): " + Arguments.asString(args)); // } // // return execute(String.valueOf(args[0]), Arguments.shift(args)); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/CommandLineBuilder.java import java.io.StringReader; import org.apache.geronimo.gshell.commandline.parser.CommandLineParser; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ParseException; import org.apache.geronimo.gshell.Shell; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import java.io.Reader; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Builds {@link CommandLine} instances ready for executing. * * @version $Rev$ $Date$ */ public class CommandLineBuilder { private static final Log log = LogFactory.getLog(CommandLineBuilder.class);
private final Shell shell;
apache/geronimo-gshell
gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandSupport.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // }
import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.cli.Options; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLine; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.util.Arguments;
this.context = null; log.debug("Destroyed"); } protected void doDestroy() throws Exception { // Sub-class should override to provide custom cleanup } public void abort() { // Sub-calss should override to allow for custom abort functionality } // // Context Helpers // protected CommandContext getCommandContext() { if (context == null) { throw new IllegalStateException("Not initialized; missing command context"); } return context; } protected Variables getVariables() { return getCommandContext().getVariables(); }
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // } // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandSupport.java import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.cli.Options; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLine; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.util.Arguments; this.context = null; log.debug("Destroyed"); } protected void doDestroy() throws Exception { // Sub-class should override to provide custom cleanup } public void abort() { // Sub-calss should override to allow for custom abort functionality } // // Context Helpers // protected CommandContext getCommandContext() { if (context == null) { throw new IllegalStateException("Not initialized; missing command context"); } return context; } protected Variables getVariables() { return getCommandContext().getVariables(); }
protected IO getIO() {
apache/geronimo-gshell
gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandSupport.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // }
import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.cli.Options; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLine; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.util.Arguments;
} return context; } protected Variables getVariables() { return getCommandContext().getVariables(); } protected IO getIO() { return getCommandContext().getIO(); } protected MessageSource getMessageSource() { return getCommandContext().getMessageSource(); } // // Execute Helpers // public Object execute(final Object... args) throws Exception { assert args != null; // Make sure that we have been initialized before we go any further ensureInitialized(); boolean info = log.isInfoEnabled(); if (info) {
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // } // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandSupport.java import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.cli.Options; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLine; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.util.Arguments; } return context; } protected Variables getVariables() { return getCommandContext().getVariables(); } protected IO getIO() { return getCommandContext().getIO(); } protected MessageSource getMessageSource() { return getCommandContext().getMessageSource(); } // // Execute Helpers // public Object execute(final Object... args) throws Exception { assert args != null; // Make sure that we have been initialized before we go any further ensureInitialized(); boolean info = log.isInfoEnabled(); if (info) {
log.info("Executing w/arguments: " + Arguments.asString(args));
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // }
import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException;
switch (level) { case INFO: log.info(buff); break; case DEBUG: log.debug(buff); break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); }
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; switch (level) { case INFO: log.info(buff); break; case DEBUG: log.debug(buff); break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); }
public Object visit(final ASTQuotedString node, Object data) {
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // }
import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException;
break; case DEBUG: log.debug(buff); break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); } public Object visit(final ASTQuotedString node, Object data) { return log(ASTQuotedString.class, node, data); }
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; break; case DEBUG: log.debug(buff); break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); } public Object visit(final ASTQuotedString node, Object data) { return log(ASTQuotedString.class, node, data); }
public Object visit(final ASTOpaqueString node, Object data) {
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // }
import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException;
break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); } public Object visit(final ASTQuotedString node, Object data) { return log(ASTQuotedString.class, node, data); } public Object visit(final ASTOpaqueString node, Object data) { return log(ASTOpaqueString.class, node, data); }
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTQuotedString.java // public class ASTQuotedString // extends StringSupport // { // public ASTQuotedString(final int id) { // super(id); // } // // public ASTQuotedString(final CommandLineParser p, final int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTOpaqueString.java // public class ASTOpaqueString // extends StringSupport // { // public ASTOpaqueString(int id) { // super(id); // } // // public ASTOpaqueString(CommandLineParser p, int id) { // super(p, id); // } // // public String getValue() { // return unquote(super.getValue()); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/parser/ASTPlainString.java // public class ASTPlainString // extends StringSupport // { // public ASTPlainString(int id) { // super(id); // } // // public ASTPlainString(CommandLineParser p, int id) { // super(p, id); // } // // /** Accept the visitor. **/ // public Object jjtAccept(final CommandLineParserVisitor visitor, final Object data) { // return visitor.visit(this, data); // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/LoggingVisitor.java import org.apache.geronimo.gshell.commandline.parser.CommandLineParserVisitor; import org.apache.geronimo.gshell.commandline.parser.SimpleNode; import org.apache.geronimo.gshell.commandline.parser.ASTCommandLine; import org.apache.geronimo.gshell.commandline.parser.ASTExpression; import org.apache.geronimo.gshell.commandline.parser.ASTQuotedString; import org.apache.geronimo.gshell.commandline.parser.ASTOpaqueString; import org.apache.geronimo.gshell.commandline.parser.ASTPlainString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.NullArgumentException; break; } indent++; data = node.childrenAccept(this, data); indent--; return data; } public Object visit(final SimpleNode node, Object data) { return log(SimpleNode.class, node, data); } public Object visit(final ASTCommandLine node, Object data) { return log(ASTCommandLine.class, node, data); } public Object visit(final ASTExpression node, Object data) { return log(ASTExpression.class, node, data); } public Object visit(final ASTQuotedString node, Object data) { return log(ASTQuotedString.class, node, data); } public Object visit(final ASTOpaqueString node, Object data) { return log(ASTOpaqueString.class, node, data); }
public Object visit(final ASTPlainString node, Object data) {
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/commandline/ExecutingVisitorTest.java
// Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java // public class MockShell // extends Shell // { // public Object[] args; // // public String commandName; // // public MockShell() throws CommandException { // super(new IO()); // } // // public Object execute(Object... args) throws Exception { // this.args = args; // // return 0; // } // // public Object execute(String commandName, Object[] args) throws Exception { // this.commandName = commandName; // this.args = args; // // return 0; // } // }
import junit.framework.TestCase; import org.apache.geronimo.gshell.MockShell;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Unit tests for the {@link ExecutingVisitor} usage. * * @version $Rev$ $Date$ */ public class ExecutingVisitorTest extends TestCase { public void testConstructor() throws Exception { try { new ExecutingVisitor(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } // Happy day
// Path: gshell-core/src/test/java/org/apache/geronimo/gshell/MockShell.java // public class MockShell // extends Shell // { // public Object[] args; // // public String commandName; // // public MockShell() throws CommandException { // super(new IO()); // } // // public Object execute(Object... args) throws Exception { // this.args = args; // // return 0; // } // // public Object execute(String commandName, Object[] args) throws Exception { // this.commandName = commandName; // this.args = args; // // return 0; // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/commandline/ExecutingVisitorTest.java import junit.framework.TestCase; import org.apache.geronimo.gshell.MockShell; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Unit tests for the {@link ExecutingVisitor} usage. * * @version $Rev$ $Date$ */ public class ExecutingVisitorTest extends TestCase { public void testConstructor() throws Exception { try { new ExecutingVisitor(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } // Happy day
new ExecutingVisitor(new MockShell());
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/ShellTest.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // }
import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Unit tests for the {@link Shell} class. * * @version $Rev$ $Date$ */ public class ShellTest extends TestCase { public void testConstructorArgs() throws Exception { try { new Shell(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } new Shell();
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/ShellTest.java import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Unit tests for the {@link Shell} class. * * @version $Rev$ $Date$ */ public class ShellTest extends TestCase { public void testConstructorArgs() throws Exception { try { new Shell(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } new Shell();
new Shell(new IO());
apache/geronimo-gshell
gshell-core/src/test/java/org/apache/geronimo/gshell/ShellTest.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // }
import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Unit tests for the {@link Shell} class. * * @version $Rev$ $Date$ */ public class ShellTest extends TestCase { public void testConstructorArgs() throws Exception { try { new Shell(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } new Shell(); new Shell(new IO()); } public void testExecuteVarargs() throws Exception { Shell shell = new Shell(); try { shell.execute("foo", "bar", "baz"); }
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandNotFoundException.java // public class CommandNotFoundException // extends CommandException // { // ///CLOVER:OFF // // public CommandNotFoundException(final String path) { // this(path, "Command or path was not found"); // } // // public CommandNotFoundException(final String path, final String msg) { // super(msg + ": " + path); // } // } // Path: gshell-core/src/test/java/org/apache/geronimo/gshell/ShellTest.java import junit.framework.TestCase; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.command.CommandNotFoundException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell; /** * Unit tests for the {@link Shell} class. * * @version $Rev$ $Date$ */ public class ShellTest extends TestCase { public void testConstructorArgs() throws Exception { try { new Shell(null); fail("Accepted null value"); } catch (IllegalArgumentException expected) { // ignore } new Shell(); new Shell(new IO()); } public void testExecuteVarargs() throws Exception { Shell shell = new Shell(); try { shell.execute("foo", "bar", "baz"); }
catch (CommandNotFoundException expected) {
apache/geronimo-gshell
gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandContext.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // }
import org.apache.geronimo.gshell.console.IO;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.command; /** * Provides the running context (or environment) for a {@link Command}. * * @version $Rev$ $Date$ */ public interface CommandContext {
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/IO.java // public class IO // { // /** // * Raw input stream. // * // * @see #in // */ // public final InputStream inputStream; // // /** // * Raw output stream. // * // * @see #out // */ // public final OutputStream outputStream; // // /** // * Raw error output stream. // * // * @see #err // */ // public final OutputStream errorStream; // // /** // * Prefered input reader. // */ // public final Reader in; // // /** // * Prefered output writer. // */ // public final PrintWriter out; // // /** // * Prefered error output writer. // */ // public final PrintWriter err; // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream; must not be null // * @param err The error output stream; must not be null // */ // public IO(final InputStream in, final OutputStream out, final OutputStream err) { // if (in == null) { // throw new NullArgumentException("in"); // } // if (out == null) { // throw new NullArgumentException("out"); // } // if (err == null) { // throw new NullArgumentException("err"); // } // // this.inputStream = in; // this.outputStream = out; // this.errorStream = err; // // this.in = new InputStreamReader(in); // this.out = new PrintWriter(out, true); // this.err = new PrintWriter(err, true); // } // // /** // * Construct a new IO container. // * // * @param in The input steam; must not be null // * @param out The output stream and error stream; must not be null // */ // public IO(final InputStream in, final OutputStream out) { // this(in, out, out); // } // // /** // * Helper which uses current values from {@link System}. // */ // public IO() { // this(System.in, System.out, System.err); // } // // /** // * Flush both output streams. // */ // public void flush() { // out.flush(); // err.flush(); // } // // public void close() throws IOException { // in.close(); // out.close(); // err.close(); // } // } // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandContext.java import org.apache.geronimo.gshell.console.IO; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.command; /** * Provides the running context (or environment) for a {@link Command}. * * @version $Rev$ $Date$ */ public interface CommandContext {
IO getIO();
apache/geronimo-gshell
gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandDefinition.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // }
import java.util.Properties; import org.apache.geronimo.gshell.util.Arguments; import org.apache.commons.lang.NullArgumentException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.command; /** * Container for the very basic information about a command. * * @version $Rev$ $Date$ */ public class CommandDefinition { private final String name; private final String classname; private final String[] aliases; private final boolean enabled; private final String category; public CommandDefinition(final Properties props) throws InvalidDefinitionException { if (props == null) { throw new NullArgumentException("props"); } this.name = props.getProperty("name"); if (name == null) { throw new MissingPropertyException("name", props); } this.classname = props.getProperty("class"); if (classname == null) { throw new MissingPropertyException("class", props); } this.aliases = loadAliasesFrom(props); this.enabled = Boolean.getBoolean(props.getProperty("enable")); this.category = props.getProperty("category"); if (category == null) { throw new MissingPropertyException("category", props); } } public String toString() { return getName() + "=" + getClassName() +
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/util/Arguments.java // public class Arguments // { // public static Object[] shift(final Object[] args) { // return shift(args, 1); // } // // public static Object[] shift(final Object[] args, int pos) { // assert args != null; // assert args.length >= pos; // // String[] _args = new String[args.length - pos]; // System.arraycopy(args, pos, _args, 0, _args.length); // return _args; // } // // public static String asString(final Object[] args) { // assert args != null; // // StringBuffer buff = new StringBuffer(); // // for (int i=0; i<args.length; i++ ) { // buff.append(args[i]); // if (i + 1 < args.length) { // buff.append(", "); // } // } // // return buff.toString(); // } // // public static String[] toStringArray(final Object[] args) { // assert args != null; // // String[] strings = new String[args.length]; // // for (int i=0; i<args.length; i++ ) { // strings[i] = String.valueOf(args[i]); // } // // return strings; // } // } // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/CommandDefinition.java import java.util.Properties; import org.apache.geronimo.gshell.util.Arguments; import org.apache.commons.lang.NullArgumentException; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.command; /** * Container for the very basic information about a command. * * @version $Rev$ $Date$ */ public class CommandDefinition { private final String name; private final String classname; private final String[] aliases; private final boolean enabled; private final String category; public CommandDefinition(final Properties props) throws InvalidDefinitionException { if (props == null) { throw new NullArgumentException("props"); } this.name = props.getProperty("name"); if (name == null) { throw new MissingPropertyException("name", props); } this.classname = props.getProperty("class"); if (classname == null) { throw new MissingPropertyException("class", props); } this.aliases = loadAliasesFrom(props); this.enabled = Boolean.getBoolean(props.getProperty("enable")); this.category = props.getProperty("category"); if (category == null) { throw new MissingPropertyException("category", props); } } public String toString() { return getName() + "=" + getClassName() +
"{ aliases=" + Arguments.asString(getAliases()) +
apache/geronimo-gshell
gshell-commands/gshell-scripting-commands/src/main/java/org/apache/geronimo/gshell/commands/scripting/InteractiveInterpreter.java
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/console/InteractiveConsole.java // public class InteractiveConsole // implements Runnable // { // // // // TODO: Rename to *Runner, since this is not really a Console impl // // // // private static final Log log = LogFactory.getLog(InteractiveConsole.class); // // private final Console console; // // private final Executor executor; // // private final Prompter prompter; // // private boolean running = false; // // private boolean shutdownOnNull = true; // // public InteractiveConsole(final Console console, final Executor executor, final Prompter prompter) { // if (console == null) { // throw new NullArgumentException("console"); // } // if (executor == null) { // throw new NullArgumentException("executor"); // } // if (prompter == null) { // throw new NullArgumentException("prompter"); // } // // this.console = console; // this.executor = executor; // this.prompter = prompter; // } // // /** // * Enable or disable shutting down the interactive loop when // * a null value is read from the given console. // * // * @param flag True to shutdown when a null is received; else false // */ // public void setShutdownOnNull(final boolean flag) { // this.shutdownOnNull = flag; // } // // /** // * @see #setShutdownOnNull // */ // public boolean isShutdownOnNull() { // return shutdownOnNull; // } // // public boolean isRunning() { // return running; // } // // // // // abort() ? // // // // public void run() { // log.info("Running..."); // // running = true; // // while (running) { // try { // doRun(); // } // catch (Exception e) { // log.error("Exception", e); // } // catch (Error e) { // log.error("Error", e); // } // } // // log.info("Stopped"); // } // // private void doRun() throws Exception { // boolean debug = log.isDebugEnabled(); // String line; // // while ((line = console.readLine(doGetPrompt())) != null) { // if (debug) { // log.debug("Read line: " + line); // // // Log the line as hex // StringBuffer idx = new StringBuffer(); // StringBuffer hex = new StringBuffer(); // // byte[] bytes = line.getBytes(); // for (byte b : bytes) { // String h = Integer.toHexString(b); // // hex.append("x").append(h).append(" "); // idx.append(" ").append((char)b).append(" "); // } // // log.debug("HEX: " + hex); // log.debug(" " + idx); // } // // Executor.Result result = doExecute(line); // // // Allow executor to request that the loop stop // if (result == Executor.Result.STOP) { // log.debug("Executor requested STOP"); // running = false; // break; // } // } // // // Line was null, maybe shutdown // if (shutdownOnNull) { // log.debug("Input was null; which will cause shutdown"); // running = false; // } // // // // // TODO: Probably need to expose more configurability for handing/rejecting shutdown // // // // Use-case is that Shell might want to disallow and print a "use exit command", // // but Script interp wants this to exit and return control to Shell. // // // } // // protected Executor.Result doExecute(final String line) throws Exception { // return executor.execute(line); // } // // protected String doGetPrompt() { // return prompter.getPrompt(); // } // // // // // Executor // // // // /** // * Allows custom processing, the "do something". // */ // public static interface Executor // { // enum Result { // CONTINUE, // STOP // } // // Result execute(String line) throws Exception; // } // // // // // Prompter // // // // /** // * Allows custom prompt handling. // */ // public static interface Prompter // { // /** // * Return the prompt to be displayed. // * // * @return The prompt to be displayed; must not be null // */ // String getPrompt(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/Console.java // public interface Console // { // String readLine(final String prompt) throws IOException; // // IO getIO(); // }
import org.apache.bsf.BSFEngine; import org.apache.geronimo.gshell.console.InteractiveConsole; import org.apache.geronimo.gshell.console.Console;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.scripting; /** * An interactive console extention that knows how to execute lines of script text with a {@link BSFEngine}. * * @version $Rev$ $Date$ */ public class InteractiveInterpreter extends InteractiveConsole {
// Path: gshell-core/src/main/java/org/apache/geronimo/gshell/console/InteractiveConsole.java // public class InteractiveConsole // implements Runnable // { // // // // TODO: Rename to *Runner, since this is not really a Console impl // // // // private static final Log log = LogFactory.getLog(InteractiveConsole.class); // // private final Console console; // // private final Executor executor; // // private final Prompter prompter; // // private boolean running = false; // // private boolean shutdownOnNull = true; // // public InteractiveConsole(final Console console, final Executor executor, final Prompter prompter) { // if (console == null) { // throw new NullArgumentException("console"); // } // if (executor == null) { // throw new NullArgumentException("executor"); // } // if (prompter == null) { // throw new NullArgumentException("prompter"); // } // // this.console = console; // this.executor = executor; // this.prompter = prompter; // } // // /** // * Enable or disable shutting down the interactive loop when // * a null value is read from the given console. // * // * @param flag True to shutdown when a null is received; else false // */ // public void setShutdownOnNull(final boolean flag) { // this.shutdownOnNull = flag; // } // // /** // * @see #setShutdownOnNull // */ // public boolean isShutdownOnNull() { // return shutdownOnNull; // } // // public boolean isRunning() { // return running; // } // // // // // abort() ? // // // // public void run() { // log.info("Running..."); // // running = true; // // while (running) { // try { // doRun(); // } // catch (Exception e) { // log.error("Exception", e); // } // catch (Error e) { // log.error("Error", e); // } // } // // log.info("Stopped"); // } // // private void doRun() throws Exception { // boolean debug = log.isDebugEnabled(); // String line; // // while ((line = console.readLine(doGetPrompt())) != null) { // if (debug) { // log.debug("Read line: " + line); // // // Log the line as hex // StringBuffer idx = new StringBuffer(); // StringBuffer hex = new StringBuffer(); // // byte[] bytes = line.getBytes(); // for (byte b : bytes) { // String h = Integer.toHexString(b); // // hex.append("x").append(h).append(" "); // idx.append(" ").append((char)b).append(" "); // } // // log.debug("HEX: " + hex); // log.debug(" " + idx); // } // // Executor.Result result = doExecute(line); // // // Allow executor to request that the loop stop // if (result == Executor.Result.STOP) { // log.debug("Executor requested STOP"); // running = false; // break; // } // } // // // Line was null, maybe shutdown // if (shutdownOnNull) { // log.debug("Input was null; which will cause shutdown"); // running = false; // } // // // // // TODO: Probably need to expose more configurability for handing/rejecting shutdown // // // // Use-case is that Shell might want to disallow and print a "use exit command", // // but Script interp wants this to exit and return control to Shell. // // // } // // protected Executor.Result doExecute(final String line) throws Exception { // return executor.execute(line); // } // // protected String doGetPrompt() { // return prompter.getPrompt(); // } // // // // // Executor // // // // /** // * Allows custom processing, the "do something". // */ // public static interface Executor // { // enum Result { // CONTINUE, // STOP // } // // Result execute(String line) throws Exception; // } // // // // // Prompter // // // // /** // * Allows custom prompt handling. // */ // public static interface Prompter // { // /** // * Return the prompt to be displayed. // * // * @return The prompt to be displayed; must not be null // */ // String getPrompt(); // } // } // // Path: gshell-api/src/main/java/org/apache/geronimo/gshell/console/Console.java // public interface Console // { // String readLine(final String prompt) throws IOException; // // IO getIO(); // } // Path: gshell-commands/gshell-scripting-commands/src/main/java/org/apache/geronimo/gshell/commands/scripting/InteractiveInterpreter.java import org.apache.bsf.BSFEngine; import org.apache.geronimo.gshell.console.InteractiveConsole; import org.apache.geronimo.gshell.console.Console; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commands.scripting; /** * An interactive console extention that knows how to execute lines of script text with a {@link BSFEngine}. * * @version $Rev$ $Date$ */ public class InteractiveInterpreter extends InteractiveConsole {
public InteractiveInterpreter(final Console console, final BSFEngine engine, final String language) {
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/VariableExpressionParser.java
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Variables.java // public interface Variables // { // void set(String name, Object value) throws ImmutableVariableException; // // void set(String name, Object value, boolean mutable) throws ImmutableVariableException; // // Object get(String name); // // Object get(String name, Object _default); // // boolean isMutable(String name); // // boolean isCloaked(String name); // // void unset(String name) throws ImmutableVariableException; // // boolean contains(String name); // // Iterator<String> names(); // // Variables parent(); // // // // // Exceptions // // // // class ImmutableVariableException // extends RuntimeException // { // ///CLOVER:OFF // // public ImmutableVariableException(final String name) { // super("Variable is immutable: " + name); // } // } // }
import org.apache.commons.jexl.resolver.FlatResolver; import org.apache.commons.lang.NullArgumentException; import org.apache.geronimo.gshell.command.Variables; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.jexl.JexlHelper; import org.apache.commons.jexl.JexlContext; import org.apache.commons.jexl.Expression; import org.apache.commons.jexl.ExpressionFactory;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Parser to handle ${...} expressions using * <a href="http://jakarta.apache.org/commons/jexl/">JEXL</a>. * * <p> * Supports complex ${xxx} and simple $xxx expressions * * @version $Rev$ $Date$ */ public class VariableExpressionParser { // // NOTE: May want to add the ${...} bits the the CommandLineParser directly. // This sub-parser is probably only short-term so we can get soemthing working // private static final Log log = LogFactory.getLog(VariableExpressionParser.class); protected JexlContext context; public VariableExpressionParser(final Map vars) { if (vars == null) { throw new NullArgumentException("vars"); } context = JexlHelper.createContext(); context.setVars(vars); if (log.isTraceEnabled()) { log.trace("Using variables: " + context.getVars()); } }
// Path: gshell-api/src/main/java/org/apache/geronimo/gshell/command/Variables.java // public interface Variables // { // void set(String name, Object value) throws ImmutableVariableException; // // void set(String name, Object value, boolean mutable) throws ImmutableVariableException; // // Object get(String name); // // Object get(String name, Object _default); // // boolean isMutable(String name); // // boolean isCloaked(String name); // // void unset(String name) throws ImmutableVariableException; // // boolean contains(String name); // // Iterator<String> names(); // // Variables parent(); // // // // // Exceptions // // // // class ImmutableVariableException // extends RuntimeException // { // ///CLOVER:OFF // // public ImmutableVariableException(final String name) { // super("Variable is immutable: " + name); // } // } // } // Path: gshell-core/src/main/java/org/apache/geronimo/gshell/commandline/VariableExpressionParser.java import org.apache.commons.jexl.resolver.FlatResolver; import org.apache.commons.lang.NullArgumentException; import org.apache.geronimo.gshell.command.Variables; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.jexl.JexlHelper; import org.apache.commons.jexl.JexlContext; import org.apache.commons.jexl.Expression; import org.apache.commons.jexl.ExpressionFactory; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.gshell.commandline; /** * Parser to handle ${...} expressions using * <a href="http://jakarta.apache.org/commons/jexl/">JEXL</a>. * * <p> * Supports complex ${xxx} and simple $xxx expressions * * @version $Rev$ $Date$ */ public class VariableExpressionParser { // // NOTE: May want to add the ${...} bits the the CommandLineParser directly. // This sub-parser is probably only short-term so we can get soemthing working // private static final Log log = LogFactory.getLog(VariableExpressionParser.class); protected JexlContext context; public VariableExpressionParser(final Map vars) { if (vars == null) { throw new NullArgumentException("vars"); } context = JexlHelper.createContext(); context.setVars(vars); if (log.isTraceEnabled()) { log.trace("Using variables: " + context.getVars()); } }
private static Map convertToMap(final Variables vars) {
oakesville/mythling
src/com/oakesville/mythling/app/Localizer.java
// Path: src/com/oakesville/mythling/util/Reporter.java // public class Reporter { // private static final String TAG = Reporter.class.getSimpleName(); // private static final String ERROR_REPORTING_URL = "http://54.187.163.194/mythling/report"; // // private Throwable throwable; // private final String message; // // public Reporter(Throwable t) { // this.throwable = t; // this.message = t.getMessage(); // } // // public Reporter(String message) { // this.message = message; // } // // /** // * Report the error in a background thread. // */ // public void send() { // new Thread(new Runnable() { // public void run() { // try { // JSONObject json = buildJson(); // HttpHelper helper = new HttpHelper(new URL(ERROR_REPORTING_URL)); // String response = new String(helper.post(json.toString(2).getBytes())); // JSONObject responseJson = new JSONObject(response); // JSONObject reportResponse = responseJson.getJSONObject("reportResponse"); // String status = reportResponse.getString("status"); // if (!"success".equals(status)) // throw new IOException("Error response from reporting site: " + reportResponse.getString("message")); // } catch (Exception ex) { // Log.e(TAG, ex.getMessage(), ex); // } // } // }).start(); // } // // private JSONObject buildJson() throws JSONException { // JSONObject json = new JSONObject(); // JSONObject report = new JSONObject(); // json.put("report", report); // report.put("source", "Mythling v" + AppSettings.staticGetMythlingVersion() + // " (sdk " + AppSettings.getAndroidVersion() + ")"); // report.put("message", message == null ? "No message" : message); // if (throwable != null) { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // throwable.printStackTrace(new PrintStream(out)); // report.put("stackTrace", new String(out.toByteArray())); // } // return json; // } // }
import java.text.SimpleDateFormat; import com.oakesville.mythling.R; import com.oakesville.mythling.util.Reporter; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import io.oakesville.media.MediaSettings.MediaType; import io.oakesville.media.MediaSettings.MediaTypeDeterminer; import io.oakesville.media.MediaSettings.SortType;
} return instance; } private AppSettings getAppSettings() { return (AppSettings)getResources(); } private Context getAppContext() { return getAppSettings().getAppContext(); } @SuppressLint("SimpleDateFormat") @Override public void initialize(Object appSettings) { try { super.initialize(appSettings); leadingArticles = getAppContext().getResources().getStringArray(R.array.leading_articles); dateFormat = new SimpleDateFormat(getStringRes(R.string.date_format)); timeFormat = new SimpleDateFormat(getStringRes(R.string.time_format)); dateTimeFormat = new SimpleDateFormat(getStringRes(R.string.date_time_format)); dateTimeYearFormat = new SimpleDateFormat(getStringRes(R.string.date_time_year_format)); yearFormat = new SimpleDateFormat(getStringRes(R.string.year_format)); weekdayDateFormat = new SimpleDateFormat(getStringRes(R.string.weekday_date_format)); am = AM_PM_FORMAT.format(AM_PM_FORMAT_US.parse("00")); pm = AM_PM_FORMAT.format(AM_PM_FORMAT_US.parse("12")); abbrevAm = getStringRes(R.string.abbrev_am); abbrevPm = getStringRes(R.string.abbrev_pm); } catch (Exception ex) { Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled())
// Path: src/com/oakesville/mythling/util/Reporter.java // public class Reporter { // private static final String TAG = Reporter.class.getSimpleName(); // private static final String ERROR_REPORTING_URL = "http://54.187.163.194/mythling/report"; // // private Throwable throwable; // private final String message; // // public Reporter(Throwable t) { // this.throwable = t; // this.message = t.getMessage(); // } // // public Reporter(String message) { // this.message = message; // } // // /** // * Report the error in a background thread. // */ // public void send() { // new Thread(new Runnable() { // public void run() { // try { // JSONObject json = buildJson(); // HttpHelper helper = new HttpHelper(new URL(ERROR_REPORTING_URL)); // String response = new String(helper.post(json.toString(2).getBytes())); // JSONObject responseJson = new JSONObject(response); // JSONObject reportResponse = responseJson.getJSONObject("reportResponse"); // String status = reportResponse.getString("status"); // if (!"success".equals(status)) // throw new IOException("Error response from reporting site: " + reportResponse.getString("message")); // } catch (Exception ex) { // Log.e(TAG, ex.getMessage(), ex); // } // } // }).start(); // } // // private JSONObject buildJson() throws JSONException { // JSONObject json = new JSONObject(); // JSONObject report = new JSONObject(); // json.put("report", report); // report.put("source", "Mythling v" + AppSettings.staticGetMythlingVersion() + // " (sdk " + AppSettings.getAndroidVersion() + ")"); // report.put("message", message == null ? "No message" : message); // if (throwable != null) { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // throwable.printStackTrace(new PrintStream(out)); // report.put("stackTrace", new String(out.toByteArray())); // } // return json; // } // } // Path: src/com/oakesville/mythling/app/Localizer.java import java.text.SimpleDateFormat; import com.oakesville.mythling.R; import com.oakesville.mythling.util.Reporter; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import io.oakesville.media.MediaSettings.MediaType; import io.oakesville.media.MediaSettings.MediaTypeDeterminer; import io.oakesville.media.MediaSettings.SortType; } return instance; } private AppSettings getAppSettings() { return (AppSettings)getResources(); } private Context getAppContext() { return getAppSettings().getAppContext(); } @SuppressLint("SimpleDateFormat") @Override public void initialize(Object appSettings) { try { super.initialize(appSettings); leadingArticles = getAppContext().getResources().getStringArray(R.array.leading_articles); dateFormat = new SimpleDateFormat(getStringRes(R.string.date_format)); timeFormat = new SimpleDateFormat(getStringRes(R.string.time_format)); dateTimeFormat = new SimpleDateFormat(getStringRes(R.string.date_time_format)); dateTimeYearFormat = new SimpleDateFormat(getStringRes(R.string.date_time_year_format)); yearFormat = new SimpleDateFormat(getStringRes(R.string.year_format)); weekdayDateFormat = new SimpleDateFormat(getStringRes(R.string.weekday_date_format)); am = AM_PM_FORMAT.format(AM_PM_FORMAT_US.parse("00")); pm = AM_PM_FORMAT.format(AM_PM_FORMAT_US.parse("12")); abbrevAm = getStringRes(R.string.abbrev_am); abbrevPm = getStringRes(R.string.abbrev_pm); } catch (Exception ex) { Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled())
new Reporter(ex).send();
oakesville/mythling
src/com/oakesville/mythling/util/MediaStreamProxy.java
// Path: src/com/oakesville/mythling/util/HttpHelper.java // public enum AuthType { // None, // Basic, // Digest // }
import android.net.Uri; import android.net.http.AndroidHttpClient; import android.util.Base64; import android.util.Log; import com.oakesville.mythling.util.HttpHelper.AuthType; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.protocol.HttpContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.StringTokenizer;
/** * Copyright 2015 Donald Oakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oakesville.mythling.util; /** * Proxies media streaming requests, providing HTTP Basic and Digest * authentication for players that don't natively support these options. */ public class MediaStreamProxy implements Runnable { private static final String TAG = MediaStreamProxy.class.getSimpleName(); private InetAddress localhost; public InetAddress getLocalhost() { return localhost; } private int port; public int getPort() { return port; } private AndroidHttpClient httpClient; private boolean isRunning = true; private ServerSocket socket; private Thread thread; private final ProxyInfo proxyInfo;
// Path: src/com/oakesville/mythling/util/HttpHelper.java // public enum AuthType { // None, // Basic, // Digest // } // Path: src/com/oakesville/mythling/util/MediaStreamProxy.java import android.net.Uri; import android.net.http.AndroidHttpClient; import android.util.Base64; import android.util.Log; import com.oakesville.mythling.util.HttpHelper.AuthType; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.protocol.HttpContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.StringTokenizer; /** * Copyright 2015 Donald Oakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oakesville.mythling.util; /** * Proxies media streaming requests, providing HTTP Basic and Digest * authentication for players that don't natively support these options. */ public class MediaStreamProxy implements Runnable { private static final String TAG = MediaStreamProxy.class.getSimpleName(); private InetAddress localhost; public InetAddress getLocalhost() { return localhost; } private int port; public int getPort() { return port; } private AndroidHttpClient httpClient; private boolean isRunning = true; private ServerSocket socket; private Thread thread; private final ProxyInfo proxyInfo;
private final AuthType authType;
oakesville/mythling
src/com/oakesville/mythling/media/MediaPlayer.java
// Path: src/com/oakesville/mythling/util/HttpHelper.java // public enum AuthType { // None, // Basic, // Digest // }
import java.io.FileDescriptor; import java.io.IOException; import java.util.List; import com.oakesville.mythling.util.HttpHelper.AuthType; import android.net.Uri;
/** * Copyright 2015 Donald Oakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oakesville.mythling.media; public interface MediaPlayer { class MediaPlayerEvent { public MediaPlayerEvent(MediaPlayerEventType type) { this.type = type; } public final MediaPlayerEventType type; public int position; public String message; } enum MediaPlayerEventType { playing, time, seek, buffered, paused, stopped, end, error } interface MediaPlayerEventListener { void onEvent(MediaPlayerEvent event); } interface MediaPlayerShiftListener { void onShift(int delta); } interface MediaPlayerLayoutChangeListener { void onLayoutChange(int width, int height, int aspectNumerator, int aspectDenominator); } String getVersion(); /** * @param metaLength length from mythtv database */
// Path: src/com/oakesville/mythling/util/HttpHelper.java // public enum AuthType { // None, // Basic, // Digest // } // Path: src/com/oakesville/mythling/media/MediaPlayer.java import java.io.FileDescriptor; import java.io.IOException; import java.util.List; import com.oakesville.mythling.util.HttpHelper.AuthType; import android.net.Uri; /** * Copyright 2015 Donald Oakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oakesville.mythling.media; public interface MediaPlayer { class MediaPlayerEvent { public MediaPlayerEvent(MediaPlayerEventType type) { this.type = type; } public final MediaPlayerEventType type; public int position; public String message; } enum MediaPlayerEventType { playing, time, seek, buffered, paused, stopped, end, error } interface MediaPlayerEventListener { void onEvent(MediaPlayerEvent event); } interface MediaPlayerShiftListener { void onShift(int delta); } interface MediaPlayerLayoutChangeListener { void onLayoutChange(int width, int height, int aspectNumerator, int aspectDenominator); } String getVersion(); /** * @param metaLength length from mythtv database */
void playMedia(Uri mediaUri, int metaLength, AuthType authType, List<String> options) throws IOException;
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable;
package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */
public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable;
package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */ public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); changeSkinStyle(view, skinStyle);
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class SkinCompat { public interface SkinStyleChangeListener { void beforeChange(); void afterChange(); } /** * @param activity 当前 Activity * @param skinStyle Dark(夜间),Light(日间) * @param skinStyleChangeListener (转换监听器) */ public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); changeSkinStyle(view, skinStyle);
SkinConfig.setSkinStyle(activity, skinStyle);
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable;
skinStyleChangeListener.beforeChange(); changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) {
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; skinStyleChangeListener.beforeChange(); changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) {
if (view instanceof SkinEnable) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable;
} public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) { if (view instanceof SkinEnable) { ((SkinEnable) view).setSkinStyle(skinStyle); } else { ViewGroup.LayoutParams params = view.getLayoutParams();
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/SLayoutParamsI.java // public interface SLayoutParamsI { // // void setSkinStyle(SkinStyle skinStyle); // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinEnable.java // public interface SkinEnable { // // void setSkinStyle(SkinStyle skinStyle); // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.dim.skin.SkinStyle; import com.dim.widget.SLayoutParamsI; import com.dim.skin.SkinConfig; import com.dim.skin.SkinEnable; } public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { if (skinStyleChangeListener != null) skinStyleChangeListener.beforeChange(); setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); if (skinStyleChangeListener != null) skinStyleChangeListener.afterChange(); } public static void changeSkinStyle(View view, SkinStyle skinStyle) { changeSkinView(view, skinStyle); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View v = ((ViewGroup) view).getChildAt(i); changeSkinStyle(v, skinStyle); } } } public static void changeSkinView(View view, SkinStyle skinStyle) { if (view instanceof SkinEnable) { ((SkinEnable) view).setSkinStyle(skinStyle); } else { ViewGroup.LayoutParams params = view.getLayoutParams();
if (params instanceof SLayoutParamsI) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView;
package com.dim.skin.hepler; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class DefaultViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView;
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView; package com.dim.skin.hepler; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class DefaultViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView;
protected SkinStyle mSkinStyle = SkinStyle.Light;
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView;
} if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } mLightTextColorRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColor", -1); if (mLightTextColorRes == -1) { mLightTextColor = attrs.getAttributeIntValue(ANDROIDXML, "textColor", -1); } mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { nightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } } public void setView(View view){ this.mView=view; } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if(!mEnable){ return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); }
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView; } if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } mLightTextColorRes = attrs.getAttributeResourceValue(ANDROIDXML, "textColor", -1); if (mLightTextColorRes == -1) { mLightTextColor = attrs.getAttributeIntValue(ANDROIDXML, "textColor", -1); } mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { nightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } } public void setView(View view){ this.mView=view; } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if(!mEnable){ return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); }
if(mView instanceof TextView) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView;
if (mNightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mNightTextColorRes)); } else if (nightTextColor != -1) { tv.setTextColor(nightTextColor); } } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } if(mView instanceof TextView) { android.widget.TextView tv= (android.widget.TextView) mView; if (mLightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mLightTextColorRes)); } else if (mLightTextColor != -1) { tv.setTextColor(mLightTextColor); } } } } @Override public void setCurrentTheme() {
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/TextView.java // public class TextView extends AppCompatTextView implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public TextView(Context context) { // super(context); // init(null); // // } // // public TextView(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // public TextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // mSkinHelper.preDraw(this); // // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // mSkinHelper.setSkinStyle(skinStyle); // // // } // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/DefaultViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.TextView; if (mNightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mNightTextColorRes)); } else if (nightTextColor != -1) { tv.setTextColor(nightTextColor); } } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } if(mView instanceof TextView) { android.widget.TextView tv= (android.widget.TextView) mView; if (mLightTextColorRes != -1) { tv.setTextColor(mView.getResources().getColorStateList(mLightTextColorRes)); } else if (mLightTextColor != -1) { tv.setTextColor(mLightTextColor); } } } } @Override public void setCurrentTheme() {
if(SkinConfig.getSkinStyle(mView.getContext())== SkinStyle.Dark){
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/ListViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // }
import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import com.dim.skin.SkinStyle;
package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class ListViewSkinHelper extends ViewSkinHelper { private int mNightLVDivider = -1; private int mNightLVDividerRes = -1; private int mDivider = -1; private int mDividerRes = -1; public ListViewSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); if (mDividerRes == -1) { mDivider = attrs.getAttributeIntValue(ANDROIDXML, "divider", -1); } mNightLVDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightLVDivider", -1); if (mNightLVDividerRes != -1) { mNightLVDivider = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightLVDivider", -1); } } @Override
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/ListViewSkinHelper.java import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import com.dim.skin.SkinStyle; package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class ListViewSkinHelper extends ViewSkinHelper { private int mNightLVDivider = -1; private int mNightLVDividerRes = -1; private int mDivider = -1; private int mDividerRes = -1; public ListViewSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); if (mDividerRes == -1) { mDivider = attrs.getAttributeIntValue(ANDROIDXML, "divider", -1); } mNightLVDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightLVDivider", -1); if (mNightLVDividerRes != -1) { mNightLVDivider = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightLVDivider", -1); } } @Override
public void setSkinStyle(SkinStyle skinStyle) {
zzz40500/ThemeDemo
app/src/main/java/com/dim/themedemo/APP.java
// Path: baselibrary/src/main/java/android/support/v7/app/SkinHelper.java // public class SkinHelper { // // // private static final String TAG = "SkinHelper"; // // public static void init(Object ob) { // // try { // Class cls = Class.forName("android.app.SystemServiceRegistry"); // Class serviceFetcher = Class.forName("android.app.SystemServiceRegistry$ServiceFetcher"); // Field system_service_fetchers = cls.getDeclaredField("SYSTEM_SERVICE_FETCHERS"); // system_service_fetchers.setAccessible(true); // HashMap o = (HashMap) system_service_fetchers.get(null); // final Object layoutInflaterFetcher = o.get(Context.LAYOUT_INFLATER_SERVICE); // Object HockLayoutInflaterFetcher = Proxy.newProxyInstance(ob.getClass().getClassLoader(), new Class[]{serviceFetcher}, new InvocationHandler() { // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // LayoutInflater inflater = (LayoutInflater) method.invoke(layoutInflaterFetcher, args); // inflater.setFactory2(new LayoutInflaterFactory2()); // return inflater; // } // }); // o.put(Context.LAYOUT_INFLATER_SERVICE, HockLayoutInflaterFetcher); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // // } // // }
import android.app.Application; import android.support.v7.app.SkinHelper;
package com.dim.themedemo; /** * Created by zzz40500 on 16/5/24. */ public class APP extends Application { @Override public void onCreate() { super.onCreate();
// Path: baselibrary/src/main/java/android/support/v7/app/SkinHelper.java // public class SkinHelper { // // // private static final String TAG = "SkinHelper"; // // public static void init(Object ob) { // // try { // Class cls = Class.forName("android.app.SystemServiceRegistry"); // Class serviceFetcher = Class.forName("android.app.SystemServiceRegistry$ServiceFetcher"); // Field system_service_fetchers = cls.getDeclaredField("SYSTEM_SERVICE_FETCHERS"); // system_service_fetchers.setAccessible(true); // HashMap o = (HashMap) system_service_fetchers.get(null); // final Object layoutInflaterFetcher = o.get(Context.LAYOUT_INFLATER_SERVICE); // Object HockLayoutInflaterFetcher = Proxy.newProxyInstance(ob.getClass().getClassLoader(), new Class[]{serviceFetcher}, new InvocationHandler() { // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // LayoutInflater inflater = (LayoutInflater) method.invoke(layoutInflaterFetcher, args); // inflater.setFactory2(new LayoutInflaterFactory2()); // return inflater; // } // }); // o.put(Context.LAYOUT_INFLATER_SERVICE, HockLayoutInflaterFetcher); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // // } // // } // Path: app/src/main/java/com/dim/themedemo/APP.java import android.app.Application; import android.support.v7.app.SkinHelper; package com.dim.themedemo; /** * Created by zzz40500 on 16/5/24. */ public class APP extends Application { @Override public void onCreate() { super.onCreate();
SkinHelper.init(this);
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/circletreveal/CircleRevealHelper.java
// Path: baselibrary/src/main/java/com/dim/widget/animation/CRAnimation.java // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public class CRAnimation { // // private ValueAnimator mNAnimator; // private android.animation.Animator mAAnimator; // // // public CRAnimation(ValueAnimator NAnimator) { // // mNAnimator = NAnimator; // } // // public CRAnimation(Animator AAnimator) { // mAAnimator = AAnimator; // } // // public void setInterpolator(Interpolator interpolator) { // // if (mAAnimator != null) { // // mAAnimator.setInterpolator(interpolator); // } else if (mNAnimator != null) { // // mNAnimator.setInterpolator(interpolator); // } // // } // // public void setStartDelay(long startDelay) { // // if (mAAnimator != null) { // // mAAnimator.setStartDelay(startDelay); // } else if (mNAnimator != null) { // // mNAnimator.setStartDelay(startDelay); // } // // } // // // public void addListener(final SimpleAnimListener simpleAnimListener) { // // if (mAAnimator != null) { // mAAnimator.addListener(new android.animation.Animator.AnimatorListener() { // @Override // public void onAnimationStart(android.animation.Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(android.animation.Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(android.animation.Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(android.animation.Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } else if (mNAnimator != null) { // mNAnimator.addListener(new Animator.AnimatorListener() { // @Override // public void onAnimationStart(Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } // // } // // public void end() { // if (mAAnimator != null) { // // mAAnimator.end(); // } else if (mNAnimator != null) { // // mNAnimator.end(); // } // // } // // public void cancel() { // if (mAAnimator != null) { // // mAAnimator.cancel(); // } else if (mNAnimator != null) { // // mNAnimator.cancel(); // } // } // // public void setDuration(long duration) { // // if (mAAnimator != null) { // mAAnimator.setDuration(duration); // } else if (mNAnimator != null) { // mNAnimator.setDuration(duration); // } // // } // // // public void start() { // if (mAAnimator != null) { // // mAAnimator.start(); // } else if (mNAnimator != null) { // // mNAnimator.start(); // } // // } // }
import android.animation.Animator; import android.animation.ValueAnimator; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Region; import android.os.Build; import android.view.View; import android.view.ViewAnimationUtils; import com.dim.widget.animation.CRAnimation;
package com.dim.circletreveal; /** * Created by zzz40500 on 15/8/26. */ public class CircleRevealHelper { private ValueAnimator mValueAnimator; public CircleRevealHelper(View view) { mView = view; if (view instanceof CircleRevealEnable) { mCircleRevealEnable = (CircleRevealEnable) view; } else { throw new RuntimeException("the View must implements CircleRevealEnable "); } } private Path mPath = new Path(); private View mView; private int mAnchorX, mAnchorY; private float mRadius; private CircleRevealEnable mCircleRevealEnable;
// Path: baselibrary/src/main/java/com/dim/widget/animation/CRAnimation.java // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public class CRAnimation { // // private ValueAnimator mNAnimator; // private android.animation.Animator mAAnimator; // // // public CRAnimation(ValueAnimator NAnimator) { // // mNAnimator = NAnimator; // } // // public CRAnimation(Animator AAnimator) { // mAAnimator = AAnimator; // } // // public void setInterpolator(Interpolator interpolator) { // // if (mAAnimator != null) { // // mAAnimator.setInterpolator(interpolator); // } else if (mNAnimator != null) { // // mNAnimator.setInterpolator(interpolator); // } // // } // // public void setStartDelay(long startDelay) { // // if (mAAnimator != null) { // // mAAnimator.setStartDelay(startDelay); // } else if (mNAnimator != null) { // // mNAnimator.setStartDelay(startDelay); // } // // } // // // public void addListener(final SimpleAnimListener simpleAnimListener) { // // if (mAAnimator != null) { // mAAnimator.addListener(new android.animation.Animator.AnimatorListener() { // @Override // public void onAnimationStart(android.animation.Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(android.animation.Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(android.animation.Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(android.animation.Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } else if (mNAnimator != null) { // mNAnimator.addListener(new Animator.AnimatorListener() { // @Override // public void onAnimationStart(Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } // // } // // public void end() { // if (mAAnimator != null) { // // mAAnimator.end(); // } else if (mNAnimator != null) { // // mNAnimator.end(); // } // // } // // public void cancel() { // if (mAAnimator != null) { // // mAAnimator.cancel(); // } else if (mNAnimator != null) { // // mNAnimator.cancel(); // } // } // // public void setDuration(long duration) { // // if (mAAnimator != null) { // mAAnimator.setDuration(duration); // } else if (mNAnimator != null) { // mNAnimator.setDuration(duration); // } // // } // // // public void start() { // if (mAAnimator != null) { // // mAAnimator.start(); // } else if (mNAnimator != null) { // // mNAnimator.start(); // } // // } // } // Path: baselibrary/src/main/java/com/dim/circletreveal/CircleRevealHelper.java import android.animation.Animator; import android.animation.ValueAnimator; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Region; import android.os.Build; import android.view.View; import android.view.ViewAnimationUtils; import com.dim.widget.animation.CRAnimation; package com.dim.circletreveal; /** * Created by zzz40500 on 15/8/26. */ public class CircleRevealHelper { private ValueAnimator mValueAnimator; public CircleRevealHelper(View view) { mView = view; if (view instanceof CircleRevealEnable) { mCircleRevealEnable = (CircleRevealEnable) view; } else { throw new RuntimeException("the View must implements CircleRevealEnable "); } } private Path mPath = new Path(); private View mView; private int mAnchorX, mAnchorY; private float mRadius; private CircleRevealEnable mCircleRevealEnable;
public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/LinearLayoutSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // }
import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.dim.skin.SkinStyle;
package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class LinearLayoutSkinHelper extends ViewSkinHelper { private int mDividerRes; private int mDarkDividerRes; public LinearLayoutSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); mDarkDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightDivider", -1); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/LinearLayoutSkinHelper.java import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.dim.skin.SkinStyle; package com.dim.skin.hepler; /** * Created by zzz40500 on 15/9/4. */ public class LinearLayoutSkinHelper extends ViewSkinHelper { private int mDividerRes; private int mDarkDividerRes; public LinearLayoutSkinHelper(Context context) { super(context); } @Override public void init(View view, AttributeSet attrs) { super.init(view, attrs); if (attrs == null) { mEnable = false; return; } mDividerRes = attrs.getAttributeResourceValue(ANDROIDXML, "divider", -1); mDarkDividerRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightDivider", -1); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void setSkinStyle(SkinStyle skinStyle) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/ViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle;
package com.dim.skin.hepler; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class ViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView;
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/ViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; package com.dim.skin.hepler; /** * @attr ref android.R.styleable#View_background * Created by zzz40500 on 15/9/3. */ public class ViewSkinHelper extends SkinHelper { protected final static String MATERIALDESIGNXML = "http://schemas.android.com/apk/res-auto"; protected final static String ANDROIDXML = "http://schemas.android.com/apk/res/android"; protected View mView;
protected SkinStyle mSkinStyle = SkinStyle.Light;
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/ViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle;
} if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if (!mEnable) { return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } } } @Override public void setCurrentTheme() {
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/ViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; } if (mDarkBackgroundRes == -1) { mDarkBackgroundColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightBackground", -1); } } public void setSkinStyle(SkinStyle skinStyle) { super.setSkinStyle(skinStyle); if (!mEnable) { return; } if (skinStyle == SkinStyle.Light) { if (mLightBackgroundRes != -1) { mView.setBackgroundResource(mLightBackgroundRes); } else if (mLightBackgroundColor != -1) { mView.setBackgroundColor(mLightBackgroundColor); } } else { if (mDarkBackgroundRes != -1) { mView.setBackgroundResource(mDarkBackgroundRes); } else if (mDarkBackgroundColor != -1) { mView.setBackgroundColor(mDarkBackgroundColor); } } } @Override public void setCurrentTheme() {
if (SkinConfig.getSkinStyle(mView.getContext()) == SkinStyle.Dark) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/TextViewSkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.dim.skin.SkinStyle;
mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { mNightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } int mNightTextColorHighlightRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); if (mNightTextColorHighlightRes != -1) { mNightTextColorHighlight = view.getContext().getResources().getColor(mNightTextColorHighlightRes); } else { mNightTextColorHighlight = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); } mNightTextColorLinkRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorLink", -1); if (mNightTextColorLinkRes == -1) { mNightTextColorLink = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorLink", -1); } mNightTextColorHintRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHint", -1); if (mNightTextColorHintRes == -1) { mNightTextColorHint = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHint", -1); } mNightTextColorAppearance = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorAppearance", -1); } @Override
// Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/TextViewSkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.dim.skin.SkinStyle; mNightTextColorRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColor", -1); if (mNightTextColorRes == -1) { mNightTextColor = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColor", -1); } int mNightTextColorHighlightRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); if (mNightTextColorHighlightRes != -1) { mNightTextColorHighlight = view.getContext().getResources().getColor(mNightTextColorHighlightRes); } else { mNightTextColorHighlight = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHighlight", -1); } mNightTextColorLinkRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorLink", -1); if (mNightTextColorLinkRes == -1) { mNightTextColorLink = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorLink", -1); } mNightTextColorHintRes = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorHint", -1); if (mNightTextColorHintRes == -1) { mNightTextColorHint = attrs.getAttributeIntValue(MATERIALDESIGNXML, "nightTextColorHint", -1); } mNightTextColorAppearance = attrs.getAttributeResourceValue(MATERIALDESIGNXML, "nightTextColorAppearance", -1); } @Override
public void setSkinStyle(SkinStyle skinStyle) {
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/LinearLayout.java // public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public LinearLayout(Context context) { // super(context); // init(null); // } // // public LinearLayout(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // @Override // public void setDividerDrawable(Drawable divider) { // super.setDividerDrawable(divider); // } // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // // mSkinHelper.preDraw(this); // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // // mSkinHelper.setSkinStyle(skinStyle); // } // // @Override // public LayoutParams generateLayoutParams(AttributeSet attrs) { // // // return new SLayoutParams(getContext(),attrs); // } // // @Override // public void addView(View child, int index, ViewGroup.LayoutParams params) { // super.addView(child, index, params); // if(params instanceof SLayoutParams){ // ((SLayoutParams) params).setSkinHelper(child); // } // } // // @Override // protected LayoutParams generateDefaultLayoutParams() { // return super.generateDefaultLayoutParams(); // } // // // public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { // // private DefaultViewSkinHelper mSkinHelper; // // public SLayoutParams(Context c, AttributeSet attrs) { // super(c, attrs); // mSkinHelper=SkinHelper.createDeFault(c); // mSkinHelper.init(null,attrs); // } // // public void setSkinHelper(View view){ // mSkinHelper.setView(view); // } // public void setSkinStyle(SkinStyle skinStyle){ // mSkinHelper.setSkinStyle(skinStyle); // } // // public SLayoutParams(int width, int height) { // super(width, height); // } // // public SLayoutParams(int width, int height, float weight) { // super(width, height, weight); // } // // public SLayoutParams(ViewGroup.LayoutParams p) { // super(p); // } // // public SLayoutParams(MarginLayoutParams source) { // super(source); // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public SLayoutParams(LayoutParams source) { // super(source); // } // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.LinearLayout;
package com.dim.skin.hepler; /** * /** * * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by dim on 15/8/27. */ public abstract class SkinHelper { private SkinStyle mSkinStyle; private Context mContext; public SkinHelper(Context context) {
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/LinearLayout.java // public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public LinearLayout(Context context) { // super(context); // init(null); // } // // public LinearLayout(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // @Override // public void setDividerDrawable(Drawable divider) { // super.setDividerDrawable(divider); // } // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // // mSkinHelper.preDraw(this); // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // // mSkinHelper.setSkinStyle(skinStyle); // } // // @Override // public LayoutParams generateLayoutParams(AttributeSet attrs) { // // // return new SLayoutParams(getContext(),attrs); // } // // @Override // public void addView(View child, int index, ViewGroup.LayoutParams params) { // super.addView(child, index, params); // if(params instanceof SLayoutParams){ // ((SLayoutParams) params).setSkinHelper(child); // } // } // // @Override // protected LayoutParams generateDefaultLayoutParams() { // return super.generateDefaultLayoutParams(); // } // // // public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { // // private DefaultViewSkinHelper mSkinHelper; // // public SLayoutParams(Context c, AttributeSet attrs) { // super(c, attrs); // mSkinHelper=SkinHelper.createDeFault(c); // mSkinHelper.init(null,attrs); // } // // public void setSkinHelper(View view){ // mSkinHelper.setView(view); // } // public void setSkinStyle(SkinStyle skinStyle){ // mSkinHelper.setSkinStyle(skinStyle); // } // // public SLayoutParams(int width, int height) { // super(width, height); // } // // public SLayoutParams(int width, int height, float weight) { // super(width, height, weight); // } // // public SLayoutParams(ViewGroup.LayoutParams p) { // super(p); // } // // public SLayoutParams(MarginLayoutParams source) { // super(source); // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public SLayoutParams(LayoutParams source) { // super(source); // } // } // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.LinearLayout; package com.dim.skin.hepler; /** * /** * * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by dim on 15/8/27. */ public abstract class SkinHelper { private SkinStyle mSkinStyle; private Context mContext; public SkinHelper(Context context) {
mSkinStyle = SkinConfig.getSkinStyle(context);
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/skin/hepler/SkinHelper.java
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/LinearLayout.java // public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public LinearLayout(Context context) { // super(context); // init(null); // } // // public LinearLayout(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // @Override // public void setDividerDrawable(Drawable divider) { // super.setDividerDrawable(divider); // } // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // // mSkinHelper.preDraw(this); // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // // mSkinHelper.setSkinStyle(skinStyle); // } // // @Override // public LayoutParams generateLayoutParams(AttributeSet attrs) { // // // return new SLayoutParams(getContext(),attrs); // } // // @Override // public void addView(View child, int index, ViewGroup.LayoutParams params) { // super.addView(child, index, params); // if(params instanceof SLayoutParams){ // ((SLayoutParams) params).setSkinHelper(child); // } // } // // @Override // protected LayoutParams generateDefaultLayoutParams() { // return super.generateDefaultLayoutParams(); // } // // // public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { // // private DefaultViewSkinHelper mSkinHelper; // // public SLayoutParams(Context c, AttributeSet attrs) { // super(c, attrs); // mSkinHelper=SkinHelper.createDeFault(c); // mSkinHelper.init(null,attrs); // } // // public void setSkinHelper(View view){ // mSkinHelper.setView(view); // } // public void setSkinStyle(SkinStyle skinStyle){ // mSkinHelper.setSkinStyle(skinStyle); // } // // public SLayoutParams(int width, int height) { // super(width, height); // } // // public SLayoutParams(int width, int height, float weight) { // super(width, height, weight); // } // // public SLayoutParams(ViewGroup.LayoutParams p) { // super(p); // } // // public SLayoutParams(MarginLayoutParams source) { // super(source); // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public SLayoutParams(LayoutParams source) { // super(source); // } // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.LinearLayout;
package com.dim.skin.hepler; /** * /** * * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by dim on 15/8/27. */ public abstract class SkinHelper { private SkinStyle mSkinStyle; private Context mContext; public SkinHelper(Context context) { mSkinStyle = SkinConfig.getSkinStyle(context); mContext = context; } public abstract void init(View view, AttributeSet attrs); public void setSkinStyle(SkinStyle skinStyle) { mSkinStyle = skinStyle; } public static SkinHelper create(View v) { if (v instanceof TextView) { return new TextViewSkinHelper(v.getContext()); } else if (v instanceof ListView) { return new ListViewSkinHelper(v.getContext());
// Path: baselibrary/src/main/java/com/dim/skin/SkinConfig.java // public class SkinConfig { // // public static SkinStyle getSkinStyle(Context context) { // SharedPreferences sharedPreferences = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE); // boolean nightMode = sharedPreferences.getBoolean("nightMode", false); // return nightMode ? SkinStyle.Dark : SkinStyle.Light; // } // // public static void setSkinStyle(Context context, SkinStyle skinStyle) { // SharedPreferences.Editor editor = context.getSharedPreferences("SkinStyle", // Activity.MODE_PRIVATE).edit(); // editor.putBoolean("nightMode", skinStyle == SkinStyle.Dark).apply(); // } // // } // // Path: baselibrary/src/main/java/com/dim/skin/SkinStyle.java // public enum SkinStyle { // // Dark, // Light//默认Light // } // // Path: baselibrary/src/main/java/com/dim/widget/LinearLayout.java // public class LinearLayout extends android.widget.LinearLayout implements CircleRevealEnable,SkinEnable { // // private CircleRevealHelper mCircleRevealHelper ; // private SkinHelper mSkinHelper; // // public LinearLayout(Context context) { // super(context); // init(null); // } // // public LinearLayout(Context context, AttributeSet attrs) { // super(context, attrs); // init(attrs); // } // // private void init(AttributeSet attrs) { // // mSkinHelper=SkinHelper.create(this); // mSkinHelper.init(this, attrs); // mSkinHelper.setCurrentTheme(); // mCircleRevealHelper=new CircleRevealHelper(this); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public LinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs); // } // // @Override // public void setDividerDrawable(Drawable divider) { // super.setDividerDrawable(divider); // } // // @Override // public void setOnClickListener(OnClickListener l) { // super.setOnClickListener(new SingleClickListener(l)); // } // // @Override // public void draw(Canvas canvas) { // // mSkinHelper.preDraw(this); // mCircleRevealHelper.draw(canvas); // } // // // @Override // public void superDraw(Canvas canvas) { // super.draw(canvas); // } // // // @Override // public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) { // // return mCircleRevealHelper.circularReveal(centerX,centerY,startRadius,endRadius); // } // // @Override // public void setSkinStyle(SkinStyle skinStyle) { // // // mSkinHelper.setSkinStyle(skinStyle); // } // // @Override // public LayoutParams generateLayoutParams(AttributeSet attrs) { // // // return new SLayoutParams(getContext(),attrs); // } // // @Override // public void addView(View child, int index, ViewGroup.LayoutParams params) { // super.addView(child, index, params); // if(params instanceof SLayoutParams){ // ((SLayoutParams) params).setSkinHelper(child); // } // } // // @Override // protected LayoutParams generateDefaultLayoutParams() { // return super.generateDefaultLayoutParams(); // } // // // public class SLayoutParams extends android.widget.LinearLayout.LayoutParams implements SLayoutParamsI { // // private DefaultViewSkinHelper mSkinHelper; // // public SLayoutParams(Context c, AttributeSet attrs) { // super(c, attrs); // mSkinHelper=SkinHelper.createDeFault(c); // mSkinHelper.init(null,attrs); // } // // public void setSkinHelper(View view){ // mSkinHelper.setView(view); // } // public void setSkinStyle(SkinStyle skinStyle){ // mSkinHelper.setSkinStyle(skinStyle); // } // // public SLayoutParams(int width, int height) { // super(width, height); // } // // public SLayoutParams(int width, int height, float weight) { // super(width, height, weight); // } // // public SLayoutParams(ViewGroup.LayoutParams p) { // super(p); // } // // public SLayoutParams(MarginLayoutParams source) { // super(source); // } // // @TargetApi(Build.VERSION_CODES.KITKAT) // public SLayoutParams(LayoutParams source) { // super(source); // } // } // } // Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinHelper.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; import android.widget.TextView; import com.dim.skin.SkinConfig; import com.dim.skin.SkinStyle; import com.dim.widget.LinearLayout; package com.dim.skin.hepler; /** * /** * * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * Created by dim on 15/8/27. */ public abstract class SkinHelper { private SkinStyle mSkinStyle; private Context mContext; public SkinHelper(Context context) { mSkinStyle = SkinConfig.getSkinStyle(context); mContext = context; } public abstract void init(View view, AttributeSet attrs); public void setSkinStyle(SkinStyle skinStyle) { mSkinStyle = skinStyle; } public static SkinHelper create(View v) { if (v instanceof TextView) { return new TextViewSkinHelper(v.getContext()); } else if (v instanceof ListView) { return new ListViewSkinHelper(v.getContext());
} else if (v instanceof LinearLayout) {
zzz40500/ThemeDemo
app/src/main/java/com/dim/themedemo/adapter/itemhandler/TestItemHandler.java
// Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java // public class SkinCompat { // // public interface SkinStyleChangeListener { // void beforeChange(); // // void afterChange(); // } // // /** // * @param activity 当前 Activity // * @param skinStyle Dark(夜间),Light(日间) // * @param skinStyleChangeListener (转换监听器) // */ // public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { // // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ // View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); // changeSkinStyle(view, skinStyle); // SkinConfig.setSkinStyle(activity, skinStyle); // // } // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // } // // public static void setCurrentTheme(View v, SkinStyleChangeListener skinStyleChangeListener) { // // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // // // } // // public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // } // // // public static void changeSkinStyle(View view, SkinStyle skinStyle) { // // changeSkinView(view, skinStyle); // // if (view instanceof ViewGroup) { // for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { // View v = ((ViewGroup) view).getChildAt(i); // changeSkinStyle(v, skinStyle); // } // } // } // // public static void changeSkinView(View view, SkinStyle skinStyle) { // if (view instanceof SkinEnable) { // ((SkinEnable) view).setSkinStyle(skinStyle); // } else { // ViewGroup.LayoutParams params = view.getLayoutParams(); // if (params instanceof SLayoutParamsI) { // ((SLayoutParamsI) params).setSkinStyle(skinStyle); // } // } // } // // // }
import android.view.View; import com.dim.skin.hepler.SkinCompat; import com.mingle.themedemo.R; import kale.adapter.handler.SimpleItemHandler; import kale.adapter.util.ViewHolder;
package com.dim.themedemo.adapter.itemhandler; /** * Created by zzz40500 on 15/9/5. */ public class TestItemHandler extends SimpleItemHandler<String> { @Override public void onBindView33(ViewHolder viewHolder, String s, int i) {
// Path: baselibrary/src/main/java/com/dim/skin/hepler/SkinCompat.java // public class SkinCompat { // // public interface SkinStyleChangeListener { // void beforeChange(); // // void afterChange(); // } // // /** // * @param activity 当前 Activity // * @param skinStyle Dark(夜间),Light(日间) // * @param skinStyleChangeListener (转换监听器) // */ // public static void setSkinStyle(Activity activity, SkinStyle skinStyle, SkinStyleChangeListener skinStyleChangeListener) { // // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // // if(SkinConfig.getSkinStyle(activity)!=skinStyle){ // View view = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); // changeSkinStyle(view, skinStyle); // SkinConfig.setSkinStyle(activity, skinStyle); // // } // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // } // // public static void setCurrentTheme(View v, SkinStyleChangeListener skinStyleChangeListener) { // // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // changeSkinStyle(v, SkinConfig.getSkinStyle(v.getContext())); // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // // // } // // public static void setCurrentTheme(Activity activity, SkinStyleChangeListener skinStyleChangeListener) { // if (skinStyleChangeListener != null) // skinStyleChangeListener.beforeChange(); // setSkinStyle(activity, SkinConfig.getSkinStyle(activity), null); // if (skinStyleChangeListener != null) // skinStyleChangeListener.afterChange(); // } // // // public static void changeSkinStyle(View view, SkinStyle skinStyle) { // // changeSkinView(view, skinStyle); // // if (view instanceof ViewGroup) { // for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { // View v = ((ViewGroup) view).getChildAt(i); // changeSkinStyle(v, skinStyle); // } // } // } // // public static void changeSkinView(View view, SkinStyle skinStyle) { // if (view instanceof SkinEnable) { // ((SkinEnable) view).setSkinStyle(skinStyle); // } else { // ViewGroup.LayoutParams params = view.getLayoutParams(); // if (params instanceof SLayoutParamsI) { // ((SLayoutParamsI) params).setSkinStyle(skinStyle); // } // } // } // // // } // Path: app/src/main/java/com/dim/themedemo/adapter/itemhandler/TestItemHandler.java import android.view.View; import com.dim.skin.hepler.SkinCompat; import com.mingle.themedemo.R; import kale.adapter.handler.SimpleItemHandler; import kale.adapter.util.ViewHolder; package com.dim.themedemo.adapter.itemhandler; /** * Created by zzz40500 on 15/9/5. */ public class TestItemHandler extends SimpleItemHandler<String> { @Override public void onBindView33(ViewHolder viewHolder, String s, int i) {
SkinCompat.setCurrentTheme(viewHolder.getConvertView(),null);
zzz40500/ThemeDemo
baselibrary/src/main/java/com/dim/circletreveal/CircularRevealCompat.java
// Path: baselibrary/src/main/java/com/dim/widget/animation/CRAnimation.java // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public class CRAnimation { // // private ValueAnimator mNAnimator; // private android.animation.Animator mAAnimator; // // // public CRAnimation(ValueAnimator NAnimator) { // // mNAnimator = NAnimator; // } // // public CRAnimation(Animator AAnimator) { // mAAnimator = AAnimator; // } // // public void setInterpolator(Interpolator interpolator) { // // if (mAAnimator != null) { // // mAAnimator.setInterpolator(interpolator); // } else if (mNAnimator != null) { // // mNAnimator.setInterpolator(interpolator); // } // // } // // public void setStartDelay(long startDelay) { // // if (mAAnimator != null) { // // mAAnimator.setStartDelay(startDelay); // } else if (mNAnimator != null) { // // mNAnimator.setStartDelay(startDelay); // } // // } // // // public void addListener(final SimpleAnimListener simpleAnimListener) { // // if (mAAnimator != null) { // mAAnimator.addListener(new android.animation.Animator.AnimatorListener() { // @Override // public void onAnimationStart(android.animation.Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(android.animation.Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(android.animation.Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(android.animation.Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } else if (mNAnimator != null) { // mNAnimator.addListener(new Animator.AnimatorListener() { // @Override // public void onAnimationStart(Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } // // } // // public void end() { // if (mAAnimator != null) { // // mAAnimator.end(); // } else if (mNAnimator != null) { // // mNAnimator.end(); // } // // } // // public void cancel() { // if (mAAnimator != null) { // // mAAnimator.cancel(); // } else if (mNAnimator != null) { // // mNAnimator.cancel(); // } // } // // public void setDuration(long duration) { // // if (mAAnimator != null) { // mAAnimator.setDuration(duration); // } else if (mNAnimator != null) { // mNAnimator.setDuration(duration); // } // // } // // // public void start() { // if (mAAnimator != null) { // // mAAnimator.start(); // } else if (mNAnimator != null) { // // mNAnimator.start(); // } // // } // }
import android.support.annotation.Nullable; import android.view.View; import com.dim.widget.animation.CRAnimation;
package com.dim.circletreveal; /** * Created by zzz40500 on 15/8/27. */ public class CircularRevealCompat { public View mView; public CircularRevealCompat(View view) { mView = view; } @Nullable
// Path: baselibrary/src/main/java/com/dim/widget/animation/CRAnimation.java // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public class CRAnimation { // // private ValueAnimator mNAnimator; // private android.animation.Animator mAAnimator; // // // public CRAnimation(ValueAnimator NAnimator) { // // mNAnimator = NAnimator; // } // // public CRAnimation(Animator AAnimator) { // mAAnimator = AAnimator; // } // // public void setInterpolator(Interpolator interpolator) { // // if (mAAnimator != null) { // // mAAnimator.setInterpolator(interpolator); // } else if (mNAnimator != null) { // // mNAnimator.setInterpolator(interpolator); // } // // } // // public void setStartDelay(long startDelay) { // // if (mAAnimator != null) { // // mAAnimator.setStartDelay(startDelay); // } else if (mNAnimator != null) { // // mNAnimator.setStartDelay(startDelay); // } // // } // // // public void addListener(final SimpleAnimListener simpleAnimListener) { // // if (mAAnimator != null) { // mAAnimator.addListener(new android.animation.Animator.AnimatorListener() { // @Override // public void onAnimationStart(android.animation.Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(android.animation.Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(android.animation.Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(android.animation.Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } else if (mNAnimator != null) { // mNAnimator.addListener(new Animator.AnimatorListener() { // @Override // public void onAnimationStart(Animator animation) { // simpleAnimListener.onAnimationStart(CRAnimation.this); // } // // @Override // public void onAnimationEnd(Animator animation) { // simpleAnimListener.onAnimationEnd(CRAnimation.this); // } // // @Override // public void onAnimationCancel(Animator animation) { // simpleAnimListener.onAnimationCancel(CRAnimation.this); // } // // @Override // public void onAnimationRepeat(Animator animation) { // simpleAnimListener.onAnimationRepeat(CRAnimation.this); // } // }); // } // // } // // public void end() { // if (mAAnimator != null) { // // mAAnimator.end(); // } else if (mNAnimator != null) { // // mNAnimator.end(); // } // // } // // public void cancel() { // if (mAAnimator != null) { // // mAAnimator.cancel(); // } else if (mNAnimator != null) { // // mNAnimator.cancel(); // } // } // // public void setDuration(long duration) { // // if (mAAnimator != null) { // mAAnimator.setDuration(duration); // } else if (mNAnimator != null) { // mNAnimator.setDuration(duration); // } // // } // // // public void start() { // if (mAAnimator != null) { // // mAAnimator.start(); // } else if (mNAnimator != null) { // // mNAnimator.start(); // } // // } // } // Path: baselibrary/src/main/java/com/dim/circletreveal/CircularRevealCompat.java import android.support.annotation.Nullable; import android.view.View; import com.dim.widget.animation.CRAnimation; package com.dim.circletreveal; /** * Created by zzz40500 on 15/8/27. */ public class CircularRevealCompat { public View mView; public CircularRevealCompat(View view) { mView = view; } @Nullable
public CRAnimation circularReveal(int centerX, int centerY, float startRadius, float endRadius) {
viadeo/axon-kafka-terminal
src/test/java/com/viadeo/axonframework/eventhandling/cluster/ClassnameDynamicClusterSelectorUTest.java
// Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupb/GroupB.java // public interface GroupB { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupa/GroupA.java // public interface GroupA { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // }
import com.viadeo.axonframework.eventhandling.cluster.fixture.groupb.GroupB; import com.viadeo.axonframework.eventhandling.cluster.fixture.groupa.GroupA; import org.axonframework.eventhandling.Cluster; import org.axonframework.eventhandling.SimpleCluster; import org.junit.Test; import static org.junit.Assert.*;
// Then throws an exception } @Test(expected = NullPointerException.class) public void init_withNullAsGivenClusterFactory_throwException(){ // Given nothing // When new ClassnameDynamicClusterSelector("", null); // Then throws an exception } @Test(expected = NullPointerException.class) public void selectCluster_withNullAsGivenEventListener_throwException() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); // When clusterSelector.selectCluster(null); // Then throws an exception } @Test public void selectCluster_withEventListenerB_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector();
// Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupb/GroupB.java // public interface GroupB { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupa/GroupA.java // public interface GroupA { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/ClassnameDynamicClusterSelectorUTest.java import com.viadeo.axonframework.eventhandling.cluster.fixture.groupb.GroupB; import com.viadeo.axonframework.eventhandling.cluster.fixture.groupa.GroupA; import org.axonframework.eventhandling.Cluster; import org.axonframework.eventhandling.SimpleCluster; import org.junit.Test; import static org.junit.Assert.*; // Then throws an exception } @Test(expected = NullPointerException.class) public void init_withNullAsGivenClusterFactory_throwException(){ // Given nothing // When new ClassnameDynamicClusterSelector("", null); // Then throws an exception } @Test(expected = NullPointerException.class) public void selectCluster_withNullAsGivenEventListener_throwException() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); // When clusterSelector.selectCluster(null); // Then throws an exception } @Test public void selectCluster_withEventListenerB_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector();
final GroupB.EventListenerB eventListenerB = new GroupB.EventListenerB();
viadeo/axon-kafka-terminal
src/test/java/com/viadeo/axonframework/eventhandling/cluster/ClassnameDynamicClusterSelectorUTest.java
// Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupb/GroupB.java // public interface GroupB { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupa/GroupA.java // public interface GroupA { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // }
import com.viadeo.axonframework.eventhandling.cluster.fixture.groupb.GroupB; import com.viadeo.axonframework.eventhandling.cluster.fixture.groupa.GroupA; import org.axonframework.eventhandling.Cluster; import org.axonframework.eventhandling.SimpleCluster; import org.junit.Test; import static org.junit.Assert.*;
public void selectCluster_withNullAsGivenEventListener_throwException() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); // When clusterSelector.selectCluster(null); // Then throws an exception } @Test public void selectCluster_withEventListenerB_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); final GroupB.EventListenerB eventListenerB = new GroupB.EventListenerB(); // When final Cluster cluster = clusterSelector.selectCluster(eventListenerB); // Then assertNotNull(cluster); assertEquals("groupb", cluster.getName()); } @Test public void selectCluster_withEventListenerA_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector();
// Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupb/GroupB.java // public interface GroupB { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/fixture/groupa/GroupA.java // public interface GroupA { // // class EventListenerA extends EventListenerWrapper { // public EventListenerA() { // this(null); // } // // public EventListenerA(final EventListener delegate) { // super(delegate); // } // } // // class EventListenerB extends EventListenerWrapper { // public EventListenerB() { // this(null); // } // // public EventListenerB(final EventListener delegate) { // super(delegate); // } // } // } // Path: src/test/java/com/viadeo/axonframework/eventhandling/cluster/ClassnameDynamicClusterSelectorUTest.java import com.viadeo.axonframework.eventhandling.cluster.fixture.groupb.GroupB; import com.viadeo.axonframework.eventhandling.cluster.fixture.groupa.GroupA; import org.axonframework.eventhandling.Cluster; import org.axonframework.eventhandling.SimpleCluster; import org.junit.Test; import static org.junit.Assert.*; public void selectCluster_withNullAsGivenEventListener_throwException() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); // When clusterSelector.selectCluster(null); // Then throws an exception } @Test public void selectCluster_withEventListenerB_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector(); final GroupB.EventListenerB eventListenerB = new GroupB.EventListenerB(); // When final Cluster cluster = clusterSelector.selectCluster(eventListenerB); // Then assertNotNull(cluster); assertEquals("groupb", cluster.getName()); } @Test public void selectCluster_withEventListenerA_returnClusterNamedAfterPackageOfListener() throws Exception { // Given final ClassnameDynamicClusterSelector clusterSelector = initClusterSelector();
final GroupA.EventListenerA eventListenerA = new GroupA.EventListenerA();
viadeo/axon-kafka-terminal
src/test/java/com/viadeo/axonframework/eventhandling/TestEventBus.java
// Path: src/main/java/com/viadeo/axonframework/eventhandling/cluster/ClusterSelectorFactory.java // public interface ClusterSelectorFactory { // ClusterSelector create(); // }
import com.google.common.collect.Lists; import com.viadeo.axonframework.eventhandling.cluster.ClusterSelectorFactory; import com.viadeo.axonframework.eventhandling.terminal.kafka.*; import org.axonframework.domain.EventMessage; import org.axonframework.eventhandling.ClusteringEventBus; import org.axonframework.eventhandling.EventBus; import org.axonframework.eventhandling.EventBusTerminal; import org.axonframework.eventhandling.EventListener; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.UUID; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState;
package com.viadeo.axonframework.eventhandling; public class TestEventBus extends ExternalResource { private static final Logger LOGGER = LoggerFactory.getLogger(TestEventBus.class); private final KafkaTerminalFactory terminalFactory;
// Path: src/main/java/com/viadeo/axonframework/eventhandling/cluster/ClusterSelectorFactory.java // public interface ClusterSelectorFactory { // ClusterSelector create(); // } // Path: src/test/java/com/viadeo/axonframework/eventhandling/TestEventBus.java import com.google.common.collect.Lists; import com.viadeo.axonframework.eventhandling.cluster.ClusterSelectorFactory; import com.viadeo.axonframework.eventhandling.terminal.kafka.*; import org.axonframework.domain.EventMessage; import org.axonframework.eventhandling.ClusteringEventBus; import org.axonframework.eventhandling.EventBus; import org.axonframework.eventhandling.EventBusTerminal; import org.axonframework.eventhandling.EventListener; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.UUID; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; package com.viadeo.axonframework.eventhandling; public class TestEventBus extends ExternalResource { private static final Logger LOGGER = LoggerFactory.getLogger(TestEventBus.class); private final KafkaTerminalFactory terminalFactory;
private final ClusterSelectorFactory clusterSelectorFactory;
evant/redux
sample-android/src/main/java/com/example/sample_android/reducer/RemoveReducer.java
// Path: sample-android/src/main/java/com/example/sample_android/action/Remove.java // @AutoValue // public abstract class Remove implements Action { // // public static Remove create(int id) { // return new AutoValue_Remove(id); // } // // public abstract int id(); // } // // Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // } // // Path: sample-android/src/main/java/com/example/sample_android/state/TodoList.java // @AutoValue // public abstract class TodoList { // // public static TodoList initial() { // return new AutoValue_TodoList(true, Collections.<TodoItem>emptyList()); // } // // public static TodoList create(boolean loading, List<TodoItem> items) { // return new AutoValue_TodoList(loading, Collections.unmodifiableList(items)); // } // // public abstract boolean loading(); // // public abstract List<TodoItem> items(); // } // // Path: redux-core/src/main/java/me/tatarka/redux/Reducer.java // public interface Reducer<A, S> { // S reduce(A action, S state); // }
import com.example.sample_android.action.Remove; import com.example.sample_android.state.TodoItem; import com.example.sample_android.state.TodoList; import java.util.ArrayList; import java.util.List; import me.tatarka.redux.Reducer;
package com.example.sample_android.reducer; public class RemoveReducer implements Reducer<Remove, TodoList> { @Override public TodoList reduce(Remove action, TodoList state) {
// Path: sample-android/src/main/java/com/example/sample_android/action/Remove.java // @AutoValue // public abstract class Remove implements Action { // // public static Remove create(int id) { // return new AutoValue_Remove(id); // } // // public abstract int id(); // } // // Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // } // // Path: sample-android/src/main/java/com/example/sample_android/state/TodoList.java // @AutoValue // public abstract class TodoList { // // public static TodoList initial() { // return new AutoValue_TodoList(true, Collections.<TodoItem>emptyList()); // } // // public static TodoList create(boolean loading, List<TodoItem> items) { // return new AutoValue_TodoList(loading, Collections.unmodifiableList(items)); // } // // public abstract boolean loading(); // // public abstract List<TodoItem> items(); // } // // Path: redux-core/src/main/java/me/tatarka/redux/Reducer.java // public interface Reducer<A, S> { // S reduce(A action, S state); // } // Path: sample-android/src/main/java/com/example/sample_android/reducer/RemoveReducer.java import com.example.sample_android.action.Remove; import com.example.sample_android.state.TodoItem; import com.example.sample_android.state.TodoList; import java.util.ArrayList; import java.util.List; import me.tatarka.redux.Reducer; package com.example.sample_android.reducer; public class RemoveReducer implements Reducer<Remove, TodoList> { @Override public TodoList reduce(Remove action, TodoList state) {
List<TodoItem> items = new ArrayList<>(state.items());
evant/redux
redux-rx2/src/test/java/me/tatarka/redux/rx2/ObservableDispatcherTest.java
// Path: redux-core/src/main/java/me/tatarka/redux/Dispatcher.java // public abstract class Dispatcher<A, R> { // // /** // * Constructs a {@code Dispatcher} from the given {@link Store} and {@link Reducer}. {@link #dispatch(Object)} will // * run the action through the reducer and update the store with the resulting state. // * // * @param <S> The type of state in the store. // * @param <A> The type of action. // * @return the action dispatched. // */ // public static <S, A> Dispatcher<A, A> forStore(final Store<S> store, final Reducer<A, S> reducer) { // if (store == null) { // throw new NullPointerException("store==null"); // } // if (reducer == null) { // throw new NullPointerException("reducer==null"); // } // return new Dispatcher<A, A>() { // @Override // public A dispatch(A action) { // store.setState(reducer.reduce(action, store.getState())); // return action; // } // }; // } // // /** // * Dispatches the given action. // */ // public abstract R dispatch(A action); // // /** // * Returns a new {@code Dispatcher} that runs the given {@link Middleware}. // */ // public final Dispatcher<A, R> chain(final Middleware<A, R> middleware) { // if (middleware == null) { // throw new NullPointerException("middleware==null"); // } // return new Dispatcher<A, R>() { // @Override // public R dispatch(A action) { // return middleware.dispatch(new Middleware.Next<A, R>() { // @Override // public R next(A action) { // return Dispatcher.this.dispatch(action); // } // }, action); // } // }; // } // // /** // * Returns a new {@code Dispatcher} that runs the given collection of {@link Middleware}. // */ // public final Dispatcher<A, R> chain(Iterable<Middleware<A, R>> middleware) { // return chain(middleware.iterator()); // } // // /** // * Returns a new {@code Dispatcher} that runs the given collection of {@link Middleware}. // */ // @SafeVarargs // public final Dispatcher<A, R> chain(Middleware<A, R>... middleware) { // return chain(Arrays.asList(middleware)); // } // // private Dispatcher<A, R> chain(Iterator<Middleware<A, R>> itr) { // if (!itr.hasNext()) { // return this; // } // return chain(itr.next()).chain(itr); // } // } // // Path: redux-core/src/main/java/me/tatarka/redux/Reducer.java // public interface Reducer<A, S> { // S reduce(A action, S state); // } // // Path: redux-core/src/main/java/me/tatarka/redux/SimpleStore.java // public class SimpleStore<S> implements Store<S> { // // private volatile S state; // private final CopyOnWriteArrayList<Listener<S>> listeners = new CopyOnWriteArrayList<>(); // // public SimpleStore(S initialState) { // setState(initialState); // } // // @Override // public S getState() { // return state; // } // // @Override // public void setState(S newState) { // if (!equals(state, newState)) { // state = newState; // for (Listener<S> listener : listeners) { // listener.onNewState(state); // } // } // } // // /** // * Registers as listener to receive state changes. The current state will be delivered // * immediately. // */ // public void addListener(Listener<S> listener) { // listeners.add(listener); // listener.onNewState(state); // } // // /** // * Removes the listener so it no longer receives state changes. // */ // public void removeListener(Listener<S> listener) { // listeners.remove(listener); // } // // public interface Listener<S> { // /** // * Called when a new state is set. This is called on the same thread as or {@link #setState(Object)}. // */ // void onNewState(S state); // } // // private static boolean equals(Object var0, Object var1) { // return var0 == var1 || var0 != null && var0.equals(var1); // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.subscribers.TestSubscriber; import me.tatarka.redux.Dispatcher; import me.tatarka.redux.Reducer; import me.tatarka.redux.SimpleStore; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.Assert.assertTrue;
package me.tatarka.redux.rx2; @RunWith(JUnit4.class) public class ObservableDispatcherTest { @Test public void subscription_receives_initial_state() {
// Path: redux-core/src/main/java/me/tatarka/redux/Dispatcher.java // public abstract class Dispatcher<A, R> { // // /** // * Constructs a {@code Dispatcher} from the given {@link Store} and {@link Reducer}. {@link #dispatch(Object)} will // * run the action through the reducer and update the store with the resulting state. // * // * @param <S> The type of state in the store. // * @param <A> The type of action. // * @return the action dispatched. // */ // public static <S, A> Dispatcher<A, A> forStore(final Store<S> store, final Reducer<A, S> reducer) { // if (store == null) { // throw new NullPointerException("store==null"); // } // if (reducer == null) { // throw new NullPointerException("reducer==null"); // } // return new Dispatcher<A, A>() { // @Override // public A dispatch(A action) { // store.setState(reducer.reduce(action, store.getState())); // return action; // } // }; // } // // /** // * Dispatches the given action. // */ // public abstract R dispatch(A action); // // /** // * Returns a new {@code Dispatcher} that runs the given {@link Middleware}. // */ // public final Dispatcher<A, R> chain(final Middleware<A, R> middleware) { // if (middleware == null) { // throw new NullPointerException("middleware==null"); // } // return new Dispatcher<A, R>() { // @Override // public R dispatch(A action) { // return middleware.dispatch(new Middleware.Next<A, R>() { // @Override // public R next(A action) { // return Dispatcher.this.dispatch(action); // } // }, action); // } // }; // } // // /** // * Returns a new {@code Dispatcher} that runs the given collection of {@link Middleware}. // */ // public final Dispatcher<A, R> chain(Iterable<Middleware<A, R>> middleware) { // return chain(middleware.iterator()); // } // // /** // * Returns a new {@code Dispatcher} that runs the given collection of {@link Middleware}. // */ // @SafeVarargs // public final Dispatcher<A, R> chain(Middleware<A, R>... middleware) { // return chain(Arrays.asList(middleware)); // } // // private Dispatcher<A, R> chain(Iterator<Middleware<A, R>> itr) { // if (!itr.hasNext()) { // return this; // } // return chain(itr.next()).chain(itr); // } // } // // Path: redux-core/src/main/java/me/tatarka/redux/Reducer.java // public interface Reducer<A, S> { // S reduce(A action, S state); // } // // Path: redux-core/src/main/java/me/tatarka/redux/SimpleStore.java // public class SimpleStore<S> implements Store<S> { // // private volatile S state; // private final CopyOnWriteArrayList<Listener<S>> listeners = new CopyOnWriteArrayList<>(); // // public SimpleStore(S initialState) { // setState(initialState); // } // // @Override // public S getState() { // return state; // } // // @Override // public void setState(S newState) { // if (!equals(state, newState)) { // state = newState; // for (Listener<S> listener : listeners) { // listener.onNewState(state); // } // } // } // // /** // * Registers as listener to receive state changes. The current state will be delivered // * immediately. // */ // public void addListener(Listener<S> listener) { // listeners.add(listener); // listener.onNewState(state); // } // // /** // * Removes the listener so it no longer receives state changes. // */ // public void removeListener(Listener<S> listener) { // listeners.remove(listener); // } // // public interface Listener<S> { // /** // * Called when a new state is set. This is called on the same thread as or {@link #setState(Object)}. // */ // void onNewState(S state); // } // // private static boolean equals(Object var0, Object var1) { // return var0 == var1 || var0 != null && var0.equals(var1); // } // } // Path: redux-rx2/src/test/java/me/tatarka/redux/rx2/ObservableDispatcherTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.subscribers.TestSubscriber; import me.tatarka.redux.Dispatcher; import me.tatarka.redux.Reducer; import me.tatarka.redux.SimpleStore; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.Assert.assertTrue; package me.tatarka.redux.rx2; @RunWith(JUnit4.class) public class ObservableDispatcherTest { @Test public void subscription_receives_initial_state() {
SimpleStore<String> store = new SimpleStore<>("test1");
evant/redux
sample-android/src/main/java/com/example/sample_android/Datastore.java
// Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // }
import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import com.example.sample_android.state.TodoItem; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.example.sample_android; public class Datastore { // poor-man's persistence private SharedPreferences prefs; public Datastore(Context context) { prefs = context.getSharedPreferences("datastore", Context.MODE_PRIVATE); }
// Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // } // Path: sample-android/src/main/java/com/example/sample_android/Datastore.java import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import com.example.sample_android.state.TodoItem; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.example.sample_android; public class Datastore { // poor-man's persistence private SharedPreferences prefs; public Datastore(Context context) { prefs = context.getSharedPreferences("datastore", Context.MODE_PRIVATE); }
public void store(List<TodoItem> items) {
evant/redux
redux-monitor/src/main/java/me/tatarka/redux/monitor/MonitorMiddleware.java
// Path: redux-core/src/main/java/me/tatarka/redux/Store.java // public interface Store<S> { // // /** // * Returns the current state of the store. // */ // S getState(); // // /** // * Sets the state of the store. Warning! You should not call this in normal application code, // * instead preferring to update it through dispatching an action. It is however, useful for // * tests. // */ // void setState(S state); // } // // Path: redux-core/src/main/java/me/tatarka/redux/middleware/Middleware.java // public interface Middleware<A, R> { // // /** // * Called when an action is dispatched. // * // * @param next Dispatch to the next middleware or actually update the state if there is none. // * You can chose to call this anywhere to see the state before and after it has // * changed or not at all to drop the action. // * @param action This action that was dispatched. // */ // R dispatch(Next<A, R> next, A action); // // interface Next<A, R> { // R next(A action); // } // }
import com.neovisionaries.ws.client.WebSocketException; import com.neovisionaries.ws.client.WebSocketFrame; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import io.github.sac.BasicListener; import io.github.sac.Socket; import me.tatarka.redux.Store; import me.tatarka.redux.middleware.Middleware;
package me.tatarka.redux.monitor; public class MonitorMiddleware<S, A, R> implements Middleware<A, R> { private final Config config;
// Path: redux-core/src/main/java/me/tatarka/redux/Store.java // public interface Store<S> { // // /** // * Returns the current state of the store. // */ // S getState(); // // /** // * Sets the state of the store. Warning! You should not call this in normal application code, // * instead preferring to update it through dispatching an action. It is however, useful for // * tests. // */ // void setState(S state); // } // // Path: redux-core/src/main/java/me/tatarka/redux/middleware/Middleware.java // public interface Middleware<A, R> { // // /** // * Called when an action is dispatched. // * // * @param next Dispatch to the next middleware or actually update the state if there is none. // * You can chose to call this anywhere to see the state before and after it has // * changed or not at all to drop the action. // * @param action This action that was dispatched. // */ // R dispatch(Next<A, R> next, A action); // // interface Next<A, R> { // R next(A action); // } // } // Path: redux-monitor/src/main/java/me/tatarka/redux/monitor/MonitorMiddleware.java import com.neovisionaries.ws.client.WebSocketException; import com.neovisionaries.ws.client.WebSocketFrame; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import io.github.sac.BasicListener; import io.github.sac.Socket; import me.tatarka.redux.Store; import me.tatarka.redux.middleware.Middleware; package me.tatarka.redux.monitor; public class MonitorMiddleware<S, A, R> implements Middleware<A, R> { private final Config config;
private final Store<S> store;
evant/redux
sample-android/src/main/java/com/example/sample_android/action/Load.java
// Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // }
import com.example.sample_android.state.TodoItem; import com.google.auto.value.AutoValue; import java.util.List;
package com.example.sample_android.action; @AutoValue public abstract class Load implements Action {
// Path: sample-android/src/main/java/com/example/sample_android/state/TodoItem.java // @AutoValue // public abstract class TodoItem { // // public static TodoItem create(int id, String text, boolean done) { // return new AutoValue_TodoItem(id, text, done); // } // // public abstract int id(); // // public abstract String text(); // // public abstract boolean done(); // } // Path: sample-android/src/main/java/com/example/sample_android/action/Load.java import com.example.sample_android.state.TodoItem; import com.google.auto.value.AutoValue; import java.util.List; package com.example.sample_android.action; @AutoValue public abstract class Load implements Action {
public static Load create(List<TodoItem> items) {
evant/redux
redux-thunk/src/test/java/me/tatarka/redux/ThunkDispatcherTest.java
// Path: redux-core/src/main/java/me/tatarka/redux/middleware/TestMiddleware.java // public class TestMiddleware<S, A, R> implements Middleware<A, R> { // // private final Store<S> store; // private final List<A> actions = new ArrayList<>(); // private final List<S> states = new ArrayList<>(); // // public TestMiddleware(Store<S> store) { // this.store = store; // states.add(store.getState()); // } // // @Override // public R dispatch(Next<A, R> next, A action) { // actions.add(action); // R result = next.next(action); // states.add(store.getState()); // return result; // } // // /** // * Returns all actions that have been dispatched. // */ // public List<A> actions() { // return Collections.unmodifiableList(actions); // } // // /** // * Returns all states. The first state is before any action has been dispatched. Each // * subsequent // * state is the state after each action. // */ // public List<S> states() { // return Collections.unmodifiableList(states); // } // // /** // * Resets the middleware to only contain the current state and no actions. // */ // public void reset() { // states.subList(0, states.size() - 1).clear(); // actions.clear(); // } // }
import me.tatarka.redux.middleware.TestMiddleware; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals;
package me.tatarka.redux; @RunWith(JUnit4.class) public class ThunkDispatcherTest { @Test public void thunk_run_when_dispatched() { Thunk<String, String> thunk = new Thunk<String, String>() { @Override public void run(Dispatcher<String, String> dispatcher) { dispatcher.dispatch("action1"); dispatcher.dispatch("action2"); } }; SimpleStore<String> store = new SimpleStore<>("test1");
// Path: redux-core/src/main/java/me/tatarka/redux/middleware/TestMiddleware.java // public class TestMiddleware<S, A, R> implements Middleware<A, R> { // // private final Store<S> store; // private final List<A> actions = new ArrayList<>(); // private final List<S> states = new ArrayList<>(); // // public TestMiddleware(Store<S> store) { // this.store = store; // states.add(store.getState()); // } // // @Override // public R dispatch(Next<A, R> next, A action) { // actions.add(action); // R result = next.next(action); // states.add(store.getState()); // return result; // } // // /** // * Returns all actions that have been dispatched. // */ // public List<A> actions() { // return Collections.unmodifiableList(actions); // } // // /** // * Returns all states. The first state is before any action has been dispatched. Each // * subsequent // * state is the state after each action. // */ // public List<S> states() { // return Collections.unmodifiableList(states); // } // // /** // * Resets the middleware to only contain the current state and no actions. // */ // public void reset() { // states.subList(0, states.size() - 1).clear(); // actions.clear(); // } // } // Path: redux-thunk/src/test/java/me/tatarka/redux/ThunkDispatcherTest.java import me.tatarka.redux.middleware.TestMiddleware; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals; package me.tatarka.redux; @RunWith(JUnit4.class) public class ThunkDispatcherTest { @Test public void thunk_run_when_dispatched() { Thunk<String, String> thunk = new Thunk<String, String>() { @Override public void run(Dispatcher<String, String> dispatcher) { dispatcher.dispatch("action1"); dispatcher.dispatch("action2"); } }; SimpleStore<String> store = new SimpleStore<>("test1");
TestMiddleware<String, String, String> testMiddleware = new TestMiddleware<>(store);
evant/redux
redux-android-lifecycle/src/main/java/me/tatarka/redux/android/lifecycle/LiveDataAdapter.java
// Path: redux-core/src/main/java/me/tatarka/redux/SimpleStore.java // public class SimpleStore<S> implements Store<S> { // // private volatile S state; // private final CopyOnWriteArrayList<Listener<S>> listeners = new CopyOnWriteArrayList<>(); // // public SimpleStore(S initialState) { // setState(initialState); // } // // @Override // public S getState() { // return state; // } // // @Override // public void setState(S newState) { // if (!equals(state, newState)) { // state = newState; // for (Listener<S> listener : listeners) { // listener.onNewState(state); // } // } // } // // /** // * Registers as listener to receive state changes. The current state will be delivered // * immediately. // */ // public void addListener(Listener<S> listener) { // listeners.add(listener); // listener.onNewState(state); // } // // /** // * Removes the listener so it no longer receives state changes. // */ // public void removeListener(Listener<S> listener) { // listeners.remove(listener); // } // // public interface Listener<S> { // /** // * Called when a new state is set. This is called on the same thread as or {@link #setState(Object)}. // */ // void onNewState(S state); // } // // private static boolean equals(Object var0, Object var1) { // return var0 == var1 || var0 != null && var0.equals(var1); // } // }
import androidx.lifecycle.LiveData; import android.os.Looper; import androidx.annotation.Nullable; import me.tatarka.redux.SimpleStore;
package me.tatarka.redux.android.lifecycle; /** * Handles constructing a LiveData from a {@link me.tatarka.redux.SimpleStore} */ public class LiveDataAdapter { private static boolean debugAll = false; public static void setDebugAll(boolean value) { debugAll = value; }
// Path: redux-core/src/main/java/me/tatarka/redux/SimpleStore.java // public class SimpleStore<S> implements Store<S> { // // private volatile S state; // private final CopyOnWriteArrayList<Listener<S>> listeners = new CopyOnWriteArrayList<>(); // // public SimpleStore(S initialState) { // setState(initialState); // } // // @Override // public S getState() { // return state; // } // // @Override // public void setState(S newState) { // if (!equals(state, newState)) { // state = newState; // for (Listener<S> listener : listeners) { // listener.onNewState(state); // } // } // } // // /** // * Registers as listener to receive state changes. The current state will be delivered // * immediately. // */ // public void addListener(Listener<S> listener) { // listeners.add(listener); // listener.onNewState(state); // } // // /** // * Removes the listener so it no longer receives state changes. // */ // public void removeListener(Listener<S> listener) { // listeners.remove(listener); // } // // public interface Listener<S> { // /** // * Called when a new state is set. This is called on the same thread as or {@link #setState(Object)}. // */ // void onNewState(S state); // } // // private static boolean equals(Object var0, Object var1) { // return var0 == var1 || var0 != null && var0.equals(var1); // } // } // Path: redux-android-lifecycle/src/main/java/me/tatarka/redux/android/lifecycle/LiveDataAdapter.java import androidx.lifecycle.LiveData; import android.os.Looper; import androidx.annotation.Nullable; import me.tatarka.redux.SimpleStore; package me.tatarka.redux.android.lifecycle; /** * Handles constructing a LiveData from a {@link me.tatarka.redux.SimpleStore} */ public class LiveDataAdapter { private static boolean debugAll = false; public static void setDebugAll(boolean value) { debugAll = value; }
public static <S> LiveData<S> liveData(final SimpleStore<S> store) {