Example #1
0
  @Test
  public void testMoreFunctions() {
    // Up first... Choice
    Function<String, Integer> choice =
        MoreFunctions.<String, Integer>choice()
            .of(Comparisons.equalsIgnoreCase().predicateFor("A"), 1)
            .of(Comparisons.equalsIgnoreCase().predicateFor("B"), 2)
            .otherwise(3)
            .get();
    assertEquals(Integer.valueOf(1), choice.apply("a"));
    assertEquals(Integer.valueOf(2), choice.apply("b"));
    assertEquals(Integer.valueOf(3), choice.apply("c"));

    // Test createInstance
    Foo foo = MoreFunctions.createInstance(Foo.class).apply(null);
    assertNotNull(foo);

    foo = MoreFunctions.createInstance(Foo.class, String.class).apply(MoreFunctions.array("A"));
    assertNotNull(foo);
    assertEquals("A", foo.a());

    // Test each
    String[] array = MoreFunctions.array("a", "b", "c", "d");
    array =
        MoreFunctions.eachArray(
                new Function<String, String>() {
                  public String apply(String input) {
                    return input.toUpperCase();
                  }
                },
                String.class)
            .apply(array);
    assertEquals("A", array[0]);
    assertEquals("B", array[1]);
    assertEquals("C", array[2]);
    assertEquals("D", array[3]);

    // Test firstNonNull...
    assertEquals("A", MoreFunctions.firstNonNull(null, null, null, "A"));

    // Test futureFunction... executes the function in a separate
    // thread using the passed in ExecutorService
    Future<String> future =
        MoreFunctions.<String, String>futureFunction(
                new Function<String, String>() {
                  public String apply(String input) {
                    System.out.println("Thread sleeping....");
                    try {
                      Thread.sleep(10 * 1000);
                    } catch (Throwable t) {
                    }
                    return input;
                  }
                },
                MoreExecutors2.getExitingExecutor())
            .apply("A");
    try {
      System.out.println("Waiting for return...");
      assertEquals("A", future.get());
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }