コード例 #1
0
  /** Uso da interface funcional java.util.function.Supplier<T> Método principal: T get(); */
  public static void exampleOfSupplier() {

    // sintaxe simplificada chamando um método que executa uma operação e
    // retorna um objeto T
    Supplier<Integer> supplier = LambdaAPI::sum;
    Integer result = supplier.get();
    print(result.toString());

    // sintaxe com código que executa uma operação em uma linha que retorna
    // ou resulta em um objeto T
    supplier = () -> 1;
    result += supplier.get();
    print(result.toString());

    // outra sintaxe para a mesma operação, agora com bloco de código
    // e instrução de retorno
    supplier =
        () -> {
          int x = 1;
          return x;
        };

    result += supplier.get();
    print(result.toString());

    // Observe que o método T get() não recebe parâmetros, sendo assim, se utilizar
    // um método com parâmetros ou informar algum parâmetro, o código não compila
    // supplier = LambdaAPI::print;
    // supplier = (Integer param) -> 10 + 5;

    // se o retorno da operação get() na expressão lambda não for igual o retorno
    // esperado, o código não compila
    // supplier = () -> "" + 1;
  }
コード例 #2
0
ファイル: LogLambda.java プロジェクト: eugenyk/hpcourse
  public void debug(String msg, Supplier<Object> arg1, Supplier<Object> arg2) {
    if (!isDebugEnabled()) {
      return;
    }

    log.debug(msg, arg1.get(), arg2.get());
  }
コード例 #3
0
ファイル: WeakCache.java プロジェクト: susotajuraj/jdk8u-jdk
  /**
   * Look-up the value through the cache. This always evaluates the {@code subKeyFactory} function
   * and optionally evaluates {@code valueFactory} function if there is no entry in the cache for
   * given pair of (key, subKey) or the entry has already been cleared.
   *
   * @param key possibly null key
   * @param parameter parameter used together with key to create sub-key and value (should not be
   *     null)
   * @return the cached value (never null)
   * @throws NullPointerException if {@code parameter} passed in or {@code sub-key} calculated by
   *     {@code subKeyFactory} or {@code value} calculated by {@code valueFactory} is null.
   */
  public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);

    expungeStaleEntries();

    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // lazily install the 2nd level valuesMap for the particular cacheKey
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
    if (valuesMap == null) {
      ConcurrentMap<Object, Supplier<V>> oldValuesMap =
          map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>());
      if (oldValuesMap != null) {
        valuesMap = oldValuesMap;
      }
    }

    // create subKey and retrieve the possible Supplier<V> stored by that
    // subKey from valuesMap
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) {
      if (supplier != null) {
        // supplier might be a Factory or a CacheValue<V> instance
        V value = supplier.get();
        if (value != null) {
          return value;
        }
      }
      // else no supplier in cache
      // or a supplier that returned null (could be a cleared CacheValue
      // or a Factory that wasn't successful in installing the CacheValue)

      // lazily construct a Factory
      if (factory == null) {
        factory = new Factory(key, parameter, subKey, valuesMap);
      }

      if (supplier == null) {
        supplier = valuesMap.putIfAbsent(subKey, factory);
        if (supplier == null) {
          // successfully installed Factory
          supplier = factory;
        }
        // else retry with winning supplier
      } else {
        if (valuesMap.replace(subKey, supplier, factory)) {
          // successfully replaced
          // cleared CacheEntry / unsuccessful Factory
          // with our Factory
          supplier = factory;
        } else {
          // retry with current supplier
          supplier = valuesMap.get(subKey);
        }
      }
    }
  }
コード例 #4
0
  public static SearchSortValues createTestItem() {
    List<Supplier<Object>> valueSuppliers = new ArrayList<>();
    // this should reflect all values that are allowed to go through the transport layer
    valueSuppliers.add(() -> null);
    valueSuppliers.add(() -> randomInt());
    valueSuppliers.add(() -> randomLong());
    valueSuppliers.add(() -> randomDouble());
    valueSuppliers.add(() -> randomFloat());
    valueSuppliers.add(() -> randomByte());
    valueSuppliers.add(() -> randomShort());
    valueSuppliers.add(() -> randomBoolean());
    valueSuppliers.add(
        () ->
            frequently()
                ? randomAsciiOfLengthBetween(1, 30)
                : randomRealisticUnicodeOfCodepointLength(30));

    int size = randomInt(20);
    Object[] values = new Object[size];
    for (int i = 0; i < size; i++) {
      Supplier<Object> supplier = randomFrom(valueSuppliers);
      values[i] = supplier.get();
    }
    return new SearchSortValues(values);
  }
コード例 #5
0
 /** Calls the given {@link Supplier} while flagged as replicating remote events. */
 public static <T> T asReplicating(final Supplier<T> supplier) {
   if (isReplicating()) {
     return supplier.get();
   } else {
     isReplicating.set(TRUE);
     try {
       return supplier.get();
     } finally {
       isReplicating.remove();
     }
   }
 }
コード例 #6
0
  @Test
  public void shouldReturnSuccess() {
    // Given
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
    assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);

    // When
    Supplier<String> checkedSupplier =
        CircuitBreaker.decorateSupplier(() -> "Hello world", circuitBreaker);

    // Then
    assertThat(checkedSupplier.get()).isEqualTo("Hello world");
  }
コード例 #7
0
 private static List<CatchExceptionTest> createTests(int argsCount, int catchDrops) {
   if (catchDrops > argsCount || argsCount < 0 || catchDrops < 0) {
     throw new IllegalArgumentException(
         "argsCount = " + argsCount + ", catchDrops = " + catchDrops);
   }
   List<CatchExceptionTest> result = new ArrayList<>(TestCase.CONSTRUCTORS.size());
   for (Supplier<TestCase> constructor : TestCase.CONSTRUCTORS) {
     result.add(
         new CatchExceptionTest(constructor.get(), /* isVararg = */ true, argsCount, catchDrops));
     result.add(
         new CatchExceptionTest(constructor.get(), /* isVararg = */ false, argsCount, catchDrops));
   }
   return result;
 }
コード例 #8
0
  private void set(Supplier<T> result, int index) {
    try {

      Object current = result.get();

      final Object use = current;
      if (index < pipeline.functions.length) {
        Function op = pipeline.functions[index];
        this.pipeline.executors[index].execute(
            () -> {
              set(() -> (T) op.apply(use), index + 1);
            });
        return;
      }

      this.result.lazySet(current);
      done();

    } catch (Throwable t) {
      if (t instanceof CompletedException) {
        if (this.doFinally != null) doFinally.accept(this);
      }

      completeExceptionally(t);
    }
  }
コード例 #9
0
ファイル: LambdaTest.java プロジェクト: meshuga/typetools
  /**
   * Asserts that arguments can be resolved from lambda expressions for simple functional
   * interfaces.
   */
  public void shouldResolveArguments() {
    Predicate<String> predicate = str -> true;
    Function<String, Integer> fn = str -> Integer.valueOf(str);
    Supplier<String> supplier = () -> "test";
    Consumer<String> consumer = s -> {};

    assertEquals(
        TypeResolver.resolveRawArgument(Predicate.class, predicate.getClass()), String.class);
    assertEquals(
        TypeResolver.resolveRawArguments(Function.class, fn.getClass()),
        new Class<?>[] {String.class, Integer.class});
    assertEquals(
        TypeResolver.resolveRawArgument(Supplier.class, supplier.getClass()), String.class);
    assertEquals(
        TypeResolver.resolveRawArgument(Consumer.class, consumer.getClass()), String.class);
  }
コード例 #10
0
 @Override
 public Element findElement(Supplier<By> by) {
   Element element = new Element(super.findElement(by.get()));
   element.setSearchContext(this);
   element.setLocator((ExplicitWait e) -> this.untilFound2(by));
   return element;
 }
 @Override
 public HttpServerAuthenticationMechanism createAuthenticationMechanism(
     String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler) {
   for (Provider current : providers.get()) {
     Set<Service> services = current.getServices();
     if (services != null) {
       for (Service currentService : services) {
         if (SERVICE_TYPE.equals(currentService.getType())) {
           try {
             HttpServerAuthenticationMechanismFactory factory =
                 (HttpServerAuthenticationMechanismFactory) currentService.newInstance(null);
             HttpServerAuthenticationMechanism mechanism =
                 factory.createAuthenticationMechanism(mechanismName, properties, callbackHandler);
             if (mechanism != null) {
               return mechanism;
             }
           } catch (NoSuchAlgorithmException e) {
             log.debug(e);
           }
         }
       }
     }
   }
   return null;
 }
コード例 #12
0
 /** Return the beanCache creating it if necessary. */
 private ServerCache getBeanCache() {
   if (beanCache == null) {
     throw new IllegalStateException(
         "No bean cache enabled for " + desc + ". Add the @Cache annotation.");
   }
   return beanCache.get();
 }
コード例 #13
0
  private void performOnReplicas(ShardId primaryId, ReplicaRequest replicaRequest) {
    // we have to get a new state after successfully indexing into the primary in order to honour
    // recovery semantics.
    // we have to make sure that every operation indexed into the primary after recovery start will
    // also be replicated
    // to the recovery target. If we use an old cluster state, we may miss a relocation that has
    // started since then.
    // If the index gets deleted after primary operation, we skip replication
    final List<ShardRouting> shards = getShards(primaryId, clusterStateSupplier.get());
    final String localNodeId = primary.routingEntry().currentNodeId();
    for (final ShardRouting shard : shards) {
      if (executeOnReplicas == false || shard.unassigned()) {
        if (shard.primary() == false) {
          totalShards.incrementAndGet();
        }
        continue;
      }

      if (shard.currentNodeId().equals(localNodeId) == false) {
        performOnReplica(shard, replicaRequest);
      }

      if (shard.relocating() && shard.relocatingNodeId().equals(localNodeId) == false) {
        performOnReplica(shard.buildTargetRelocatingShard(), replicaRequest);
      }
    }
  }
コード例 #14
0
  @Override
  public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
      throws CatalogTransformerException {
    StringWriter stringWriter = new StringWriter();
    Boolean omitXmlDec = null;
    if (MapUtils.isNotEmpty(arguments)) {
      omitXmlDec = (Boolean) arguments.get(CswConstants.OMIT_XML_DECLARATION);
    }

    if (omitXmlDec == null || !omitXmlDec) {
      stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
    }

    PrettyPrintWriter writer = new PrettyPrintWriter(stringWriter, new NoNameCoder());

    MarshallingContext context = new TreeMarshaller(writer, null, null);
    copyArgumentsToContext(context, arguments);

    converterSupplier.get().marshal(metacard, writer, context);

    ByteArrayInputStream bais =
        new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));

    return new BinaryContentImpl(bais, new MimeType());
  }
コード例 #15
0
  /** Test method for {@link FailureReport#continueWith()}. */
  @Test
  public void continueWith() {
    final FailureReport<String> failReport = new FailureReport<>();
    final Runnable runTest = mock(Runnable.class);
    failReport.continueWith(runTest);
    assertThat(failReport.getContinueRoutine().get(), is(nullValue()));
    verify(runTest).run();

    @SuppressWarnings("unchecked")
    final Supplier<Object> continueTest = mock(Supplier.class);
    final Object returned = mock(Object.class);
    final FailureReport<Object> failReport2 = new FailureReport<>();
    failReport2.continueWith(continueTest);
    given(continueTest.get()).willReturn(returned);
    assertThat(failReport2.getContinueRoutine().get(), is(theInstance(returned)));
  }
コード例 #16
0
 public Stream<FieldInfo> getFieldStream() {
   return type.get()
       .getMembers()
       .stream()
       .filter(x -> x instanceof FieldDeclaration)
       .map(x -> new FieldDeclarationWrapper((FieldDeclaration) x));
 }
コード例 #17
0
 /**
  * Build a random search request.
  *
  * @param randomSearchSourceBuilder builds a random {@link SearchSourceBuilder}. You can use
  *     {@link #randomSearchSourceBuilder(Supplier, Supplier, Supplier, Supplier)}.
  */
 public static SearchRequest randomSearchRequest(
     Supplier<SearchSourceBuilder> randomSearchSourceBuilder) throws IOException {
   SearchRequest searchRequest = new SearchRequest();
   if (randomBoolean()) {
     searchRequest.indices(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.indicesOptions(
         IndicesOptions.fromOptions(
             randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()));
   }
   if (randomBoolean()) {
     searchRequest.types(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.preference(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.requestCache(randomBoolean());
   }
   if (randomBoolean()) {
     searchRequest.routing(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.scroll(randomPositiveTimeValue());
   }
   if (randomBoolean()) {
     searchRequest.searchType(randomFrom(SearchType.values()));
   }
   if (randomBoolean()) {
     searchRequest.source(randomSearchSourceBuilder.get());
   }
   return searchRequest;
 }
コード例 #18
0
 /** TODO: Documentation */
 default <E extends Throwable> T orThrow(final Supplier<E> exceptionSupplier) throws E {
   if (this.isPresent()) {
     return this.get();
   } else {
     throw exceptionSupplier.get();
   }
 }
コード例 #19
0
 public Stream<MethodInfo> getMethodStream() {
   return type.get()
       .getMembers()
       .stream()
       .map(this::getMethodInfoWrapper)
       .filter(Objects::nonNull);
 }
コード例 #20
0
 @Override
 public Builder add(Supplier<InvalidateMethodContribution> supplier) {
   Objects.requireNonNull(supplier);
   InvalidateMethodContribution contribution = supplier.get();
   Objects.requireNonNull(contribution, "Provided supplier returned null.");
   list.add(contribution);
   return this;
 }
コード例 #21
0
 /** Clear the bean cache. */
 void beanCacheClear() {
   if (beanCache != null) {
     if (beanLog.isDebugEnabled()) {
       beanLog.debug("   CLEAR {}", cacheName);
     }
     beanCache.get().clear();
   }
 }
コード例 #22
0
 public ServiceDiscovery getServiceDiscovery() {
   if (serviceDiscovery == null) {
     if (serviceDiscoverySupplier != null) {
       serviceDiscovery = serviceDiscoverySupplier.get();
     }
   }
   return serviceDiscovery;
 }
コード例 #23
0
 @Override
 public List<Type> getInterfaceTypes() {
   return type.get()
       .getImplements()
       .stream()
       .map(getContext()::resolve)
       .collect(Collectors.toList());
 }
コード例 #24
0
  @Override
  public Type getSuperType() {
    val extends_ = type.get().getExtends();

    if (extends_ == null || extends_.isEmpty()) return null;

    return getContext().resolve(extends_.get(0));
  }
コード例 #25
0
ファイル: Optional2.java プロジェクト: imace/tutorials
 public static <T> Optional<T> resolve(Supplier<T> resolver) {
   try {
     T result = resolver.get();
     return Optional.ofNullable(result);
   } catch (NullPointerException e) {
     return Optional.empty();
   }
 }
コード例 #26
0
 /** Clear the query cache. */
 void queryCacheClear() {
   if (queryCache != null) {
     if (queryLog.isDebugEnabled()) {
       queryLog.debug("   CLEAR {}", cacheName);
     }
     queryCache.get().clear();
   }
 }
コード例 #27
0
ファイル: FLineInteraction.java プロジェクト: cassiel/Field2
  @Override
  public void draw(Drawing context) {
    all = new LinkedHashSet<>();
    this.breadthFirst(this.both())
        .forEach(
            x -> {
              Rect r = x.properties.get(frame);

              {
                Map<String, Function<Box, FLine>> drawing =
                    x.properties.computeIfAbsent(interactiveDrawing, k -> new LinkedHashMap<>());

                if (drawing != null && drawing.size() > 0) {
                  Iterator<Function<Box, FLine>> it = drawing.values().iterator();
                  while (it.hasNext()) {
                    Function<Box, FLine> f = it.next();
                    FLine fl = f.apply(x);
                    if (fl == null) it.remove();
                    else all.add(fl);
                  }
                }
              }
              {
                Map<String, Supplier<FLine>> drawing =
                    x.properties.computeIfAbsent(
                        interactiveLines, k -> new LinkedHashMapAndArrayList<>());
                if (drawing != null && drawing.size() > 0) {
                  Iterator<Supplier<FLine>> it = drawing.values().iterator();
                  while (it.hasNext()) {
                    Supplier<FLine> f = it.next();
                    FLine fl = f.get();
                    if (fl == null) it.remove();
                    else all.add(fl);
                  }
                }
              }
            });
    for (FLine f : all)
      f.attributes.computeIfAbsent(
          projectedArea,
          (k) ->
              new Cached<FLine, Object, Area>(
                  (fline, previously) -> projectFLineToArea(fline),
                  (fline) -> new Object[] {fline, fline.getModCount()}));
  }
コード例 #28
0
 public static <T> CompletableFuture<T> toCompletableFuture(final Supplier<T> supplier) {
   CompletableFuture<T> future = new CompletableFuture<T>();
   try {
     future.complete(supplier.get());
   } catch (RuntimeException e) {
     future.completeExceptionally(e);
   }
   return future;
 }
コード例 #29
0
 @Override
 public void setName(String name) {
   String packageName = getPackageName();
   if (name.startsWith(packageName)) {
     type.get().setName(name.replace(packageName, ""));
   } else {
     throw new TransformationException("Name '" + name + "' must be in package: " + packageName);
   }
 }
コード例 #30
0
 @Override
 public AttributesMap map(ResultSet rs) throws SQLException {
   AttributesMap.Builder attributes = attributeMapBuilderSupplier.get();
   Iterator<AttributeMapper<?>> mapperIter = applicableMappers(rs.getMetaData()).iterator();
   while (mapperIter.hasNext()) {
     attributes.and(mapperIter.next().attributeAndValue(rs));
   }
   return attributes.build();
 }