Exemplo n.º 1
0
  private void launch(String[] cmd) throws IOException {
    String[] params = Arrays.copyOf(cmd, cmd.length + 1);
    params[cmd.length] = tmpfile.toString();
    ProcessBuilder pb = new ProcessBuilder(params);
    pb = pb.inheritIO();

    try {
      input.suspend();
      Process process = pb.start();
      process.waitFor();
    } catch (IOException ex) {
      errorHandler.accept("process IO failure: " + ex.getMessage());
    } catch (InterruptedException ex) {
      errorHandler.accept("process interrupt: " + ex.getMessage());
    } finally {
      try {
        watcher.close();
        watchedThread.join(); // so that saveFile() is finished.
        saveFile();
      } catch (InterruptedException ex) {
        errorHandler.accept("process interrupt: " + ex.getMessage());
      } finally {
        input.resume();
      }
    }
  }
Exemplo n.º 2
0
 @Override
 public void paginateSQL(
     final StringBuilder query,
     final int firstRow,
     final int maxRows,
     final Consumer<StringBuilder> queryBuilder) {
   if ((firstRow >= 0) && (maxRows > 0)) {
     queryBuilder.accept(query);
     query.append(OFFSET);
     query.append(firstRow);
     query.append(ROWS_FETCH_FIRST);
     query.append(maxRows);
     query.append(ROWS_ONLY);
     return;
   }
   if (firstRow >= 0) {
     queryBuilder.accept(query);
     query.append(OFFSET);
     query.append(firstRow);
     query.append(ROWS);
     return;
   }
   if (maxRows > 0) {
     queryBuilder.accept(query);
     query.append(FETCH_FIRST);
     query.append(maxRows);
     query.append(ROWS_ONLY);
     return;
   }
   queryBuilder.accept(query);
 }
Exemplo n.º 3
0
 private void saveFile() {
   try {
     saveHandler.accept(Files.lines(tmpfile).collect(Collectors.joining("\n", "", "\n")));
   } catch (IOException ex) {
     errorHandler.accept("Failure in read edit file: " + ex.getMessage());
   }
 }
 @Override
 public void forEachRemaining(Consumer<? super R> action) {
   while (left != null) {
     accept(handleLeft(), action);
   }
   if (cur == none()) {
     if (!source.tryAdvance(this)) {
       accept(pushRight(none(), none()), action);
       return;
     }
   }
   acc = mapper.apply(cur);
   source.forEachRemaining(
       next -> {
         if (!this.mergeable.test(cur, next)) {
           action.accept(acc);
           acc = mapper.apply(next);
         } else {
           acc = accumulator.apply(acc, next);
         }
         cur = next;
       });
   if (accept(pushRight(acc, cur), action)) {
     if (right != null) {
       action.accept(right.acc);
       right = null;
     }
   }
 }
Exemplo n.º 5
0
 /** Process objects with specific tag. */
 public void byTag(
     String tagName, Predicate<IOsmObject> predicate, Consumer<IOsmObject> consumer) {
   short tagKey = tagsPack.getTagCode(tagName);
   for (int i = 0; i < nodes.size(); i++) {
     IOsmNode n = nodes.get(i);
     if (n.hasTag(tagKey)) {
       if (predicate.test(n)) {
         consumer.accept(n);
       }
     }
   }
   for (int i = 0; i < ways.size(); i++) {
     IOsmWay w = ways.get(i);
     if (w.hasTag(tagKey)) {
       if (predicate.test(w)) {
         consumer.accept(w);
       }
     }
   }
   for (int i = 0; i < relations.size(); i++) {
     IOsmRelation r = relations.get(i);
     if (r.hasTag(tagKey)) {
       if (predicate.test(r)) {
         consumer.accept(r);
       }
     }
   }
 }
Exemplo n.º 6
0
 default BiFunctor<T1, T2> bipeek(Consumer<? super T1> c1, Consumer<? super T2> c2) {
   return bimap(
       input -> {
         c1.accept(input);
         return input;
       },
       input -> {
         c2.accept(input);
         return input;
       });
 }
  public void addOr(T value, Consumer<T> ifFound) {
    Node<T> toInsert = new Node<>(value);

    // Assume we're inserting and making a comparison, fix later
    size++;
    comparisonCount++;

    int headComparison = head != null ? head.getValue().compareTo(value) : -1;

    if (head == null) {
      // There's nothing in the list
      comparisonCount--;
      head = tail = toInsert;
      referenceChangeCount += 2;
    } else if (headComparison == 0) {
      // The element we're interested in is the first thing in the list
      size--;
      if (ifFound != null) ifFound.accept(head.getValue());
    } else if (headComparison > 0) {
      // The element needs to become the first element in the sorted list
      toInsert.linkTo(head);
      head = toInsert;
      referenceChangeCount += 2;
    } else {
      // The element is not the first element, or doesn't belong at the very start of the list
      // Search for an element that matches the target, or insert it if we've passed where it
      // should "logically" be in terms of sorting order
      Node<T> ref = head;
      while (ref.next() != null) {
        comparisonCount++;
        int comparison = ref.next().getValue().compareTo(value);

        if (comparison > 0) {
          // The element cannot possibly come after this element. Insert before it
          toInsert.linkTo(ref.next());
          ref.linkTo(toInsert);
          referenceChangeCount += 2;
          return;
        } else if (comparison == 0) {
          // We found the element. Perform the specified action if one was provided
          size--;
          if (ifFound != null) ifFound.accept(ref.next().getValue());
          return;
        }

        ref = ref.next();
      }

      // The element hasn't been inserted yet, it belongs at the tail of the list
      tail.linkTo(toInsert);
      tail = toInsert;
      referenceChangeCount += 2;
    }
  }
  public static void runExample(
      String exampleDir,
      String verticleID,
      VertxOptions options,
      DeploymentOptions deploymentOptions) {
    if (options == null) {
      // Default parameter
      options = new VertxOptions();
    }
    // Smart cwd detection

    // Based on the current directory (.) and the desired directory (exampleDir), we try to compute
    // the vertx.cwd
    // directory:
    try {
      // We need to use the canonical file. Without the file name is .
      File current = new File(".").getCanonicalFile();
      if (exampleDir.startsWith(current.getName()) && !exampleDir.equals(current.getName())) {
        exampleDir = exampleDir.substring(current.getName().length() + 1);
      }
    } catch (IOException e) {
      // Ignore it.
    }

    System.setProperty("vertx.cwd", exampleDir);
    Consumer<Vertx> runner =
        vertx -> {
          try {
            if (deploymentOptions != null) {
              vertx.deployVerticle(verticleID, deploymentOptions);
            } else {
              vertx.deployVerticle(verticleID);
            }
          } catch (Throwable t) {
            t.printStackTrace();
          }
        };
    if (options.isClustered()) {
      Vertx.clusteredVertx(
          options,
          res -> {
            if (res.succeeded()) {
              Vertx vertx = res.result();
              runner.accept(vertx);
            } else {
              res.cause().printStackTrace();
            }
          });
    } else {
      Vertx vertx = Vertx.vertx(options);
      runner.accept(vertx);
    }
  }
Exemplo n.º 9
0
  public void transferMoneyBalanceCheck(
      AccountHolder fromData, AccountHolder toData, double amount, Consumer<Boolean> result) {
    new Thread(
            () -> {
              if (fromData.withdrawMoney(amount)) {
                toData.creditMoney(amount);

                if (result != null) result.accept(true);
              } else if (result != null) result.accept(false);
            })
        .start();
  }
Exemplo n.º 10
0
 @Override
 public void processRow(Row columns) {
   if (columns == null || columns.isEmpty()) {
     this.LOG.accept("Nothing to do -> empty entry list");
     return;
   }
   try {
     final String insertSQL = generateInsertStatement(columns);
     LOG.accept("#processRow(): " + insertSQL);
     this.statement.execute(insertSQL);
     LOG.accept("#processRow() executed!");
   } catch (SQLException ex) {
     throw new IllegalStateException("Cannot insert entry: " + ex.getMessage(), ex);
   }
 }
Exemplo n.º 11
0
 @Test
 public void runTestWithAsyncCompletion() throws Exception {
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   AtomicInteger count = new AtomicInteger();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 count.compareAndSet(0, 1);
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Async async = queue.poll(2, TimeUnit.SECONDS);
   assertEquals(1, count.get());
   assertFalse(reporter.completed());
   completeAsync.accept(async);
   reporter.await();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertTrue(result.succeeded());
   assertFalse(result.failed());
   assertNull(result.failure());
 }
Exemplo n.º 12
0
 /**
  * Takes action on the Unicode of each character in this {@code CharSeq}.
  *
  * <p>Similar to {@link #eachCodePoint()}, but instead of returning the Unicode collection, it
  * iterates the collection and takes action.
  *
  * @param consumer the action to be taken on the Unicode of each character
  * @throws NullPointerException if consumer is null
  */
 public void forEachCodePoint(Consumer<Integer> consumer) {
   Objects.requireNonNull(consumer);
   char[] chars = str.toCharArray();
   for (int i = 0; i < chars.length; i++) {
     consumer.accept((int) chars[i]);
   }
 }
 private static void execute(
     Settings settings,
     BiFunction<Runnable, TimeValue, ScheduledFuture<?>> scheduler,
     Consumer<Throwable> consumer,
     boolean constructionShouldFail,
     Runnable asserts)
     throws InterruptedException {
   assert constructionShouldFail == (consumer != null);
   assert constructionShouldFail == (asserts == null);
   ThreadPool threadPool = null;
   try {
     threadPool =
         new ThreadPool(JvmGcMonitorServiceSettingsTests.class.getCanonicalName()) {
           @Override
           public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval) {
             return scheduler.apply(command, interval);
           }
         };
     try {
       JvmGcMonitorService service = new JvmGcMonitorService(settings, threadPool);
       if (constructionShouldFail) {
         fail("construction of jvm gc service should have failed");
       }
       service.doStart();
       asserts.run();
       service.doStop();
     } catch (Throwable t) {
       consumer.accept(t);
     }
   } finally {
     ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
   }
 }
Exemplo n.º 14
0
 private void dragConsume(DragEvent e, Consumer<DragEvent> c) {
   List<File> files = e.getDragboard().getFiles();
   if (files != null && !files.isEmpty()) {
     c.accept(e);
   }
   e.consume();
 }
Exemplo n.º 15
0
 @Override
 public void visit(Consumer<? super Renderer> consumer) {
   consumer.accept(this);
   for (Renderer c : content) {
     c.visit(consumer);
   }
 }
Exemplo n.º 16
0
 @Override
 public Set<Integer> onIntermediateResult(
     Address address, Collection<CacheEntry<K, Object>> results) {
   if (results != null) {
     log.tracef("Response from %s with results %s", address, results.size());
     Set<Integer> segmentsCompleted;
     CacheEntry<K, Object>[] lastCompleted = new CacheEntry[1];
     if (listenerNotifier != null) {
       segmentsCompleted = new HashSet<>();
     } else {
       segmentsCompleted = null;
     }
     results.forEach(
         e -> {
           K key = e.getKey();
           int segment = ch.getSegment(key);
           Set<K> keys = referenceArray.get(segment);
           // On completion we null this out first - thus we don't need to add
           if (keys != null) {
             keys.add(key);
           } else if (segmentsCompleted != null) {
             segmentsCompleted.add(segment);
             lastCompleted[0] = e;
           }
           consumer.accept(valueFunction.apply(e));
         });
     if (lastCompleted[0] != null) {
       listenerNotifier.addSegmentsForObject(lastCompleted[0], segmentsCompleted);
     }
     return segmentsCompleted;
   }
   return null;
 }
Exemplo n.º 17
0
  /**
   * Listen to a message from JMS from a given destination by name.
   *
   * @param destinationName destinationName
   * @param messageListener messageListener
   */
  public void listenTextMessagesWithDestination(
      final String destinationName, final Consumer<String> messageListener) {
    final MessageConsumer consumer = getConsumer(destinationName);
    try {
      consumer.setMessageListener(
          message -> {
            try {
              messageListener.accept(((TextMessage) message).getText());

              if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
                message.acknowledge();
              }

            } catch (JMSException e) {

              throw new IllegalStateException(
                  "Unable to register get text from message in listener " + destinationName, e);
            } catch (Exception ex) {

              throw new IllegalStateException("Unable handle JMS Consumer  " + destinationName, ex);
            }
          });
    } catch (JMSException e) {

      throw new IllegalStateException("Unable to register message listener " + destinationName, e);
    }
  }
Exemplo n.º 18
0
 protected void withRedisTransaction(Consumer<Transaction> r, Consumer<Jedis> onOk) {
   Jedis redis = getRedis();
   Transaction transaction = null;
   try {
     transaction = redis.multi();
     r.accept(transaction);
     transaction.exec();
     transaction = null;
     if (onOk != null) {
       onOk.accept(redis);
     }
   } finally {
     rollback(transaction);
     redis.close();
   }
 }
 @Override
 public boolean tryAdvance(Consumer<? super R> action) {
   if (left != null) {
     if (accept(handleLeft(), action)) {
       return true;
     }
   }
   if (cur == none()) { // start
     if (!source.tryAdvance(this)) {
       return accept(pushRight(none(), none()), action);
     }
   }
   T first = cur;
   R acc = mapper.apply(cur);
   T last = first;
   while (source.tryAdvance(this)) {
     if (!this.mergeable.test(last, cur)) {
       action.accept(acc);
       return true;
     }
     last = cur;
     acc = this.accumulator.apply(acc, last);
   }
   return accept(pushRight(acc, last), action);
 }
 @Override
 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
   if (shouldVisit(file, attrs)) {
     consumer.accept(file);
   }
   return FileVisitResult.CONTINUE;
 }
Exemplo n.º 21
0
  private void parseAndConsumeBufferContent(
      CriteriaSet criteriaSet, Consumer<Message> consumer, List<String> buffer) {
    Message msg = parseOneMessage(buffer);
    if (msg != null && criteriaSet.IsSatisfiedBy(msg)) consumer.accept(msg);

    buffer.clear();
  }
Exemplo n.º 22
0
  /**
   * Find the path from start to goal using breadth first search
   *
   * @param start The starting location
   * @param goal The goal location
   * @param nodeSearched A hook for visualization. See assignment instructions for how to use it.
   * @return The list of intersections that form the shortest (unweighted) path from start to goal
   *     (including both start and goal).
   */
  public List<GeographicPoint> bfs(
      GeographicPoint start, GeographicPoint goal, Consumer<GeographicPoint> nodeSearched) {
    // TODO: Implement this method in WEEK 2

    // Hook for visualization.  See writeup.
    // nodeSearched.accept(next.getLocation());

    Queue<GeographicPoint> queue = new LinkedList<GeographicPoint>();
    Set<GeographicPoint> visited = new HashSet<GeographicPoint>();
    Map<GeographicPoint, GeographicPoint> parentMap =
        new HashMap<GeographicPoint, GeographicPoint>();
    queue.add(start);
    visited.add(start);
    while (!queue.isEmpty()) {
      GeographicPoint curr = queue.poll();
      nodeSearched.accept(curr);
      if (curr.equals(goal)) { // reaches the goal
        return RetrievePath(parentMap, start, goal); // retrieve the path
      }
      MapVertex node = Vertices.get(curr); // the MapVertex associated with the location curr
      Set<MapEdge> edges = node.getEdges(); // the edges connected to the node
      for (MapEdge edge : edges) {
        MapVertex next = edge.getEnd(); // neighbor of the location curr
        GeographicPoint nextLoc = next.getLocation();
        if (!visited.contains(nextLoc)) {
          visited.add(nextLoc);
          parentMap.put(nextLoc, curr); // set curr as the parent of next in tha path map
          queue.add(nextLoc);
        }
      }
    }
    /////// if the goal is not achievable
    return null;
  }
Exemplo n.º 23
0
 private void map(final Consumer<MapCell> mapping, final MapCell[][] map) {
   for (int i = 0; i < map.length; i++) {
     for (int j = 0; j < map[0].length; j++) {
       mapping.accept(map[i][j]);
     }
   }
 }
 /** TODO: Documentation */
 default boolean ifPresent(final Consumer<T> consumer) {
   if (this.isPresent()) {
     consumer.accept(this.get());
     return true;
   }
   return false;
 }
 private boolean accept(R acc, Consumer<? super R> action) {
   if (acc != NONE) {
     action.accept(acc);
     return true;
   }
   return false;
 }
  @Override
  public boolean tryAdvance(Consumer<? super ByteBuffer> action) {
    Objects.requireNonNull(action);
    int messageOffset = offset + MessageLengthFrameDecoder.HEADER_LENGTH;
    if (messageOffset > buffer.limit()) {
      return false;
    }
    frameDecoder.wrap(buffer);
    frameDecoder.decodeFrameHeader();
    final int messageLength = frameDecoder.getMessageLength();
    int messageLimit = offset + MessageLengthFrameDecoder.HEADER_LENGTH + messageLength;

    if (messageLength <= 0 || (messageLimit > buffer.limit())) {
      return false;
    }

    ByteBuffer message = buffer.duplicate();
    message.order(originalByteOrder);
    message.limit(messageLimit);

    action.accept(message);
    offset = messageLimit;
    buffer.position(messageLimit);
    return true;
  }
Exemplo n.º 27
0
  public final ServerStarter start(Stage stage, Consumer<ServerBuilder> consumer) {
    notNull(consumer, "Null ServerBuilder consumer");

    /* Create a new injector and set up the module */
    final Injector injector =
        Guice.createInjector(stage, (binder) -> consumer.accept(new ServerBuilder(binder)));

    /* Get a hold on our HttpServer instance */
    final HttpServer server = injector.getInstance(HttpServer.class);
    final String serverName = server.getServerConfiguration().getName();

    /* Attempt to start our server */
    try {
      log.info("Starting server %s", serverName);
      server.start();
    } catch (IOException exception) {
      log.error(exception, "Exception starting server %s", serverName);
      System.exit(1);
    }

    /* Add a shutdown hook terminating the server on exit */
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                log.info("Shutting down server %s", serverName);
                server.shutdown();
              }
            });

    /* Return self for chaining */
    this.server = server;
    return this;
  }
Exemplo n.º 28
0
 /**
  * Performs the given action for each element contained within this {@code LinkedList} in
  * <em>forward</em> order. The behavior of this method is undefined if this list is modified
  * during the iteration process.
  *
  * @param action The action to apply to each element in this list.
  * @throws NullPointerException if the specified argument {@code action} is {@code null}.
  */
 @Override
 public void forEach(Consumer<? super E> action) {
   Objects.requireNonNull(action);
   for (Node<E> n = first; n != null; n = n.nextLink) {
     action.accept(n.item);
   }
 }
Exemplo n.º 29
0
  public JsPromise then(Consumer onSuccessCallBack) {
    // future.thenAccept(onSuccessCallBack);
    onSuccess = onSuccessCallBack;
    executor.submit(
        () -> {
          try {
            onSuccessCallBack.accept(future.get());
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          } catch (ExecutionException e) {
            onError.accept(e);
          }
        });

    return this;
  }
Exemplo n.º 30
0
 @Override
 public void onError(WebContext ctx, HandledException error) {
   if (error != null) {
     UserContext.message(Message.error(error.getMessage()));
   }
   defaultRoute.accept(ctx);
 }