Search in sources :

Example 16 with Function

use of java.util.function.Function in project elasticsearch by elastic.

the class AbstractFilteringJsonGeneratorTestCase method testWithLfAtEnd.

public void testWithLfAtEnd() throws IOException {
    final Function<XContentBuilder, XContentBuilder> build = builder -> {
        try {
            return builder.startObject().startObject("foo").field("bar", "baz").endObject().endObject().prettyPrint().lfAtEnd();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
    XContentBuilder expected = build.apply(newXContentBuilder());
    assertXContentBuilder(expected, build.apply(newXContentBuilderWithIncludes("foo")));
    assertXContentBuilder(expected, build.apply(newXContentBuilderWithExcludes("bar")));
    assertXContentBuilder(expected, build.apply(newXContentBuilder(singleton("f*"), singleton("baz"))));
    expected = newXContentBuilder().startObject().endObject().prettyPrint().lfAtEnd();
    assertXContentBuilder(expected, build.apply(newXContentBuilderWithExcludes("foo")));
    assertXContentBuilder(expected, build.apply(newXContentBuilderWithIncludes("bar")));
    assertXContentBuilder(expected, build.apply(newXContentBuilder(singleton("f*"), singleton("foo"))));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) Collections.emptySet(java.util.Collections.emptySet) XContentType(org.elasticsearch.common.xcontent.XContentType) XContent(org.elasticsearch.common.xcontent.XContent) Set(java.util.Set) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) BytesReference(org.elasticsearch.common.bytes.BytesReference) Function(java.util.function.Function) Sets(org.elasticsearch.common.util.set.Sets) XContentParser(org.elasticsearch.common.xcontent.XContentParser) Collections.singleton(java.util.Collections.singleton) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ESTestCase(org.elasticsearch.test.ESTestCase) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 17 with Function

use of java.util.function.Function in project failsafe by jhalterman.

the class Java8Example method main.

@SuppressWarnings("unused")
public static void main(String... args) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    RetryPolicy retryPolicy = new RetryPolicy();
    // Create a retryable functional interface
    Function<String, String> bar = value -> Failsafe.with(retryPolicy).get(() -> value + "bar");
    // Create a retryable runnable Stream
    Failsafe.with(retryPolicy).run(() -> Stream.of("foo").map(value -> value + "bar").forEach(System.out::println));
    // Create a retryable callable Stream
    Failsafe.with(retryPolicy).get(() -> Stream.of("foo").map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).collect(Collectors.toList()));
    // Create a individual retryable Stream operation
    Stream.of("foo").map(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).forEach(System.out::println);
    // Create a retryable CompletableFuture
    Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> "foo").thenApplyAsync(value -> value + "bar").thenAccept(System.out::println));
    // Create an individual retryable CompletableFuture stages
    CompletableFuture.supplyAsync(() -> Failsafe.with(retryPolicy).get(() -> "foo")).thenApplyAsync(value -> Failsafe.with(retryPolicy).get(() -> value + "bar")).thenAccept(System.out::println);
}
Also used : Stream(java.util.stream.Stream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CompletableFuture(java.util.concurrent.CompletableFuture) RetryPolicy(net.jodah.failsafe.RetryPolicy) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Failsafe(net.jodah.failsafe.Failsafe) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Example 18 with Function

use of java.util.function.Function in project storm by apache.

the class WorkerState method refreshLoad.

public void refreshLoad() {
    Set<Integer> remoteTasks = Sets.difference(new HashSet<Integer>(outboundTasks), new HashSet<>(taskIds));
    Long now = System.currentTimeMillis();
    Map<Integer, Double> localLoad = shortExecutorReceiveQueueMap.entrySet().stream().collect(Collectors.toMap((Function<Map.Entry<Integer, DisruptorQueue>, Integer>) Map.Entry::getKey, (Function<Map.Entry<Integer, DisruptorQueue>, Double>) entry -> {
        DisruptorQueue.QueueMetrics qMetrics = entry.getValue().getMetrics();
        return ((double) qMetrics.population()) / qMetrics.capacity();
    }));
    Map<Integer, Load> remoteLoad = new HashMap<>();
    cachedNodeToPortSocket.get().values().stream().forEach(conn -> remoteLoad.putAll(conn.getLoad(remoteTasks)));
    loadMapping.setLocal(localLoad);
    loadMapping.setRemote(remoteLoad);
    if (now > nextUpdate.get()) {
        receiver.sendLoadMetrics(localLoad);
        nextUpdate.set(now + LOAD_REFRESH_INTERVAL_MS);
    }
}
Also used : Load(org.apache.storm.grouping.Load) DisruptorQueue(org.apache.storm.utils.DisruptorQueue) Function(java.util.function.Function) AtomicLong(java.util.concurrent.atomic.AtomicLong) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 19 with Function

use of java.util.function.Function in project hbase by apache.

the class TestAsyncTableBatch method test.

@Test
public void test() throws InterruptedException, ExecutionException, IOException {
    AsyncTableBase table = tableGetter.apply(TABLE_NAME);
    table.putAll(IntStream.range(0, COUNT).mapToObj(i -> new Put(getRow(i)).addColumn(FAMILY, CQ, Bytes.toBytes(i))).collect(Collectors.toList())).get();
    List<Result> results = table.getAll(IntStream.range(0, COUNT).mapToObj(i -> Arrays.asList(new Get(getRow(i)), new Get(Arrays.copyOf(getRow(i), 4)))).flatMap(l -> l.stream()).collect(Collectors.toList())).get();
    assertEquals(2 * COUNT, results.size());
    for (int i = 0; i < COUNT; i++) {
        assertEquals(i, Bytes.toInt(results.get(2 * i).getValue(FAMILY, CQ)));
        assertTrue(results.get(2 * i + 1).isEmpty());
    }
    Admin admin = TEST_UTIL.getAdmin();
    admin.flush(TABLE_NAME);
    TEST_UTIL.getHBaseCluster().getRegions(TABLE_NAME).forEach(r -> {
        byte[] startKey = r.getRegionInfo().getStartKey();
        int number = startKey.length == 0 ? 55 : Integer.parseInt(Bytes.toString(startKey));
        byte[] splitPoint = Bytes.toBytes(String.format("%03d", number + 55));
        try {
            admin.splitRegion(r.getRegionInfo().getRegionName(), splitPoint);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
    // we are not going to test the function of split so no assertion here. Just wait for a while
    // and then start our work.
    Thread.sleep(5000);
    table.deleteAll(IntStream.range(0, COUNT).mapToObj(i -> new Delete(getRow(i))).collect(Collectors.toList())).get();
    results = table.getAll(IntStream.range(0, COUNT).mapToObj(i -> new Get(getRow(i))).collect(Collectors.toList())).get();
    assertEquals(COUNT, results.size());
    results.forEach(r -> assertTrue(r.isEmpty()));
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) CompletableFuture(java.util.concurrent.CompletableFuture) ClientTests(org.apache.hadoop.hbase.testclassification.ClientTests) Function(java.util.function.Function) ArrayList(java.util.ArrayList) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) HTableDescriptor(org.apache.hadoop.hbase.HTableDescriptor) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) After(org.junit.After) RegionCoprocessorEnvironment(org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment) Parameterized(org.junit.runners.Parameterized) Cell(org.apache.hadoop.hbase.Cell) Bytes(org.apache.hadoop.hbase.util.Bytes) Before(org.junit.Before) TableName(org.apache.hadoop.hbase.TableName) AfterClass(org.junit.AfterClass) RegionObserver(org.apache.hadoop.hbase.coprocessor.RegionObserver) Parameter(org.junit.runners.Parameterized.Parameter) Assert.assertTrue(org.junit.Assert.assertTrue) LargeTests(org.apache.hadoop.hbase.testclassification.LargeTests) IOException(java.io.IOException) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) Collectors(java.util.stream.Collectors) UncheckedIOException(java.io.UncheckedIOException) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) HBaseTestingUtility(org.apache.hadoop.hbase.HBaseTestingUtility) ForkJoinPool(java.util.concurrent.ForkJoinPool) ObserverContext(org.apache.hadoop.hbase.coprocessor.ObserverContext) Assert.assertEquals(org.junit.Assert.assertEquals) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Test(org.junit.Test)

Example 20 with Function

use of java.util.function.Function in project che by eclipse.

the class RefactoringService method createMoveRefactoring.

/**
     * Create move refactoring session.
     *
     * @param cmr
     *         move settings, contains resource paths to move.
     * @return refactoring session id.
     * @throws JavaModelException
     *         when JavaModel has a failure
     * @throws RefactoringException
     *         when impossible to create move refactoring session
     */
@POST
@Path("move/create")
@Consumes("application/json")
@Produces("text/plain")
public String createMoveRefactoring(CreateMoveRefactoring cmr) throws JavaModelException, RefactoringException {
    IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath());
    IJavaElement[] javaElements;
    try {
        Function<ElementToMove, IJavaElement> map = javaElement -> {
            try {
                if (javaElement.isPack()) {
                    return javaProject.findPackageFragment(new org.eclipse.core.runtime.Path(javaElement.getPath()));
                } else {
                    return javaProject.findType(javaElement.getPath()).getCompilationUnit();
                }
            } catch (JavaModelException e) {
                throw new IllegalArgumentException(e);
            }
        };
        javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new);
    } catch (IllegalArgumentException e) {
        if (e.getCause() instanceof JavaModelException) {
            throw (JavaModelException) e.getCause();
        } else {
            throw e;
        }
    }
    if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) {
        return manager.createMoveRefactoringSession(javaElements);
    }
    throw new RefactoringException("Can't create move refactoring.");
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Produces(javax.ws.rs.Produces) JavaModelException(org.eclipse.jdt.core.JavaModelException) GET(javax.ws.rs.GET) ReorgDestination(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ReorgDestination) Inject(com.google.inject.Inject) MoveSettings(org.eclipse.che.ide.ext.java.shared.dto.refactoring.MoveSettings) RefactoringStatus(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringStatus) Path(javax.ws.rs.Path) CoreException(org.eclipse.core.runtime.CoreException) Function(java.util.function.Function) LinkedRenameRefactoringApply(org.eclipse.che.ide.ext.java.shared.dto.refactoring.LinkedRenameRefactoringApply) RefactoringChange(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringChange) JavaModelManager(org.eclipse.jdt.internal.core.JavaModelManager) RefactoringPreview(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringPreview) JavaModel(org.eclipse.jdt.internal.core.JavaModel) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) RefactoringException(org.eclipse.che.plugin.java.server.refactoring.RefactoringException) RenameSettings(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RenameSettings) ChangeEnabledState(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangeEnabledState) RefactoringManager(org.eclipse.che.plugin.java.server.refactoring.RefactoringManager) ValidateNewName(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ValidateNewName) ChangePreview(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangePreview) POST(javax.ws.rs.POST) IJavaProject(org.eclipse.jdt.core.IJavaProject) RefactoringAvailabilityTester(org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester) ChangeCreationResult(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangeCreationResult) CreateRenameRefactoring(org.eclipse.che.ide.ext.java.shared.dto.refactoring.CreateRenameRefactoring) RefactoringSession(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringSession) ElementToMove(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ElementToMove) CreateMoveRefactoring(org.eclipse.che.ide.ext.java.shared.dto.refactoring.CreateMoveRefactoring) RefactoringResult(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringResult) IJavaElement(org.eclipse.jdt.core.IJavaElement) Response(javax.ws.rs.core.Response) RenameRefactoringSession(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RenameRefactoringSession) IResource(org.eclipse.core.resources.IResource) Path(javax.ws.rs.Path) IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) ElementToMove(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ElementToMove) RefactoringException(org.eclipse.che.plugin.java.server.refactoring.RefactoringException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

Function (java.util.function.Function)1261 List (java.util.List)606 Map (java.util.Map)447 ArrayList (java.util.ArrayList)416 Test (org.junit.Test)358 Collectors (java.util.stream.Collectors)324 HashMap (java.util.HashMap)287 Collections (java.util.Collections)284 Arrays (java.util.Arrays)271 Set (java.util.Set)255 IOException (java.io.IOException)252 Collection (java.util.Collection)192 HashSet (java.util.HashSet)191 TimeUnit (java.util.concurrent.TimeUnit)174 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)158 Optional (java.util.Optional)157 Assert (org.junit.Assert)137 Consumer (java.util.function.Consumer)134 Supplier (java.util.function.Supplier)126 CompletableFuture (java.util.concurrent.CompletableFuture)121