Example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction

List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction.

Prototype

AsyncFunction

Source Link

Usage

From source file:org.opendaylight.centinel.impl.CentinelAlertConditionImpl.java

@Override
public Future<RpcResult<UpdateAlertMessageCountRuleOutput>> updateAlertMessageCountRule(
        final UpdateAlertMessageCountRuleInput input) {
    boolean idMatches = false;
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<UpdateAlertMessageCountRuleOutput>> futureResult = SettableFuture.create();
    if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()
            || input.getRuleID() == null || input.getRuleID().isEmpty() || input.getRuleID().trim().isEmpty()) {
        LOG.debug("Invalid Parameters for UpdateAlertMessageCountRule");
        return Futures.immediateFailedCheckedFuture(
                new TransactionCommitFailedException("inalid-input", RpcResultBuilder.newError(
                        ErrorType.APPLICATION, "invalid-input", "StreamId and RuleId are mandatory fields")));
    }//from   w  ww .ja v  a  2  s  . c  om
    final UpdateAlertMessageCountRuleOutputBuilder updateAlertMessageCountRuleOutputBuilder = new UpdateAlertMessageCountRuleOutputBuilder();
    updateAlertMessageCountRuleOutputBuilder.setMessageCountOperator(input.getMessageCountOperator());
    updateAlertMessageCountRuleOutputBuilder.setMessageCountCount(input.getMessageCountCount());
    updateAlertMessageCountRuleOutputBuilder.setMessageCountGrace(input.getMessageCountGrace());
    updateAlertMessageCountRuleOutputBuilder.setMessageCountBacklog(input.getMessageCountBacklog());
    updateAlertMessageCountRuleOutputBuilder.setRuleID(input.getRuleID());
    updateAlertMessageCountRuleOutputBuilder.setNodeType(input.getNodeType());
    updateAlertMessageCountRuleOutputBuilder.setRuleTypeClassifier(input.getRuleTypeClassifier());
    updateAlertMessageCountRuleOutputBuilder.setStreamID(input.getStreamID());
    updateAlertMessageCountRuleOutputBuilder.setTimeStamp(input.getTimeStamp());
    updateAlertMessageCountRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier());
    updateAlertMessageCountRuleOutputBuilder.setAlertName(input.getAlertName());

    ListenableFuture<Optional<AlertMessageCountRuleRecord>> readFutureOperational = tx
            .read(LogicalDatastoreType.OPERATIONAL, alertMessageCountRuleRecordId);

    ListenableFuture<Optional<AlertMessageCountRuleRecord>> readFutureConfigure = tx
            .read(LogicalDatastoreType.CONFIGURATION, alertMessageCountRuleRecordId);

    String configId = null;

    try {

        Optional<AlertMessageCountRuleRecord> record = readFutureOperational.get();
        if (record.isPresent()) {
            AlertMessageCountRuleRecord operationalRecord = readFutureOperational.get().get();
            List<StreamAlertMessageCountRuleList> streamAlertRuleList = new ArrayList<StreamAlertMessageCountRuleList>();

            if (!operationalRecord.getStreamAlertMessageCountRuleList().isEmpty()) {

                streamAlertRuleList = operationalRecord.getStreamAlertMessageCountRuleList();
                Iterator<StreamAlertMessageCountRuleList> itearator = streamAlertRuleList.iterator();

                StreamAlertMessageCountRuleList operationalObject = null;

                while (itearator.hasNext()) {

                    operationalObject = itearator.next();
                    if (operationalObject.getRuleID().equalsIgnoreCase(input.getRuleID())
                            && operationalObject.getStreamID().equalsIgnoreCase(input.getStreamID())) {

                        configId = operationalObject.getConfigID();
                        idMatches = true;

                    }
                }
                if (!idMatches) {
                    return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
                            "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                                    "Invalid Stream/Rule id or The stream/Rule is not present in operational data store")));

                }

            }

        } else {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "Record is not present in operational data store")));
        }
    } catch (InterruptedException | ExecutionException e) {

        futureResult.set(RpcResultBuilder.<UpdateAlertMessageCountRuleOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;

    }
    final String configID = configId;

    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<AlertMessageCountRuleRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(
                        final Optional<AlertMessageCountRuleRecord> alertMessageCountRuleRecord)
                        throws Exception {

                    List<StreamAlertMessageCountRuleList> streamAlertRuleList = new ArrayList<StreamAlertMessageCountRuleList>();
                    List<StreamAlertMessageCountRuleList> updatedStreamAlertRuleList = new ArrayList<StreamAlertMessageCountRuleList>();

                    if (alertMessageCountRuleRecord.isPresent()) {

                        streamAlertRuleList = alertMessageCountRuleRecord.get()
                                .getStreamAlertMessageCountRuleList();
                        StreamAlertMessageCountRuleList configObject = null;
                        Iterator<StreamAlertMessageCountRuleList> iterator = streamAlertRuleList.iterator();

                        while (iterator.hasNext()) {

                            configObject = iterator.next();

                            if (configObject.getConfigID().equalsIgnoreCase(configID)) {

                                updatedStreamAlertRuleList
                                        .add(buildUpdateAlertMessageCountRuleRecord(input, configObject));
                                tx.merge(LogicalDatastoreType.CONFIGURATION, alertMessageCountRuleRecordId,
                                        new AlertMessageCountRuleRecordBuilder()
                                                .setStreamAlertMessageCountRuleList(updatedStreamAlertRuleList)
                                                .build());

                            }
                        }

                    }

                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<UpdateAlertMessageCountRuleOutput>success(
                    updateAlertMessageCountRuleOutputBuilder.build()).build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.info("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<UpdateAlertMessageCountRuleOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());

        }
    });

    return futureResult;
}

From source file:org.opendaylight.vbd.impl.VbdBridgeDomain.java

private ListenableFuture<Void> addSupportingBridgeDomain(
        final ListenableFuture<Void> addVppToBridgeDomainFuture, final Node node) {
    return Futures.transform(addVppToBridgeDomainFuture, new AsyncFunction<Void, Void>() {

        @Override/*from  w w  w .  j a v a2 s . c  o  m*/
        public ListenableFuture<Void> apply(@Nonnull Void input) throws Exception {
            LOG.debug("Storing bridge member to operational DS....");
            final BridgeMemberBuilder bridgeMemberBuilder = new BridgeMemberBuilder();
            bridgeMemberBuilder.setSupportingBridgeDomain(new ExternalReference(iiBridgeDomainOnVPPRest));
            final InstanceIdentifier<BridgeMember> iiToBridgeMember = topology.child(Node.class, node.getKey())
                    .augmentation(NodeVbridgeAugment.class).child(BridgeMember.class);
            final WriteTransaction wTx = chain.newWriteOnlyTransaction();
            wTx.put(LogicalDatastoreType.OPERATIONAL, iiToBridgeMember, bridgeMemberBuilder.build(), true);
            return wTx.submit();
        }
    });
}

From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<Void>> clearStaticRoute(ClearStaticRouteInput input) {
    FabricId fabricId = input.getFabricId();
    NodeId ldev = input.getNodeId();/*from   ww w.  jav a2  s  . c o m*/

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }

    final InstanceIdentifier<Routes> routesIId = MdSalUtils.createNodeIId(fabricId, ldev)
            .augmentation(LogicalRouterAugment.class).child(LrAttribute.class).child(Routes.class);

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();
    if (MdSalUtils.syncReadOper(trans, routesIId).isPresent()) {
        trans.delete(LogicalDatastoreType.OPERATIONAL, routesIId);

        return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<Void>>() {

            @Override
            public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
                fabricObj.notifyRouteCleared(routesIId.firstIdentifierOf(Node.class));
                return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
            }
        }, executor);
    } else {
        return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
    }
}

From source file:org.opendaylight.vpnservice.alivenessmonitor.internal.AlivenessMonitor.java

private void sendMonitorPacket(final MonitoringInfo monitoringInfo) {
    //TODO: Handle interrupts
    final Long monitorId = monitoringInfo.getId();
    final String monitorKey = monitorIdKeyCache.getUnchecked(monitorId);
    if (monitorKey == null) {
        LOG.warn("No monitor Key associated with id {} to send the monitor packet", monitorId);
        return;//from   ww  w  .  ja va2  s.  c o m
    } else {
        LOG.debug("Sending monitoring packet for key: {}", monitorKey);
    }

    final MonitorProfile profile;
    Optional<MonitorProfile> optProfile = getMonitorProfile(monitoringInfo.getProfileId());
    if (optProfile.isPresent()) {
        profile = optProfile.get();
    } else {
        LOG.warn(
                "No monitor profile associated with id {}. "
                        + "Could not send Monitor packet for monitor-id {}",
                monitoringInfo.getProfileId(), monitorId);
        return;
    }

    final Semaphore lock = lockMap.get(monitorKey);
    LOG.debug("Acquiring lock for monitor key : {} to send monitor packet", monitorKey);
    acquireLock(lock);

    final ReadWriteTransaction tx = broker.newReadWriteTransaction();
    ListenableFuture<Optional<MonitoringState>> readResult = tx.read(LogicalDatastoreType.OPERATIONAL,
            getMonitorStateId(monitorKey));
    ListenableFuture<Void> writeResult = Futures.transform(readResult,
            new AsyncFunction<Optional<MonitoringState>, Void>() {

                @Override
                public ListenableFuture<Void> apply(Optional<MonitoringState> optState) throws Exception {
                    if (optState.isPresent()) {
                        MonitoringState state = optState.get();

                        //Increase the request count
                        Long requestCount = state.getRequestCount() + 1;

                        //Check with the monitor window
                        LivenessState currentLivenessState = state.getState();

                        //Increase the pending response count
                        long responsePendingCount = state.getResponsePendingCount();
                        if (responsePendingCount < profile.getMonitorWindow()) {
                            responsePendingCount = responsePendingCount + 1;
                        }

                        //Check with the failure thresold
                        if (responsePendingCount >= profile.getFailureThreshold()) {
                            //Change the state to down and notify
                            if (currentLivenessState != LivenessState.Down) {
                                LOG.debug("Response pending Count: {}, Failure threshold: {} for monitorId {}",
                                        responsePendingCount, profile.getFailureThreshold(),
                                        state.getMonitorId());
                                LOG.info("Sending notification for monitor Id : {} with State: {}",
                                        state.getMonitorId(), LivenessState.Down);
                                publishNotification(monitorId, LivenessState.Down);
                                currentLivenessState = LivenessState.Down;
                                //Reset requestCount when state changes from UP to DOWN
                                requestCount = INITIAL_COUNT;
                            }
                        }

                        //Update the ODS with state
                        MonitoringState updatedState = new MonitoringStateBuilder(/*state*/)
                                .setMonitorKey(state.getMonitorKey()).setRequestCount(requestCount)
                                .setResponsePendingCount(responsePendingCount).setState(currentLivenessState)
                                .build();
                        tx.merge(LogicalDatastoreType.OPERATIONAL, getMonitorStateId(state.getMonitorKey()),
                                updatedState);
                        return tx.submit();
                    } else {
                        //Close the transaction
                        tx.submit();
                        String errorMsg = String.format(
                                "Monitoring State associated with id %d is not present to send packet out.",
                                monitorId);
                        return Futures.immediateFailedFuture(new RuntimeException(errorMsg));
                    }
                }

            });

    Futures.addCallback(writeResult, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void noarg) {
            //invoke packetout on protocol handler
            AlivenessProtocolHandler handler = ethTypeToProtocolHandler.get(profile.getProtocolType());
            if (handler != null) {
                LOG.debug("Sending monitoring packet {}", monitoringInfo);
                handler.sendPacketOut(monitoringInfo);
            }
            releaseLock(lock);
        }

        @Override
        public void onFailure(Throwable error) {
            LOG.warn("Updating monitoring state for key: {} failed. Monitoring packet is not sent", monitorKey,
                    error);
            releaseLock(lock);
        }

    });

}

From source file:org.opendaylight.centinel.impl.CentinelImpl.java

/** 
 *    Update Alert Field Content Rule in configurational data store. 
 * //from   ww w. ja  va 2s.c  o  m
 */

@Override
public Future<RpcResult<UpdateAlertFieldContentRuleOutput>> updateAlertFieldContentRule(
        final UpdateAlertFieldContentRuleInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<UpdateAlertFieldContentRuleOutput>> futureResult = SettableFuture.create();
    LOG.info("updateAlertFieldContentRule: " + input);
    final UpdateAlertFieldContentRuleOutputBuilder updateAlertFieldContentRuleOutputBuilder = new UpdateAlertFieldContentRuleOutputBuilder();
    updateAlertFieldContentRuleOutputBuilder.setFieldContentBacklog(input.getFieldContentBacklog());
    updateAlertFieldContentRuleOutputBuilder
            .setFieldContentCompareToValue(input.getFieldContentCompareToValue());
    updateAlertFieldContentRuleOutputBuilder.setFieldContentField(input.getFieldContentField());
    updateAlertFieldContentRuleOutputBuilder.setFieldContentGrace(input.getFieldContentGrace());
    updateAlertFieldContentRuleOutputBuilder.setRuleID(input.getRuleID());
    updateAlertFieldContentRuleOutputBuilder.setNodeType(input.getNodeType());
    updateAlertFieldContentRuleOutputBuilder.setRuleTypeClassifier(input.getRuleTypeClassifier());
    updateAlertFieldContentRuleOutputBuilder.setStreamID(input.getStreamID());
    updateAlertFieldContentRuleOutputBuilder.setTimeStamp(input.getTimeStamp());
    updateAlertFieldContentRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier());

    ListenableFuture<Optional<AlertFieldContentRuleRecord>> readFutureOperational = tx
            .read(LogicalDatastoreType.OPERATIONAL, alertFeildContentRuleRecordId);

    ListenableFuture<Optional<AlertFieldContentRuleRecord>> readFutureConfigure = tx
            .read(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId);

    String configId = null;

    try {
        AlertFieldContentRuleRecord operationalRecord = readFutureOperational.get().get();
        List<StreamAlertFieldContentRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();

        if (!operationalRecord.getStreamAlertFieldContentRuleList().isEmpty()) {
            streamAlertRuleList = operationalRecord.getStreamAlertFieldContentRuleList();
            Iterator<StreamAlertFieldContentRuleList> itearator = streamAlertRuleList.iterator();
            StreamAlertFieldContentRuleList operationalObject = null;

            while (itearator.hasNext()) {
                operationalObject = itearator.next();
                if (operationalObject.getRuleID().equalsIgnoreCase(input.getRuleID())
                        && operationalObject.getStreamID().equalsIgnoreCase(input.getStreamID())) {
                    configId = operationalObject.getConfigID();

                }
            }

        }

    } catch (InterruptedException | ExecutionException e) {
        futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;

    }
    final String configID = configId;
    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<AlertFieldContentRuleRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(
                        final Optional<AlertFieldContentRuleRecord> alertFieldContentRuleRecord)
                        throws Exception {

                    List<StreamAlertFieldContentRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();
                    List<StreamAlertFieldContentRuleList> updatedStreamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();
                    if (alertFieldContentRuleRecord.isPresent()) {
                        streamAlertRuleList = alertFieldContentRuleRecord.get()
                                .getStreamAlertFieldContentRuleList();
                        StreamAlertFieldContentRuleList configObject = null;
                        Iterator<StreamAlertFieldContentRuleList> iterator = streamAlertRuleList.iterator();
                        while (iterator.hasNext()) {
                            configObject = iterator.next();

                            if (configObject.getConfigID().equalsIgnoreCase(configID)) {
                                updatedStreamAlertRuleList
                                        .add(buildUpdateAlertFieldContentRuleRecord(input, configObject));
                                tx.merge(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId,
                                        new AlertFieldContentRuleRecordBuilder()
                                                .setStreamAlertFieldContentRuleList(updatedStreamAlertRuleList)
                                                .build());

                            }

                        }

                    }

                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>success(
                    updateAlertFieldContentRuleOutputBuilder.build()).build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.debug("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());

        }
    });

    return futureResult;
}

From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<Void>> rmStaticRoute(RmStaticRouteInput input) {
    final List<Ipv4Prefix> destIps = input.getDestinationPrefix();
    FabricId fabricId = input.getFabricId();
    NodeId ldev = input.getNodeId();/*from  w  ww.j a v  a2 s .  c  o  m*/

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }

    final List<Route> routes = Lists.newArrayList();
    for (Ipv4Prefix destIp : destIps) {
        routes.add(new RouteBuilder().setKey(new RouteKey(destIp)).build());
    }

    final InstanceIdentifier<Routes> routesIId = MdSalUtils.createNodeIId(fabricId, ldev)
            .augmentation(LogicalRouterAugment.class).child(LrAttribute.class).child(Routes.class);

    WriteTransaction trans = dataBroker.newWriteOnlyTransaction();
    for (Route route : routes) {
        trans.delete(LogicalDatastoreType.OPERATIONAL, routesIId.child(Route.class, route.getKey()));
    }

    return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception {
            fabricObj.notifyRouteUpdated(routesIId.firstIdentifierOf(Node.class), routes, true);
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
    }, executor);
}

From source file:org.opendaylight.centinel.impl.CentinelStreamImpl.java

@Override
public Future<RpcResult<SetRuleOutput>> setRule(final SetRuleInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<SetRuleOutput>> futureResult = SettableFuture.create();
    boolean idMatches = false;
    final String streamRuleId = generateRandomId();
    if (input.getType() == StreamType.FieldPresence) {
        if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()
                || input.getField() == null || input.getField().isEmpty()
                || input.getField().trim().isEmpty()) {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("inalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "StreamId,Value are mandatory parameters")));
        }//  www .ja va 2 s .c  om
    } else {
        if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()
                || input.getField() == null || input.getField().isEmpty() || input.getField().trim().isEmpty()
                || input.getValue() == null || input.getValue().isEmpty()
                || input.getValue().trim().isEmpty()) {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("inalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "StreamId,Value and Field are mandatory parameters")));
        }
    }
    final SetRuleOutputBuilder setRuleOutputBuilder = new SetRuleOutputBuilder();
    setRuleOutputBuilder.setStreamRuleID(streamRuleId);
    ListenableFuture<Optional<StreamRecord>> readFutureOperational = tx.read(LogicalDatastoreType.OPERATIONAL,
            streamRecordId);

    ListenableFuture<Optional<StreamRecord>> readFutureConfigure = tx.read(LogicalDatastoreType.CONFIGURATION,
            streamRecordId);

    String configIdOp = null;
    String streamIdOp = null;

    try {
        Optional<StreamRecord> record = readFutureOperational.get();
        if (record.isPresent()) {

            StreamRecord operationalRecord = record.get();

            List<StreamList> streamRulesList = new ArrayList<StreamList>();

            if (!operationalRecord.getStreamList().isEmpty()) {

                streamRulesList = operationalRecord.getStreamList();
                Iterator<StreamList> iterator = streamRulesList.iterator();

                while (iterator.hasNext()) {

                    StreamList operationalObject = iterator.next();

                    if (operationalObject.getStreamID().equals(input.getStreamID())) {
                        configIdOp = operationalObject.getConfigID();
                        streamIdOp = operationalObject.getStreamID();
                        idMatches = true;

                    }
                }
                if (!idMatches) {
                    return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
                            "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                                    "Invalid Stream id or The stream is not present in operational data store")));
                }

            }
        } else {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "Record is not present in operational data store")));
        }

    } catch (InterruptedException | ExecutionException e) {

        futureResult.set(RpcResultBuilder.<SetRuleOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;

    }
    final String confID = configIdOp;
    final String strmID = streamIdOp;
    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<StreamRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(final Optional<StreamRecord> streamRulesRecord)
                        throws Exception {

                    List<StreamList> streamRuleList = new ArrayList<StreamList>();
                    List<StreamList> updatedStreamRuleList = new ArrayList<StreamList>();

                    if (streamRulesRecord.isPresent()) {

                        streamRuleList = streamRulesRecord.get().getStreamList();
                        StreamList configObject = null;
                        Iterator<StreamList> iterator = streamRuleList.iterator();

                        while (iterator.hasNext()) {

                            configObject = iterator.next();
                            if (configObject.getConfigID().equalsIgnoreCase(confID)) {
                                StreamRulesBuilder streamRuleBuilder = new StreamRulesBuilder();
                                streamRuleBuilder.setField(input.getField());
                                streamRuleBuilder.setType(input.getType());
                                streamRuleBuilder.setValue(input.getValue());
                                streamRuleBuilder.setInverted(input.isInverted());
                                streamRuleBuilder.setStreamRuleID(streamRuleId);
                                SetRuleOutputBuilder setRuleOutputBuilder = new SetRuleOutputBuilder();
                                setRuleOutputBuilder.setField(input.getField());
                                setRuleOutputBuilder.setInverted(input.isInverted());
                                setRuleOutputBuilder.setType(input.getType());
                                setRuleOutputBuilder.setValue(input.getValue());
                                StreamRules streamrule = streamRuleBuilder.build();
                                configObject.getStreamRules().add(streamrule);
                                updatedStreamRuleList.add(buildStreamRule(configObject, strmID));
                                tx.merge(LogicalDatastoreType.CONFIGURATION, streamRecordId,
                                        new StreamRecordBuilder().setStreamList(updatedStreamRuleList).build());
                            }
                        }

                    }

                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<SetRuleOutput>success(setRuleOutputBuilder.build()).build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.debug("Failed to commit stream Rule", ex);

            futureResult.set(RpcResultBuilder.<SetRuleOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());

        }
    });

    return futureResult;
}

From source file:org.opendaylight.vpnservice.alivenessmonitor.internal.AlivenessMonitor.java

@Override
public Future<RpcResult<MonitorProfileCreateOutput>> monitorProfileCreate(
        final MonitorProfileCreateInput input) {
    LOG.debug("Monitor Profile Create operation - {}", input.getProfile());
    final SettableFuture<RpcResult<MonitorProfileCreateOutput>> result = SettableFuture.create();
    Profile profile = input.getProfile();
    final Long failureThreshold = profile.getFailureThreshold();
    final Long monitorInterval = profile.getMonitorInterval();
    final Long monitorWindow = profile.getMonitorWindow();
    final EtherTypes ethType = profile.getProtocolType();
    String idKey = getUniqueProfileKey(failureThreshold, monitorInterval, monitorWindow, ethType);
    final Long profileId = Long.valueOf(getUniqueId(idKey));

    final ReadWriteTransaction tx = broker.newReadWriteTransaction();
    ListenableFuture<Optional<MonitorProfile>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL,
            getMonitorProfileId(profileId));
    ListenableFuture<RpcResult<MonitorProfileCreateOutput>> resultFuture = Futures.transform(readFuture,
            new AsyncFunction<Optional<MonitorProfile>, RpcResult<MonitorProfileCreateOutput>>() {

                @Override/* w w w  .  ja  v a  2s . c  o  m*/
                public ListenableFuture<RpcResult<MonitorProfileCreateOutput>> apply(
                        Optional<MonitorProfile> optProfile) throws Exception {
                    if (optProfile.isPresent()) {
                        tx.cancel();
                        MonitorProfileCreateOutput output = new MonitorProfileCreateOutputBuilder()
                                .setProfileId(profileId).build();
                        String msg = String.format("Monitor profile %s already present for the given input",
                                input);
                        LOG.warn(msg);
                        result.set(RpcResultBuilder.success(output)
                                .withWarning(ErrorType.PROTOCOL, "profile-exists", msg).build());
                    } else {
                        final MonitorProfile monitorProfile = new MonitorProfileBuilder().setId(profileId)
                                .setFailureThreshold(failureThreshold).setMonitorInterval(monitorInterval)
                                .setMonitorWindow(monitorWindow).setProtocolType(ethType).build();
                        tx.put(LogicalDatastoreType.OPERATIONAL, getMonitorProfileId(profileId), monitorProfile,
                                CREATE_MISSING_PARENT);
                        Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
                            @Override
                            public void onFailure(Throwable error) {
                                String msg = String.format("Error when storing monitorprofile %s in datastore",
                                        monitorProfile);
                                LOG.error(msg, error);
                                result.set(RpcResultBuilder.<MonitorProfileCreateOutput>failed()
                                        .withError(ErrorType.APPLICATION, msg, error).build());
                            }

                            @Override
                            public void onSuccess(Void noarg) {
                                MonitorProfileCreateOutput output = new MonitorProfileCreateOutputBuilder()
                                        .setProfileId(profileId).build();
                                result.set(RpcResultBuilder.success(output).build());
                            }
                        });
                    }
                    return result;
                }
            }, callbackExecutorService);
    Futures.addCallback(resultFuture, new FutureCallback<RpcResult<MonitorProfileCreateOutput>>() {
        @Override
        public void onFailure(Throwable error) {
            //This would happen when any error happens during reading for monitoring profile
            String msg = String.format("Error in creating monitorprofile - %s", input);
            result.set(RpcResultBuilder.<MonitorProfileCreateOutput>failed()
                    .withError(ErrorType.APPLICATION, msg, error).build());
            LOG.error(msg, error);
        }

        @Override
        public void onSuccess(RpcResult<MonitorProfileCreateOutput> result) {
            LOG.debug("Successfully created monitor Profile {} ", input);
        }
    }, callbackExecutorService);
    return result;
}

From source file:org.opendaylight.centinel.impl.CentinelAlertConditionImpl.java

@Override
public Future<RpcResult<UpdateAlertFieldContentRuleOutput>> updateAlertFieldContentRule(
        final UpdateAlertFieldContentRuleInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<UpdateAlertFieldContentRuleOutput>> futureResult = SettableFuture.create();
    boolean idMatches = false;
    if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()
            || input.getRuleID() == null || input.getRuleID().isEmpty() || input.getRuleID().trim().isEmpty()) {
        LOG.debug("Invalid Parameters for UpdateAlertFieldContentRule");
        return Futures.immediateFailedCheckedFuture(
                new TransactionCommitFailedException("inalid-input", RpcResultBuilder.newError(
                        ErrorType.APPLICATION, "invalid-input", "StreamId and RuleId are mandatory fields")));
    }//from   w  w  w.j av a  2  s  . com
    final UpdateAlertFieldContentRuleOutputBuilder updateAlertFieldContentRuleOutputBuilder = new UpdateAlertFieldContentRuleOutputBuilder();
    updateAlertFieldContentRuleOutputBuilder.setFieldContentBacklog(input.getFieldContentBacklog());
    updateAlertFieldContentRuleOutputBuilder
            .setFieldContentCompareToValue(input.getFieldContentCompareToValue());
    updateAlertFieldContentRuleOutputBuilder.setFieldContentField(input.getFieldContentField());
    updateAlertFieldContentRuleOutputBuilder.setFieldContentGrace(input.getFieldContentGrace());
    updateAlertFieldContentRuleOutputBuilder.setRuleID(input.getRuleID());
    updateAlertFieldContentRuleOutputBuilder.setNodeType(input.getNodeType());
    updateAlertFieldContentRuleOutputBuilder.setRuleTypeClassifier(input.getRuleTypeClassifier());
    updateAlertFieldContentRuleOutputBuilder.setStreamID(input.getStreamID());
    updateAlertFieldContentRuleOutputBuilder.setTimeStamp(input.getTimeStamp());
    updateAlertFieldContentRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier());
    updateAlertFieldContentRuleOutputBuilder.setAlertName(input.getAlertName());

    ListenableFuture<Optional<AlertFieldContentRuleRecord>> readFutureOperational = tx
            .read(LogicalDatastoreType.OPERATIONAL, alertFeildContentRuleRecordId);

    ListenableFuture<Optional<AlertFieldContentRuleRecord>> readFutureConfigure = tx
            .read(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId);

    String configId = null;

    try {
        Optional<AlertFieldContentRuleRecord> record = readFutureOperational.get();
        if (record.isPresent()) {
            AlertFieldContentRuleRecord operationalRecord = readFutureOperational.get().get();
            List<StreamAlertFieldContentRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();

            if (!operationalRecord.getStreamAlertFieldContentRuleList().isEmpty()) {
                streamAlertRuleList = operationalRecord.getStreamAlertFieldContentRuleList();
                Iterator<StreamAlertFieldContentRuleList> itearator = streamAlertRuleList.iterator();
                StreamAlertFieldContentRuleList operationalObject = null;

                while (itearator.hasNext()) {
                    operationalObject = itearator.next();
                    if (operationalObject.getRuleID().equalsIgnoreCase(input.getRuleID())
                            && operationalObject.getStreamID().equalsIgnoreCase(input.getStreamID())) {
                        configId = operationalObject.getConfigID();
                        idMatches = true;

                    }
                }

                if (!idMatches) {
                    return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
                            "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                                    "Invalid Stream/Rule id or The stream/rule is not present in operational data store")));

                }

            }

        } else {
            return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input",
                    RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input",
                            "Record is not present in operational data store")));
        }

    } catch (InterruptedException | ExecutionException e) {
        futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;

    }
    final String configID = configId;
    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<AlertFieldContentRuleRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(
                        final Optional<AlertFieldContentRuleRecord> alertFieldContentRuleRecord)
                        throws Exception {

                    List<StreamAlertFieldContentRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();
                    List<StreamAlertFieldContentRuleList> updatedStreamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>();
                    if (alertFieldContentRuleRecord.isPresent()) {
                        streamAlertRuleList = alertFieldContentRuleRecord.get()
                                .getStreamAlertFieldContentRuleList();
                        StreamAlertFieldContentRuleList configObject = null;
                        Iterator<StreamAlertFieldContentRuleList> iterator = streamAlertRuleList.iterator();
                        while (iterator.hasNext()) {
                            configObject = iterator.next();

                            if (configObject.getConfigID().equalsIgnoreCase(configID)) {
                                updatedStreamAlertRuleList
                                        .add(buildUpdateAlertFieldContentRuleRecord(input, configObject));
                                tx.merge(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId,
                                        new AlertFieldContentRuleRecordBuilder()
                                                .setStreamAlertFieldContentRuleList(updatedStreamAlertRuleList)
                                                .build());

                            }

                        }

                    }

                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>success(
                    updateAlertFieldContentRuleOutputBuilder.build()).build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.info("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<UpdateAlertFieldContentRuleOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());

        }
    });

    return futureResult;
}

From source file:org.opendaylight.centinel.impl.CentinelImpl.java

/** 
 *    Update Alert Field Value Rule in configurational data store. 
 * /*from  ww w.ja  va  2 s  . co  m*/
 */

@Override
public Future<RpcResult<UpdateAlertFieldValueRuleOutput>> updateAlertFieldValueRule(
        final UpdateAlertFieldValueRuleInput input) {
    final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
    final SettableFuture<RpcResult<UpdateAlertFieldValueRuleOutput>> futureResult = SettableFuture.create();
    LOG.info("updateAlertFieldValueRuleOutput: " + input);
    final UpdateAlertFieldValueRuleOutputBuilder updateAlertFieldValueRuleOutputBuilder = new UpdateAlertFieldValueRuleOutputBuilder();
    updateAlertFieldValueRuleOutputBuilder.setFieldValueBacklog(input.getFieldValueBacklog());
    updateAlertFieldValueRuleOutputBuilder.setFieldValueField(input.getFieldValueField());
    updateAlertFieldValueRuleOutputBuilder.setFieldValueGrace(input.getFieldValueGrace());
    updateAlertFieldValueRuleOutputBuilder.setFieldValueThreshhold(input.getFieldValueThreshhold());
    updateAlertFieldValueRuleOutputBuilder.setFieldValueThreshholdType(input.getFieldValueThreshholdType());
    updateAlertFieldValueRuleOutputBuilder.setFieldValueThreshholdType(input.getFieldValueThreshholdType());
    updateAlertFieldValueRuleOutputBuilder.setRuleID(input.getRuleID());
    updateAlertFieldValueRuleOutputBuilder.setNodeType(input.getNodeType());
    updateAlertFieldValueRuleOutputBuilder.setRuleTypeClassifier(input.getRuleTypeClassifier());
    updateAlertFieldValueRuleOutputBuilder.setStreamID(input.getStreamID());
    updateAlertFieldValueRuleOutputBuilder.setTimeStamp(input.getTimeStamp());
    updateAlertFieldValueRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier());

    ListenableFuture<Optional<AlertFieldValueRuleRecord>> readFutureOperational = tx
            .read(LogicalDatastoreType.OPERATIONAL, alertFieldValueRuleRecordId);

    ListenableFuture<Optional<AlertFieldValueRuleRecord>> readFutureConfigure = tx
            .read(LogicalDatastoreType.CONFIGURATION, alertFieldValueRuleRecordId);

    String configId = null;

    try {
        AlertFieldValueRuleRecord operationalRecord = readFutureOperational.get().get();
        List<StreamAlertFieldValueRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldValueRuleList>();

        if (!operationalRecord.getStreamAlertFieldValueRuleList().isEmpty()) {
            streamAlertRuleList = operationalRecord.getStreamAlertFieldValueRuleList();
            Iterator<StreamAlertFieldValueRuleList> itearator = streamAlertRuleList.iterator();
            StreamAlertFieldValueRuleList operationalObject = null;

            while (itearator.hasNext()) {
                operationalObject = itearator.next();
                if (operationalObject.getRuleID().equalsIgnoreCase(input.getRuleID())
                        && operationalObject.getStreamID().equalsIgnoreCase(input.getStreamID())) {
                    configId = operationalObject.getConfigID();

                }
            }

        }

    } catch (InterruptedException | ExecutionException e) {
        futureResult.set(RpcResultBuilder.<UpdateAlertFieldValueRuleOutput>failed()
                .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build());
        return futureResult;

    }
    final String configID = configId;
    final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure,
            new AsyncFunction<Optional<AlertFieldValueRuleRecord>, Void>() {

                @Override
                public ListenableFuture<Void> apply(
                        final Optional<AlertFieldValueRuleRecord> alertFieldValueRuleRecord) throws Exception {

                    List<StreamAlertFieldValueRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldValueRuleList>();
                    List<StreamAlertFieldValueRuleList> updatedStreamAlertRuleList = new ArrayList<StreamAlertFieldValueRuleList>();
                    if (alertFieldValueRuleRecord.isPresent()) {
                        streamAlertRuleList = alertFieldValueRuleRecord.get()
                                .getStreamAlertFieldValueRuleList();
                        StreamAlertFieldValueRuleList configObject = null;
                        Iterator<StreamAlertFieldValueRuleList> iterator = streamAlertRuleList.iterator();
                        while (iterator.hasNext()) {
                            configObject = iterator.next();

                            if (configObject.getConfigID().equalsIgnoreCase(configID)) {
                                updatedStreamAlertRuleList
                                        .add(buildUpdateAlertFieldValueRuleRecord(input, configObject));

                                tx.merge(LogicalDatastoreType.CONFIGURATION, alertFieldValueRuleRecordId,
                                        new AlertFieldValueRuleRecordBuilder()
                                                .setStreamAlertFieldValueRuleList(updatedStreamAlertRuleList)
                                                .build());

                            }
                        }

                    }

                    return tx.submit();
                }

            });
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {

            futureResult.set(RpcResultBuilder
                    .<UpdateAlertFieldValueRuleOutput>success(updateAlertFieldValueRuleOutputBuilder.build())
                    .build());
        }

        @Override
        public void onFailure(final Throwable ex) {

            LOG.debug("Failed to commit Rule", ex);

            futureResult.set(RpcResultBuilder.<UpdateAlertFieldValueRuleOutput>failed()
                    .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build());

        }
    });

    return futureResult;
}