Example usage for java.util.concurrent CompletableFuture thenAcceptAsync

List of usage examples for java.util.concurrent CompletableFuture thenAcceptAsync

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture thenAcceptAsync.

Prototype

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) 

Source Link

Usage

From source file:com.thinkbiganalytics.feedmgr.nifi.cache.NiFiFlowInspectorManager.java

public void addGroupToInspect(String groupId, int level, NiFiFlowInspection parent) {
    int nextLevel = level + 1;
    processGroupsToInspect.add(groupId);
    inspectingCount.incrementAndGet();//from  w w  w  .ja  v  a2  s  . c  o  m
    NiFiFlowInspector processGroupInspector = new NiFiFlowInspector(groupId, nextLevel, parent, restClient);
    CompletableFuture<NiFiFlowInspection> flowInspection = CompletableFuture
            .supplyAsync(() -> processGroupInspector.inspect(), executorService);
    flowInspection.thenAcceptAsync(this::flowInspectionComplete);

}

From source file:io.dropwizard.revolver.resource.RevolverRequestResource.java

private Response executeCommandAsync(final String service, final RevolverHttpApiConfig api,
        final RevolverHttpApiConfig.RequestMethod method, final String path, final HttpHeaders headers,
        final UriInfo uriInfo, final byte[] body, final boolean isDownstreamAsync, final String callMode)
        throws Exception {
    val sanatizedHeaders = new MultivaluedHashMap<String, String>();
    headers.getRequestHeaders().forEach(sanatizedHeaders::put);
    cleanHeaders(sanatizedHeaders, api);
    val httpCommand = RevolverBundle.getHttpCommand(service);
    val requestId = headers.getHeaderString(RevolversHttpHeaders.REQUEST_ID_HEADER);
    val transactionId = headers.getHeaderString(RevolversHttpHeaders.TXN_ID_HEADER);
    val mailBoxId = headers.getHeaderString(RevolversHttpHeaders.MAILBOX_ID_HEADER);
    //Short circuit if it is a duplicate request
    if (persistenceProvider.exists(requestId)) {
        return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(Collections.singletonMap("message", "Duplicate")).build();
    }//ww w  . ja  va2 s  . c  om
    persistenceProvider.saveRequest(requestId, mailBoxId,
            RevolverCallbackRequest.builder().api(api.getApi())
                    .mode(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALL_MODE_HEADER))
                    .callbackUri(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_URI_HEADER))
                    .method(headers.getRequestHeaders().getFirst(RevolversHttpHeaders.CALLBACK_METHOD_HEADER))
                    .service(service).path(path).headers(headers.getRequestHeaders())
                    .queryParams(uriInfo.getQueryParameters()).body(body).build());
    CompletableFuture<RevolverHttpResponse> response = httpCommand.executeAsync(RevolverHttpRequest.builder()
            .traceInfo(TraceInfo.builder().requestId(requestId).transactionId(transactionId)
                    .timestamp(System.currentTimeMillis()).build())
            .api(api.getApi()).service(service).path(path).method(method).headers(sanatizedHeaders)
            .queryParams(uriInfo.getQueryParameters()).body(body).build());
    //Async Downstream send accept on request path (Still circuit breaker will kick in. Keep circuit breaker aggressive)
    if (isDownstreamAsync) {
        val result = response.get();
        if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
        } else {
            persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
            saveResponse(requestId, result);
        }
        return transform(headers, result, api.getApi(), path, method);
    } else {
        response.thenAcceptAsync(result -> {
            if (result.getStatusCode() == Response.Status.ACCEPTED.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.REQUESTED);
            } else if (result.getStatusCode() == Response.Status.OK.getStatusCode()) {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.RESPONDED);
                saveResponse(requestId, result);
            } else {
                persistenceProvider.setRequestState(requestId, RevolverRequestState.ERROR);
                saveResponse(requestId, result);
            }
            if (callMode != null && callMode.equals(RevolverHttpCommand.CALL_MODE_CALLBACK)) {
                callbackHandler.handle(requestId);
            }
        });
        return Response.accepted().entity(RevolverAckMessage.builder().requestId(requestId)
                .acceptedAt(Instant.now().toEpochMilli()).build()).build();
    }
}

From source file:org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler.java

/**
 * Tears down connection points of pseudowires. We can either tear down both connection points,
 * or each one of them.//  w w  w .j  a v a2s  .c o m
 *
 * @param l2TunnelId The tunnel id for this pseudowire.
 * @param tearDownFirst Boolean, true if we want to tear down cp1
 * @param tearDownSecond Boolean, true if we want to tear down cp2
 * @param pending Boolean, if true remove only pseudowire from pending stores since no flows/groups
 *                in the network, else remove flows/groups in the devices also.
 * @return Result of tearing down the pseudowire, SUCCESS if everything was ok
 *         a descriptive error otherwise.
 */
private Result tearDownConnectionPoints(long l2TunnelId, boolean tearDownFirst, boolean tearDownSecond,
        boolean pending) {

    Result res;
    CompletableFuture<ObjectiveError> fwdInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> fwdTermNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revTermNextFuture = new CompletableFuture<>();

    if (l2TunnelId == 0) {
        log.warn("Removal process : Tunnel id cannot be 0");
        return Result.WRONG_PARAMETERS.appendError("Pseudowire id can not be 0.");
    }

    res = checkIfPwExists(l2TunnelId, pending);
    if (res != Result.SUCCESS) {
        return res;
    }

    // remove and get the tunnel and the policy from the appropriate store
    // if null, return error.
    Versioned<L2Tunnel> l2TunnelVersioned = pending ? pendingL2TunnelStore.remove(Long.toString(l2TunnelId))
            : l2TunnelStore.remove(Long.toString(l2TunnelId));
    Versioned<L2TunnelPolicy> l2TunnelPolicyVersioned = pending
            ? pendingL2PolicyStore.remove(Long.toString(l2TunnelId))
            : l2PolicyStore.remove(Long.toString(l2TunnelId));
    if ((l2TunnelVersioned == null) || (l2TunnelPolicyVersioned == null)) {
        log.warn("Removal process : Policy and/or tunnel missing for tunnel id {}", l2TunnelId);
        return Result.INTERNAL_ERROR.appendError("Policy and/or tunnel missing for pseudowire!");
    }

    L2TunnelDescription pwToRemove = new DefaultL2TunnelDescription(l2TunnelVersioned.value(),
            l2TunnelPolicyVersioned.value());

    // remove the reserved transport vlan
    if (!pwToRemove.l2Tunnel().transportVlan().equals(UNTAGGED_TRANSPORT_VLAN)) {
        vlanStore.remove(pwToRemove.l2Tunnel().transportVlan());
    }

    if (pending) {
        // no need to remove flows / groups for a pseudowire
        // in pending state
        return Result.SUCCESS;
    }

    // remove flows/groups involving with this pseudowire
    if (tearDownFirst) {
        log.info("Removal process : Tearing down forward direction of pseudowire {}", l2TunnelId);

        VlanId egressVlan = determineEgressVlan(pwToRemove.l2TunnelPolicy().cP1OuterTag(),
                pwToRemove.l2TunnelPolicy().cP1InnerTag(), pwToRemove.l2TunnelPolicy().cP2OuterTag(),
                pwToRemove.l2TunnelPolicy().cP2InnerTag());
        deletePolicy(l2TunnelId, pwToRemove.l2TunnelPolicy().cP1(), pwToRemove.l2TunnelPolicy().cP1InnerTag(),
                pwToRemove.l2TunnelPolicy().cP1OuterTag(), egressVlan, fwdInitNextFuture, FWD);

        fwdInitNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                // Finally we will tear down the pseudo wire.
                tearDownPseudoWireInit(l2TunnelId, pwToRemove.l2TunnelPolicy().cP1(), fwdTermNextFuture, FWD);
            }
        });

        fwdTermNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireTerm(pwToRemove.l2Tunnel(), pwToRemove.l2TunnelPolicy().cP2(), null, FWD);
            }
        });
    }

    if (tearDownSecond) {
        log.info("Removal process : Tearing down reverse direction of pseudowire {}", l2TunnelId);

        VlanId egressVlan = determineEgressVlan(pwToRemove.l2TunnelPolicy().cP2OuterTag(),
                pwToRemove.l2TunnelPolicy().cP2InnerTag(), pwToRemove.l2TunnelPolicy().cP1OuterTag(),
                pwToRemove.l2TunnelPolicy().cP1InnerTag());

        // We do the same operations on the reverse side.
        deletePolicy(l2TunnelId, pwToRemove.l2TunnelPolicy().cP2(), pwToRemove.l2TunnelPolicy().cP2InnerTag(),
                pwToRemove.l2TunnelPolicy().cP2OuterTag(), egressVlan, revInitNextFuture, REV);

        revInitNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireInit(l2TunnelId, pwToRemove.l2TunnelPolicy().cP2(), revTermNextFuture, REV);
            }
        });

        revTermNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireTerm(pwToRemove.l2Tunnel(), pwToRemove.l2TunnelPolicy().cP1(), null, REV);
            }
        });
    }

    return Result.SUCCESS;
}

From source file:org.onosproject.segmentrouting.pwaas.L2TunnelHandler.java

/**
 * Helper function to update a pw./*from   w ww.  ja  v  a 2  s . co  m*/
 *
 * @param oldPw the pseudo wire to remove
 * @param newPw the pseudo wirte to add
 */
private void updatePw(DefaultL2TunnelDescription oldPw, DefaultL2TunnelDescription newPw) {
    long tunnelId = oldPw.l2Tunnel().tunnelId();
    // The async tasks to orchestrate the next and
    // forwarding update.
    CompletableFuture<ObjectiveError> fwdInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> fwdTermNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revTermNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> fwdPwFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revPwFuture = new CompletableFuture<>();

    Result result = verifyPseudoWire(newPw);
    if (result != SUCCESS) {
        return;
    }
    // First we remove both policy.
    log.debug("Start deleting fwd policy for {}", tunnelId);
    deletePolicy(tunnelId, oldPw.l2TunnelPolicy().cP1(), oldPw.l2TunnelPolicy().cP1InnerTag(),
            oldPw.l2TunnelPolicy().cP1OuterTag(), fwdInitNextFuture, FWD);
    log.debug("Start deleting rev policy for {}", tunnelId);
    deletePolicy(tunnelId, oldPw.l2TunnelPolicy().cP2(), oldPw.l2TunnelPolicy().cP2InnerTag(),
            oldPw.l2TunnelPolicy().cP2OuterTag(), revInitNextFuture, REV);
    // Finally we remove both the tunnels.
    fwdInitNextFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Fwd policy removed. Now remove fwd {} for {}", INITIATION, tunnelId);
            tearDownPseudoWireInit(tunnelId, oldPw.l2TunnelPolicy().cP1(), fwdTermNextFuture, FWD);
        }
    });
    revInitNextFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Rev policy removed. Now remove rev {} for {}", INITIATION, tunnelId);
            tearDownPseudoWireInit(tunnelId, oldPw.l2TunnelPolicy().cP2(), revTermNextFuture, REV);

        }
    });
    fwdTermNextFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Fwd {} removed. Now remove fwd {} for {}", INITIATION, TERMINATION, tunnelId);
            tearDownPseudoWireTerm(oldPw.l2Tunnel(), oldPw.l2TunnelPolicy().cP2(), fwdPwFuture, FWD);
        }
    });
    revTermNextFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Rev {} removed. Now remove rev {} for {}", INITIATION, TERMINATION, tunnelId);
            tearDownPseudoWireTerm(oldPw.l2Tunnel(), oldPw.l2TunnelPolicy().cP1(), revPwFuture, REV);
        }
    });
    // At the end we install the new pw.
    fwdPwFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Deploying new fwd pw for {}", tunnelId);
            Result lamdaResult = deployPseudoWireInit(newPw.l2Tunnel(), newPw.l2TunnelPolicy().cP1(),
                    newPw.l2TunnelPolicy().cP2(), FWD);
            if (lamdaResult != SUCCESS) {
                return;
            }
            lamdaResult = deployPolicy(tunnelId, newPw.l2TunnelPolicy().cP1(),
                    newPw.l2TunnelPolicy().cP1InnerTag(), newPw.l2TunnelPolicy().cP1OuterTag(),
                    lamdaResult.nextId);
            if (lamdaResult != SUCCESS) {
                return;
            }
            deployPseudoWireTerm(newPw.l2Tunnel(), newPw.l2TunnelPolicy().cP2(),
                    newPw.l2TunnelPolicy().cP2OuterTag(), FWD);

        }
    });
    revPwFuture.thenAcceptAsync(status -> {
        if (status == null) {
            log.debug("Deploying new rev pw for {}", tunnelId);
            Result lamdaResult = deployPseudoWireInit(newPw.l2Tunnel(), newPw.l2TunnelPolicy().cP2(),
                    newPw.l2TunnelPolicy().cP1(), REV);
            if (lamdaResult != SUCCESS) {
                return;
            }
            lamdaResult = deployPolicy(tunnelId, newPw.l2TunnelPolicy().cP2(),
                    newPw.l2TunnelPolicy().cP2InnerTag(), newPw.l2TunnelPolicy().cP2OuterTag(),
                    lamdaResult.nextId);
            if (lamdaResult != SUCCESS) {
                return;
            }
            deployPseudoWireTerm(newPw.l2Tunnel(), newPw.l2TunnelPolicy().cP1(),
                    newPw.l2TunnelPolicy().cP1OuterTag(), REV);
        }
    });
}