Exemplo n.º 1
0
 @Test
 public void canAdaptConsumer() {
   final Box<Pair<O, O>> box = Box.empty();
   final Consumer<Pair<O, O>> consumer = Spies.spy(new Noop<Pair<O, O>>(), box);
   final BiConsumer<O, O> adapted = Tuples.Pairs.untupled(consumer);
   adapted.accept(O.ONE, O.ANOTHER);
   Assert.assertEquals(Pair.of(O.ONE, O.ANOTHER), box.getContent());
 }
Exemplo n.º 2
0
  public static void main(String[] args) {

    // (Employee e) -> e.getName();
    System.out.println("// (Employee e) -> e.getName()");
    Employee employee = new Employee("Employee Name", 8000);
    System.out.println(getName1.apply(employee));
    System.out.println(getName2.apply(employee));

    // (Employee emp,String s) -> emp.setName(s)
    System.out.println("// (Employee emp,String s) -> emp.setName(s)");
    setName1.accept(employee, "New Name 1");
    setName2.accept(employee, "New Name 2");

    // (Employee e) -> e.getName();
    System.out.println("// (Employee e) -> e.getName()");
    System.out.println(getName1.apply(employee));
    System.out.println(getName2.apply(employee));

    // (String s1, String s2) -> s1.compareTo(s2)
    System.out.println("// (String s1, String s2) -> s1.compareTo(s2)");
    System.out.println(compare1.compare("Employee", "Employee"));
    System.out.println(compare1.compare("Employee", "Employee2"));

    System.out.println(compare2.compare("Employee", "Employee"));
    System.out.println(compare2.compare("Employee", "Employee2"));

    // (Integer x, Integer y) -> Math.pow(x, y)
    System.out.println("// (Integer x, Integer y) -> Math.pow(x, y)");
    System.out.println(power1.apply(3, 4));
    System.out.println(power2.apply(5, 3));

    // (Apple a) -> a.getWeight()
    System.out.println("// (Apple a) -> a.getWeight()");
    Apple apple = new Apple(30);
    System.out.println(getWeight1.apply(apple));
    System.out.println(getWeight2.apply(apple));

    // (String x) -> Integer.parseInt(x)
    int int1 = parseInt1.apply("33");
    int int2 = parseInt1.apply("333");

    // (Employee e1, Employee e2) -> comp.compare(e1, e2)
    System.out.println("// (Employee e1, Employee e2) -> comp.compare(e1, e2)");
    Employee emp1 = new Employee("employee", 6000);
    Employee emp2 = new Employee("employee", 6000);
    System.out.println(comparator1.compare(emp1, emp2));
    System.out.println(comparator2.compare(emp1, emp2));

    setName1.accept(emp1, "new Employee");

    System.out.println(comparator1.compare(emp1, emp2));
    System.out.println(comparator2.compare(emp1, emp2));
  }
Exemplo n.º 3
0
 public static void forEachRowColumn(BiConsumer<Integer, Integer> consumer) {
   for (int row = 0; row < 9; row++) {
     for (int column = 0; column < 9; column++) {
       consumer.accept(row, column);
     }
   }
 }
Exemplo n.º 4
0
 public void foreach(BiConsumer<K, V> action) {
   try {
     for (Pair<K, V> pair : pairs) action.accept(pair.key, pair.value);
   } catch (Exception ignore) {
     throwRuntimeException(ignore);
   }
 }
Exemplo n.º 5
0
 @Override
 public void forEach(BiConsumer<Integer, ? super Boolean> action) {
   int size = bits.size();
   for (int i = 0; i < size; i++) {
     action.accept(i, get(size));
   }
 }
Exemplo n.º 6
0
    @SuppressWarnings("unchecked")
    private ModuleConstructor(
        List<Consumer<NTree<Class<?>>>> verification,
        BiConsumer<S, S> addMethod,
        Class<S> moduleClass) {
      this.verification = new ArrayList<>(verification);
      moduleGeneration =
          NTree.traverseUp(
              (L, l) -> {
                // parent object -- instance of multi module.
                S multiModule = l;

                // children instance of S, child module.
                Iterator<S> it = L.iterator();

                while (it.hasNext()) {
                  S m = it.next();
                  addMethod.accept(multiModule, m);
                }

                return multiModule;
              },
              (Class<?> l) -> {
                S re = null;
                try {
                  re = (S) l.newInstance();
                } catch (IllegalAccessException | InstantiationException e) {
                  reflectError("Exception in creating class " + l, e);
                } catch (ClassCastException v) {
                  reflectError(
                      "Class " + l + " is not an instance of the module class " + moduleClass);
                }
                return re;
              });
    }
 @Override
 protected void forEach(JsonObject object, BiConsumer<String, Object> objectConsumer) {
   object.forEach(
       entry -> {
         objectConsumer.accept(entry.getKey(), entry.getValue());
       });
 }
 private void verifyCommands(
     Point topLeft, Point bottomRight, BiConsumer<Integer, Integer> verifier) {
   for (int x = topLeft.x; x <= bottomRight.x; ++x) {
     for (int y = topLeft.y; y <= bottomRight.y; ++y) {
       verifier.accept(x, y);
     }
   }
 }
Exemplo n.º 9
0
 @Override
 public void forEach(BiConsumer<? super K, ? super V> action) {
   bulk(
       e -> {
         action.accept(e.key, e.value);
         return true;
       });
 }
Exemplo n.º 10
0
 @Override
 public void forEach(BiConsumer<? super K, ? super V> action) {
   checkNotNull(action);
   ImmutableList<K> keyList = keySet.asList();
   for (int i = 0; i < size(); i++) {
     action.accept(keyList.get(i), valueList.get(i));
   }
 }
Exemplo n.º 11
0
 /**
  * Tie this camera to a canvas object, as that object moves then so will the camera
  *
  * @param tiedTo Canvas Object the camera is tied to
  * @param tiedObjectLocator Anonymous function defining the camera's position in relation to the
  *     tied object
  */
 public void setTiedTo(CanvasObject tiedTo, BiConsumer<CanvasObject, Camera> tiedObjectLocator) {
   this.tiedTo = tiedTo;
   this.tiedObjectLocator = tiedObjectLocator;
   tiedObjectLocator.accept(tiedTo, this);
   OrientableCanvasObject<?> o = tiedTo.getObjectAs(OrientableCanvasObject.class);
   tiedTo.addObserver(this);
   if (o != null) {
     o.setOrientation(orientation);
   }
 }
Exemplo n.º 12
0
 @Override
 public final <R> R collect(
     Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) {
   BinaryOperator<R> operator =
       (left, right) -> {
         combiner.accept(left, right);
         return left;
       };
   return evaluate(ReduceOps.makeInt(supplier, accumulator, operator));
 }
Exemplo n.º 13
0
  @Test
  public void ensureCorrectEventSubject() {

    DateMidnight today = DateMidnight.now();
    Period period = new Period(today, today, DayLength.FULL);

    BiConsumer<EventType, String> assertCorrectEventSubject =
        (type, subject) -> {
          Absence absence = new Absence(person, period, type, timeConfiguration);

          assertThat(absence.getEventType(), is(type));
          assertThat(absence.getEventSubject(), is(subject));
        };

    assertCorrectEventSubject.accept(
        EventType.WAITING_APPLICATION, "Antrag auf Urlaub Marlene Muster");
    assertCorrectEventSubject.accept(EventType.ALLOWED_APPLICATION, "Urlaub Marlene Muster");
    assertCorrectEventSubject.accept(EventType.SICKNOTE, "Marlene Muster krank");
  }
Exemplo n.º 14
0
 public void visitHalfPlanes(BiConsumer<Segment, Integer> visitor, KDNode node, int depth) {
   if (node.isLeaf()) { // || depth > 8) {
     return;
   } else {
     if (node.splittingPlane.dimension == Dimension.X) {
       Point2D start = new Point2D(node.splittingPlane.splitValue, node.bounds.min.getY());
       Point2D end = new Point2D(node.splittingPlane.splitValue, node.bounds.max.getY());
       visitor.accept(new Segment(start, end), depth);
       visitHalfPlanes(visitor, node.left, depth + 1);
       // visitHalfPlanes(visitor, node.right, depth+1);
     } else {
       Point2D start = new Point2D(node.bounds.min.getX(), node.splittingPlane.splitValue);
       Point2D end = new Point2D(node.bounds.max.getX(), node.splittingPlane.splitValue);
       visitor.accept(new Segment(start, end), depth);
       visitHalfPlanes(visitor, node.left, depth + 1);
       // visitHalfPlanes(visitor, node.right, depth+1);
     }
   }
 }
  private static void testCorruptRecord(
      BiConsumer<LogTransaction, SSTableReader> modifier, boolean isRecoverable)
      throws IOException {
    ColumnFamilyStore cfs = MockSchema.newCFS(KEYSPACE);
    File dataFolder = new Directories(cfs.metadata).getDirectoryForNewSSTables();
    SSTableReader sstableOld = sstable(dataFolder, cfs, 0, 128);
    SSTableReader sstableNew = sstable(dataFolder, cfs, 1, 128);

    // simulate tracking sstables with a committed transaction except the checksum will be wrong
    LogTransaction log = new LogTransaction(OperationType.COMPACTION);
    assertNotNull(log);

    log.trackNew(sstableNew);
    log.obsoleted(sstableOld);

    // Modify the transaction log or disk state for sstableOld
    modifier.accept(log, sstableOld);

    assertNull(log.complete(null));

    sstableOld.selfRef().release();
    sstableNew.selfRef().release();

    // The files on disk, for old files make sure to exclude the files that were deleted by the
    // modifier
    Set<String> newFiles = sstableNew.getAllFilePaths().stream().collect(Collectors.toSet());
    Set<String> oldFiles =
        sstableOld
            .getAllFilePaths()
            .stream()
            .filter(p -> new File(p).exists())
            .collect(Collectors.toSet());

    // This should filter as in progress since the last record is corrupt
    assertFiles(newFiles, getTemporaryFiles(dataFolder));
    assertFiles(oldFiles, getFinalFiles(dataFolder));

    if (isRecoverable) { // the corruption is recoverable but the commit record is unreadable so the
      // transaction is still in progress

      // This should remove new files
      LogTransaction.removeUnfinishedLeftovers(cfs.metadata);

      // make sure to exclude the old files that were deleted by the modifier
      assertFiles(dataFolder.getPath(), oldFiles);
    } else { // if an intermediate line was also modified, it should ignore the tx log file

      // This should not remove any files
      LogTransaction.removeUnfinishedLeftovers(cfs.metadata);

      assertFiles(
          dataFolder.getPath(),
          Sets.newHashSet(Iterables.concat(newFiles, oldFiles, log.logFilePaths())));
    }
  }
Exemplo n.º 16
0
 @Override
 public final <R> R collect(
     Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) {
   Objects.requireNonNull(combiner);
   BinaryOperator<R> operator =
       (left, right) -> {
         combiner.accept(left, right);
         return left;
       };
   return evaluate(ReduceOps.makeLong(supplier, accumulator, operator));
 }
Exemplo n.º 17
0
 /**
  * Executes the given consumer for each tracked object in parallel.
  *
  * @param consumer the consumer
  */
 public void forEachTrackedObject(BiConsumer<Client, Position> consumer) {
   requireNonNull(consumer, "consumer is null");
   trackedObjects.forEach(
       PositionTracker.THRESHOLD,
       (t, pt) -> {
         // pt.time is from the first time we encountered the position.
         // We might have gotten messages with the position but different timestamps
         // To avoid confusion we do not export the timestamp out
         consumer.accept(t, Position.create(pt.getLatitude(), pt.getLongitude()));
       });
 }
Exemplo n.º 18
0
 final void forEach(BiConsumer<? super K, ? super V> action) {
   for (long a,
           tail,
           allocations = (a = ~bitSet) << (tail = Long.numberOfLeadingZeros(a)),
           allocIndex = 64 - tail;
       allocations != 0;
       allocations <<= 1, allocIndex--) {
     if (allocations < 0)
       action.accept(this.<K>readKey(allocIndex), this.<V>readValue(allocIndex));
   }
 }
 @Override
 public <R> R collect(
     Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) {
   return performOperation(
       TerminalFunctions.collectFunction(supplier, accumulator, combiner),
       true,
       (e1, e2) -> {
         combiner.accept(e1, e2);
         return e1;
       },
       null);
 }
Exemplo n.º 20
0
 default <R> R collect(
     Supplier<R> supplier, BiConsumer<R, ? super U> accumulator, BiConsumer<R, R> combiner) {
   return (R)
       this.run(
           (Collector)
               Collector.of(
                   supplier,
                   accumulator,
                   (a, b) -> {
                     combiner.accept(a, b);
                     return a;
                   }));
 }
 private <T> void dispatchMsg(ActorContext context, T localMsg, BiConsumer<String, T> biConsumer) {
   for (EndpointClusterAddress address : routes.getLocalRoutes()) {
     LOG.info("Forwarding {} to local endpoint actor {}", localMsg, address);
     ThriftEndpointActorMsg<T> msg =
         new ThriftEndpointActorMsg<>(
             address.toEndpointAddress(), ActorClassifier.LOCAL, localMsg);
     context.parent().tell(msg, context.self());
   }
   for (EndpointClusterAddress address : routes.getRemoteRoutes()) {
     LOG.info("Forwarding {} to remote endpoint actor {}", localMsg, address);
     biConsumer.accept(address.getNodeId(), localMsg);
   }
 }
Exemplo n.º 22
0
 public <V> Builder write(
     Key<? extends V> key, String fieldName, BiConsumer<JsonGenerator, ? super V> serialiser) {
   BiConsumer<JsonGenerator, ? extends V> keyValueWriter =
       (JsonGenerator generator, V value) -> {
         try {
           generator.writeFieldName(fieldName);
           serialiser.accept(generator, value);
         } catch (IOException e) {
           throw new SerialisationException(e);
         }
       };
   serialiserMap.put(key, keyValueWriter);
   return this;
 }
Exemplo n.º 23
0
  /**
   * Asserts that arguments can be resolved from lambda expressions for simple functional interfaces
   * that contain multiple type parameters.
   */
  public void shouldResolveMultiArguments() {
    BiFunction<String, Long, Integer> biFn = (str1, str2) -> Integer.valueOf(str1 + str2);
    BiConsumer<String, String> consumer1 = (s1, s2) -> {};
    BiConsumer<String, Long> consumer2 = (s1, s2) -> {};
    Foo<String, Long, Integer, Double> foo = (a, b, c) -> 2.0;
    Bar<String, Long, Integer, Double> bar = (a, b, c) -> {};

    assertEquals(
        TypeResolver.resolveRawArguments(BiFunction.class, biFn.getClass()),
        new Class<?>[] {String.class, Long.class, Integer.class});
    assertEquals(
        TypeResolver.resolveRawArguments(BiConsumer.class, consumer1.getClass()),
        new Class<?>[] {String.class, String.class});
    assertEquals(
        TypeResolver.resolveRawArguments(BiConsumer.class, consumer2.getClass()),
        new Class<?>[] {String.class, Long.class});
    assertEquals(
        TypeResolver.resolveRawArguments(Foo.class, foo.getClass()),
        new Class<?>[] {String.class, Long.class, Integer.class, Double.class});
    assertEquals(
        TypeResolver.resolveRawArguments(Bar.class, bar.getClass()),
        new Class<?>[] {String.class, Long.class, Integer.class, Unknown.class});
  }
Exemplo n.º 24
0
  @Override
  public void visitLambda(JCLambda node) {
    builder
        .build(node)
        .ifPresent(
            expr -> {
              JCExpression ne = parseExpression(expr);
              fixPos(ne, node.pos);

              changeNode.accept(node, ne);
            });

    super.visitLambda(node);
  }
Exemplo n.º 25
0
 /**
  * Wraps a BiConsumer in such a way the it will push the current execution context before any code
  * gets executed and pop it afterwards
  *
  * @param w the functional interface to be wrapped
  * @return wrapped object if there is a current execution context, or the same object if not.
  */
 public static <T, U> BiConsumer<T, U> wrap(BiConsumer<T, U> w) {
   TaskContext c = current();
   if (c != null) {
     return (t, u) -> {
       c.push();
       try {
         w.accept(t, u);
       } finally {
         c.pop();
       }
     };
   }
   return w;
 }
Exemplo n.º 26
0
  /** Apply transformations to this camera */
  public synchronized void doTransforms() {
    if (this.tiedObjectUpdated) {
      tiedObjectLocator.accept(tiedTo, this);
      this.tiedObjectUpdated = false;
    } else if (transforms.size() == 0) return;

    for (CameraTransform t : this.transforms.values()) {
      t.doTransform(this);
    }

    ot.saveCurrentTransforms(orientation);

    this.setChanged();
    this.notifyObservers(CAMERA_MOVED);
  }
Exemplo n.º 27
0
 /**
  * {@inheritDoc}
  *
  * @implSpec The default implementation is equivalent to, for this {@code map}:
  *     <pre>{@code
  * for ((Map.Entry<K, V> entry : map.entrySet())
  *     action.accept(entry.getKey(), entry.getValue());
  * }</pre>
  *
  * @implNote The default implementation assumes that {@code IllegalStateException} thrown by
  *     {@code getKey()} or {@code getValue()} indicates that the entry has been removed and cannot
  *     be processed. Operation continues for subsequent entries.
  * @throws NullPointerException {@inheritDoc}
  * @since 1.8
  */
 @Override
 default void forEach(BiConsumer<? super K, ? super V> action) {
   Objects.requireNonNull(action);
   for (Map.Entry<K, V> entry : entrySet()) {
     K k;
     V v;
     try {
       k = entry.getKey();
       v = entry.getValue();
     } catch (IllegalStateException ise) {
       // this usually means the entry is no longer in the map.
       continue;
     }
     action.accept(k, v);
   }
 }
  @SuppressWarnings("unchecked")
  @Override
  public synchronized void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action); // explicit check required in case
    // table is empty.
    final int expectedModCount = modCount;

    Entry<?, ?>[] tab = table;
    for (Entry<?, ?> entry : tab) {
      while (entry != null) {
        action.accept((K) entry.key, (V) entry.value);
        entry = entry.next;

        if (expectedModCount != modCount) {
          throw new ConcurrentModificationException();
        }
      }
    }
  }
Exemplo n.º 29
0
 @Override
 protected void describeMismatchSafely(T item, Description description) {
   descibeMismatchSafely.accept(item, description);
 }
Exemplo n.º 30
0
 private void createTermBuffer(
     final BiConsumer<RetransmitHandlerTest, Integer> creator, final int num) {
   IntStream.range(0, num).forEach((i) -> creator.accept(this, i));
 }