Example usage for com.google.common.util.concurrent Futures allAsList

List of usage examples for com.google.common.util.concurrent Futures allAsList

Introduction

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

Prototype

@Beta
@CheckReturnValue
public static <V> ListenableFuture<List<V>> allAsList(
        Iterable<? extends ListenableFuture<? extends V>> futures) 

Source Link

Document

Creates a new ListenableFuture whose value is a list containing the values of all its input futures, if all succeed.

Usage

From source file:org.hawkular.alerts.engine.impl.CassAlertsServiceImpl.java

@Override
public int deleteAlerts(String tenantId, AlertsCriteria criteria) throws Exception {
    if (isEmpty(tenantId)) {
        throw new IllegalArgumentException("TenantId must be not null");
    }//from   w w w  .jav a  2  s.c  o  m
    if (null == criteria) {
        throw new IllegalArgumentException("Criteria must be not null");
    }

    // no need to fetch the evalSets to perform the necessary deletes
    criteria.setThin(true);
    List<Alert> alertsToDelete = getAlerts(tenantId, criteria, null);

    if (alertsToDelete.isEmpty()) {
        return 0;
    }
    PreparedStatement deleteAlert = CassStatement.get(session, CassStatement.DELETE_ALERT);
    PreparedStatement deleteAlertCtime = CassStatement.get(session, CassStatement.DELETE_ALERT_CTIME);
    PreparedStatement deleteAlertTrigger = CassStatement.get(session, CassStatement.DELETE_ALERT_TRIGGER);
    PreparedStatement deleteAlertLifecycle = CassStatement.get(session, CassStatement.DELETE_ALERT_LIFECYCLE);
    PreparedStatement deleteAlertStime = CassStatement.get(session, CassStatement.DELETE_ALERT_STIME);
    if (deleteAlert == null || deleteAlertCtime == null || deleteAlertTrigger == null
            || deleteAlertLifecycle == null) {
        throw new RuntimeException("delete*Alerts PreparedStatement is null");
    }

    List<ResultSetFuture> futures = new ArrayList<>();
    int i = 0;
    BatchStatement batch = new BatchStatement(batchType);
    for (Alert a : alertsToDelete) {
        String id = a.getAlertId();
        batch.add(deleteAlert.bind(tenantId, id));
        batch.add(deleteAlertCtime.bind(tenantId, a.getCtime(), id));
        batch.add(deleteAlertTrigger.bind(tenantId, a.getTriggerId(), id));
        a.getLifecycle().stream().forEach(l -> {
            batch.add(deleteAlertLifecycle.bind(tenantId, l.getStatus().name(), l.getStime(), a.getAlertId()));
            batch.add(deleteAlertStime.bind(tenantId, l.getStime(), a.getAlertId()));
        });
        i += batch.size();
        if (i > batchSize) {
            futures.add(session.executeAsync(batch));
            batch.clear();
            i = 0;
        }
    }
    if (batch.size() > 0) {
        futures.add(session.executeAsync(batch));
    }
    Futures.allAsList(futures).get();

    return alertsToDelete.size();
}

From source file:org.hawkular.alerts.engine.impl.CassAlertsServiceImpl.java

@Override
public int deleteEvents(String tenantId, EventsCriteria criteria) throws Exception {
    if (isEmpty(tenantId)) {
        throw new IllegalArgumentException("TenantId must be not null");
    }/*from  w w w .j a v a 2 s.  com*/
    if (null == criteria) {
        throw new IllegalArgumentException("Criteria must be not null");
    }

    // no need to fetch the evalSets to perform the necessary deletes
    criteria.setThin(true);
    List<Event> eventsToDelete = getEvents(tenantId, criteria, null);

    if (eventsToDelete.isEmpty()) {
        return 0;
    }

    PreparedStatement deleteEvent = CassStatement.get(session, CassStatement.DELETE_EVENT);
    PreparedStatement deleteEventCategory = CassStatement.get(session, CassStatement.DELETE_EVENT_CATEGORY);
    PreparedStatement deleteEventCTime = CassStatement.get(session, CassStatement.DELETE_EVENT_CTIME);
    PreparedStatement deleteEventTrigger = CassStatement.get(session, CassStatement.DELETE_EVENT_TRIGGER);
    if (deleteEvent == null || deleteEventCTime == null || deleteEventCategory == null
            || deleteEventTrigger == null) {
        throw new RuntimeException("delete*Events PreparedStatement is null");
    }

    List<ResultSetFuture> futures = new ArrayList<>();
    int i = 0;
    BatchStatement batch = new BatchStatement(batchType);
    for (Event e : eventsToDelete) {
        String id = e.getId();
        batch.add(deleteEvent.bind(tenantId, id));
        batch.add(deleteEventCategory.bind(tenantId, e.getCategory(), id));
        batch.add(deleteEventCTime.bind(tenantId, e.getCtime(), id));
        if (null != e.getTrigger()) {
            batch.add(deleteEventTrigger.bind(tenantId, e.getTrigger().getId(), id));
        }
        i += batch.size();
        if (i > batchSize) {
            futures.add(session.executeAsync(batch));
            batch.clear();
            i = 0;
        }
    }
    if (batch.size() > 0) {
        futures.add(session.executeAsync(batch));
    }
    Futures.allAsList(futures).get();

    return eventsToDelete.size();
}

From source file:org.hawkular.alerts.engine.impl.CassAlertsServiceImpl.java

private Alert updateAlertStatus(Alert alert) throws Exception {
    if (alert == null || alert.getAlertId() == null || alert.getAlertId().isEmpty()) {
        throw new IllegalArgumentException("AlertId must be not null");
    }/*www . j  a v  a 2s  . c o m*/
    try {
        PreparedStatement insertAlertLifecycle = CassStatement.get(session,
                CassStatement.INSERT_ALERT_LIFECYCLE);
        PreparedStatement insertAlertStime = CassStatement.get(session, CassStatement.INSERT_ALERT_STIME);
        PreparedStatement updateAlert = CassStatement.get(session, CassStatement.UPDATE_ALERT);

        List<ResultSetFuture> futures = new ArrayList<>();
        Alert.LifeCycle lifecycle = alert.getCurrentLifecycle();
        if (lifecycle != null) {
            futures.add(session.executeAsync(insertAlertLifecycle.bind(alert.getTenantId(), alert.getAlertId(),
                    lifecycle.getStatus().name(), lifecycle.getStime())));
            futures.add(session.executeAsync(
                    insertAlertStime.bind(alert.getTenantId(), alert.getAlertId(), lifecycle.getStime())));
        }
        futures.add(session.executeAsync(
                updateAlert.bind(JsonUtil.toJson(alert), alert.getTenantId(), alert.getAlertId())));

        Futures.allAsList(futures).get();

    } catch (Exception e) {
        msgLog.errorDatabaseException(e.getMessage());
        throw e;
    }
    return alert;
}

From source file:org.apache.qpid.server.virtualhost.AbstractVirtualHost.java

@StateTransition(currentState = { State.STOPPED }, desiredState = State.ACTIVE)
private ListenableFuture<Void> onRestart() {
    resetStatistics();/*from  ww  w  . j av a 2  s  .c  om*/
    createHousekeepingExecutor();

    final List<ConfiguredObjectRecord> records = new ArrayList<>();

    // Transitioning to STOPPED will have closed all our children.  Now we are transition
    // back to ACTIVE, we need to recover and re-open them.

    getDurableConfigurationStore().reload(new ConfiguredObjectRecordHandler() {

        @Override
        public void handle(final ConfiguredObjectRecord record) {
            records.add(record);
        }

    });

    new GenericRecoverer(this).recover(records, false);

    final List<ListenableFuture<Void>> childOpenFutures = new ArrayList<>();

    Subject.doAs(getSubjectWithAddedSystemRights(), new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            applyToChildren(new Action<ConfiguredObject<?>>() {
                @Override
                public void performAction(final ConfiguredObject<?> child) {
                    final ListenableFuture<Void> childOpenFuture = child.openAsync();
                    childOpenFutures.add(childOpenFuture);

                    addFutureCallback(childOpenFuture, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(final Void result) {
                        }

                        @Override
                        public void onFailure(final Throwable t) {
                            _logger.error("Exception occurred while opening {} : {}",
                                    child.getClass().getSimpleName(), child.getName(), t);
                        }

                    }, getTaskExecutor());
                }
            });
            return null;
        }
    });

    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(childOpenFutures);
    return Futures.transform(combinedFuture, new AsyncFunction<List<Void>, Void>() {
        @Override
        public ListenableFuture<Void> apply(final List<Void> input) throws Exception {
            return onActivate();
        }
    });
}

From source file:org.glowroot.central.repo.AggregateDaoImpl.java

private ListenableFuture<?> insertQueries(List<MutableQuery> queries, int rollupLevel, String agentRollupId,
        String transactionType, @Nullable String transactionName, long captureTime, TTL adjustedTTL)
        throws Exception {
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (MutableQuery query : queries) {
        BoundStatement boundStatement;/*from  w w w .j a v  a 2 s .  c o  m*/
        if (transactionName == null) {
            boundStatement = getInsertOverallPS(queryTable, rollupLevel).bind();
        } else {
            boundStatement = getInsertTransactionPS(queryTable, rollupLevel).bind();
        }
        String fullTextSha1 = query.getFullTextSha1();
        int i = 0;
        boundStatement.setString(i++, agentRollupId);
        boundStatement.setString(i++, transactionType);
        if (transactionName != null) {
            boundStatement.setString(i++, transactionName);
        }
        boundStatement.setTimestamp(i++, new Date(captureTime));
        boundStatement.setString(i++, query.getType());
        boundStatement.setString(i++, query.getTruncatedText());
        // full_query_text_sha1 cannot be null since it is used in clustering key
        boundStatement.setString(i++, Strings.nullToEmpty(fullTextSha1));
        boundStatement.setDouble(i++, query.getTotalDurationNanos());
        boundStatement.setLong(i++, query.getExecutionCount());
        if (query.hasTotalRows()) {
            boundStatement.setLong(i++, query.getTotalRows());
        } else {
            boundStatement.setToNull(i++);
        }
        boundStatement.setInt(i++, adjustedTTL.queryTTL());
        futures.add(session.writeAsync(boundStatement));
    }
    return Futures.allAsList(futures);
}

From source file:org.glowroot.central.repo.AggregateDaoImpl.java

private ListenableFuture<?> insertServiceCalls(List<MutableServiceCall> serviceCalls, int rollupLevel,
        String agentRollupId, String transactionType, @Nullable String transactionName, long captureTime,
        TTL adjustedTTL) throws Exception {
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (MutableServiceCall serviceCall : serviceCalls) {
        BoundStatement boundStatement;// w w  w.  jav a  2 s. c  om
        if (transactionName == null) {
            boundStatement = getInsertOverallPS(serviceCallTable, rollupLevel).bind();
        } else {
            boundStatement = getInsertTransactionPS(serviceCallTable, rollupLevel).bind();
        }
        int i = 0;
        boundStatement.setString(i++, agentRollupId);
        boundStatement.setString(i++, transactionType);
        if (transactionName != null) {
            boundStatement.setString(i++, transactionName);
        }
        boundStatement.setTimestamp(i++, new Date(captureTime));
        boundStatement.setString(i++, serviceCall.getType());
        boundStatement.setString(i++, serviceCall.getText());
        boundStatement.setDouble(i++, serviceCall.getTotalDurationNanos());
        boundStatement.setLong(i++, serviceCall.getExecutionCount());
        boundStatement.setInt(i++, adjustedTTL.serviceCallTTL());
        futures.add(session.writeAsync(boundStatement));
    }
    return Futures.allAsList(futures);
}

From source file:org.hawkular.alerts.engine.impl.CassDefinitionsServiceImpl.java

@Override
public Collection<Condition> setConditions(String tenantId, String triggerId, Mode triggerMode,
        Collection<Condition> conditions) throws Exception {
    if (isEmpty(tenantId)) {
        throw new IllegalArgumentException("TenantId must be not null");
    }/*from  ww  w .j a v  a  2s .c  om*/
    if (isEmpty(triggerId)) {
        throw new IllegalArgumentException("TriggerId must be not null");
    }
    if (triggerMode == null) {
        throw new IllegalArgumentException("TriggerMode must be not null");
    }
    if (conditions == null) {
        throw new IllegalArgumentException("Conditions must be not null");
    }
    PreparedStatement insertConditionAvailability = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_AVAILABILITY);
    PreparedStatement insertConditionCompare = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_COMPARE);
    PreparedStatement insertConditionEvent = CassStatement.get(session, CassStatement.INSERT_CONDITION_EVENT);
    PreparedStatement insertConditionExternal = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_EXTERNAL);
    PreparedStatement insertConditionMissing = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_MISSING);
    PreparedStatement insertConditionNelson = CassStatement.get(session, CassStatement.INSERT_CONDITION_NELSON);
    PreparedStatement insertConditionRate = CassStatement.get(session, CassStatement.INSERT_CONDITION_RATE);
    PreparedStatement insertConditionString = CassStatement.get(session, CassStatement.INSERT_CONDITION_STRING);
    PreparedStatement insertConditionThreshold = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_THRESHOLD);
    PreparedStatement insertConditionThresholdRange = CassStatement.get(session,
            CassStatement.INSERT_CONDITION_THRESHOLD_RANGE);
    if (insertConditionAvailability == null || insertConditionCompare == null || insertConditionEvent == null
            || insertConditionExternal == null || insertConditionMissing == null || insertConditionRate == null
            || insertConditionString == null || insertConditionThreshold == null
            || insertConditionThresholdRange == null) {
        throw new RuntimeException("insert*Condition PreparedStatement is null");
    }
    // Get rid of the prior condition set
    removeConditions(tenantId, triggerId, triggerMode);

    Set<String> dataIds = new HashSet<>();
    // Now add the new condition set
    try {
        List<ResultSetFuture> futures = new ArrayList<>();
        BatchStatement batch = new BatchStatement(batchType);
        int i = 0;
        int indexCondition = 0;
        for (Condition cond : conditions) {
            cond.setTenantId(tenantId);
            cond.setTriggerId(triggerId);
            cond.setTriggerMode(triggerMode);
            cond.setConditionSetSize(conditions.size());
            cond.setConditionSetIndex(++indexCondition);

            switch (cond.getType()) {
            case AVAILABILITY:
                AvailabilityCondition aCond = (AvailabilityCondition) cond;
                batch.add(insertConditionAvailability.bind(aCond.getTenantId(), aCond.getTriggerId(),
                        aCond.getTriggerMode().name(), aCond.getContext(), aCond.getConditionSetSize(),
                        aCond.getConditionSetIndex(), aCond.getConditionId(), aCond.getDataId(),
                        aCond.getOperator().name()));
                dataIds.add(aCond.getDataId());
                break;
            case COMPARE:
                CompareCondition cCond = (CompareCondition) cond;
                batch.add(insertConditionCompare.bind(cCond.getTenantId(), cCond.getTriggerId(),
                        cCond.getTriggerMode().name(), cCond.getContext(), cCond.getConditionSetSize(),
                        cCond.getConditionSetIndex(), cCond.getConditionId(), cCond.getDataId(),
                        cCond.getOperator().name(), cCond.getData2Id(), cCond.getData2Multiplier()));
                dataIds.add(cCond.getDataId());
                dataIds.add(cCond.getData2Id());
                break;
            case EVENT:
                EventCondition evCond = (EventCondition) cond;
                batch.add(insertConditionEvent.bind(evCond.getTenantId(), evCond.getTriggerId(),
                        evCond.getTriggerMode().name(), evCond.getContext(), evCond.getConditionSetSize(),
                        evCond.getConditionSetIndex(), evCond.getConditionId(), evCond.getDataId(),
                        evCond.getExpression()));
                dataIds.add(evCond.getDataId());
                break;
            case EXTERNAL:
                ExternalCondition eCond = (ExternalCondition) cond;
                batch.add(insertConditionExternal.bind(eCond.getTenantId(), eCond.getTriggerId(),
                        eCond.getTriggerMode().name(), eCond.getContext(), eCond.getConditionSetSize(),
                        eCond.getConditionSetIndex(), eCond.getConditionId(), eCond.getDataId(),
                        eCond.getAlerterId(), eCond.getExpression()));
                dataIds.add(eCond.getDataId());
                break;
            case MISSING:
                MissingCondition mCond = (MissingCondition) cond;
                batch.add(insertConditionMissing.bind(mCond.getTenantId(), mCond.getTriggerId(),
                        mCond.getTriggerMode().name(), mCond.getContext(), mCond.getConditionSetSize(),
                        mCond.getConditionSetIndex(), mCond.getConditionId(), mCond.getDataId(),
                        mCond.getInterval()));
                dataIds.add(mCond.getDataId());
                break;
            case NELSON:
                NelsonCondition nCond = (NelsonCondition) cond;
                batch.add(insertConditionNelson.bind(nCond.getTenantId(), nCond.getTriggerId(),
                        nCond.getTriggerMode().name(), nCond.getContext(), nCond.getConditionSetSize(),
                        nCond.getConditionSetIndex(), nCond.getConditionId(), nCond.getDataId(),
                        nCond.getActiveRules().stream().map(e -> e.name()).collect(Collectors.toSet()),
                        nCond.getSampleSize()));
                dataIds.add(nCond.getDataId());
                break;
            case RANGE:
                ThresholdRangeCondition rCond = (ThresholdRangeCondition) cond;
                batch.add(insertConditionThresholdRange.bind(rCond.getTenantId(), rCond.getTriggerId(),
                        rCond.getTriggerMode().name(), rCond.getContext(), rCond.getConditionSetSize(),
                        rCond.getConditionSetIndex(), rCond.getConditionId(), rCond.getDataId(),
                        rCond.getOperatorLow().name(), rCond.getOperatorHigh().name(), rCond.getThresholdLow(),
                        rCond.getThresholdHigh(), rCond.isInRange()));
                dataIds.add(rCond.getDataId());
                break;
            case RATE:
                RateCondition rateCond = (RateCondition) cond;
                batch.add(insertConditionRate.bind(rateCond.getTenantId(), rateCond.getTriggerId(),
                        rateCond.getTriggerMode().name(), rateCond.getContext(), rateCond.getConditionSetSize(),
                        rateCond.getConditionSetIndex(), rateCond.getConditionId(), rateCond.getDataId(),
                        rateCond.getDirection().name(), rateCond.getPeriod().name(),
                        rateCond.getOperator().name(), rateCond.getThreshold()));
                dataIds.add(rateCond.getDataId());
                break;
            case STRING:
                StringCondition sCond = (StringCondition) cond;
                batch.add(insertConditionString.bind(sCond.getTenantId(), sCond.getTriggerId(),
                        sCond.getTriggerMode().name(), sCond.getContext(), sCond.getConditionSetSize(),
                        sCond.getConditionSetIndex(), sCond.getConditionId(), sCond.getDataId(),
                        sCond.getOperator().name(), sCond.getPattern(), sCond.isIgnoreCase()));
                dataIds.add(sCond.getDataId());
                break;
            case THRESHOLD:
                ThresholdCondition tCond = (ThresholdCondition) cond;
                batch.add(insertConditionThreshold.bind(tCond.getTenantId(), tCond.getTriggerId(),
                        tCond.getTriggerMode().name(), tCond.getContext(), tCond.getConditionSetSize(),
                        tCond.getConditionSetIndex(), tCond.getConditionId(), tCond.getDataId(),
                        tCond.getOperator().name(), tCond.getThreshold()));
                dataIds.add(tCond.getDataId());
                break;
            default:
                throw new IllegalArgumentException("Unexpected ConditionType: " + cond);
            }
            i += batch.size();
            if (i > batchSize) {
                futures.add(session.executeAsync(batch));
                batch.clear();
                i = 0;
            }
        }
        if (batch.size() > 0) {
            futures.add(session.executeAsync(batch));
        }
        Futures.allAsList(futures).get();

    } catch (Exception e) {
        msgLog.errorDatabaseException(e.getMessage());
        throw e;
    }

    if (alertsEngine != null) {
        alertsEngine.reloadTrigger(tenantId, triggerId);
    }

    notifyListeners(new DefinitionsEvent(Type.TRIGGER_CONDITION_CHANGE, tenantId, triggerId, dataIds));

    return conditions;
}

From source file:org.opendaylight.netvirt.fibmanager.VrfEntryListener.java

public void populateFibOnNewDpn(final BigInteger dpnId, final long vpnId, final String rd,
        final FutureCallback<List<Void>> callback) {
    LOG.trace("New dpn {} for vpn {} : populateFibOnNewDpn", dpnId, rd);
    InstanceIdentifier<VrfTables> id = buildVrfId(rd);
    final VpnInstanceOpDataEntry vpnInstance = getVpnInstance(rd);
    final Optional<VrfTables> vrfTable = FibUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, id);
    if (!vrfTable.isPresent()) {
        LOG.warn("VRF Table not yet available for RD {}", rd);
        if (callback != null) {
            List<ListenableFuture<Void>> futures = new ArrayList<>();
            ListenableFuture<List<Void>> listenableFuture = Futures.allAsList(futures);
            Futures.addCallback(listenableFuture, callback);
        }//from  ww  w  .  j  ava2  s. c  o m
        return;
    }
    DataStoreJobCoordinator dataStoreCoordinator = DataStoreJobCoordinator.getInstance();
    dataStoreCoordinator.enqueueJob("FIB-" + vpnId + "-" + dpnId.toString(), () -> {
        List<ListenableFuture<Void>> futures = new ArrayList<>();
        synchronized (vpnInstance.getVpnInstanceName().intern()) {
            WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
            for (final VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
                SubnetRoute subnetRoute = vrfEntry.getAugmentation(SubnetRoute.class);
                if (subnetRoute != null) {
                    long elanTag = subnetRoute.getElantag();
                    installSubnetRouteInFib(dpnId, elanTag, rd, vpnId, vrfEntry, tx);
                    continue;
                }
                RouterInterface routerInt = vrfEntry.getAugmentation(RouterInterface.class);
                if (routerInt != null) {
                    LOG.trace("Router augmented vrfentry found rd:{}, uuid:{}, ip:{}, mac:{}", rd,
                            routerInt.getUuid(), routerInt.getIpAddress(), routerInt.getMacAddress());
                    installRouterFibEntry(vrfEntry, dpnId, vpnId, routerInt.getUuid(), routerInt.getIpAddress(),
                            new MacAddress(routerInt.getMacAddress()), NwConstants.ADD_FLOW);
                    continue;
                }
                //Handle local flow creation for imports
                if (RouteOrigin.value(vrfEntry.getOrigin()) == RouteOrigin.SELF_IMPORTED) {
                    java.util.Optional<Long> optionalLabel = FibUtil.getLabelFromRoutePaths(vrfEntry);
                    if (optionalLabel.isPresent()) {
                        List<String> nextHopList = FibUtil.getNextHopListFromRoutePaths(vrfEntry);
                        LabelRouteInfo lri = getLabelRouteInfo(optionalLabel.get());
                        if (isPrefixAndNextHopPresentInLri(vrfEntry.getDestPrefix(), nextHopList, lri)) {
                            if (lri.getDpnId().equals(dpnId)) {
                                createLocalFibEntry(vpnId, rd, vrfEntry);
                                continue;
                            }
                        }
                    }
                }

                boolean shouldCreateRemoteFibEntry = shouldCreateFibEntryForVrfAndVpnIdOnDpn(vpnId, vrfEntry,
                        dpnId);
                if (shouldCreateRemoteFibEntry) {
                    LOG.trace("Will create remote FIB entry for vrfEntry {} on DPN {}", vrfEntry, dpnId);
                    createRemoteFibEntry(dpnId, vpnId, vrfTable.get().getKey(), vrfEntry, tx);
                }
            }
            //TODO: if we have 100K entries in FIB, can it fit in one Tranasaction (?)
            futures.add(tx.submit());
        }
        if (callback != null) {
            ListenableFuture<List<Void>> listenableFuture = Futures.allAsList(futures);
            Futures.addCallback(listenableFuture, callback);
        }
        return futures;
    });
}

From source file:org.hawkular.alerts.engine.impl.CassDefinitionsServiceImpl.java

private void insertTags(String tenantId, TagType type, String id, Map<String, String> tags) throws Exception {
    if (isEmpty(tags)) {
        return;//w ww . j  a v a  2s .  co m
    }
    PreparedStatement insertTag = CassStatement.get(session, CassStatement.INSERT_TAG);
    if (insertTag == null) {
        throw new RuntimeException("insertTag PreparedStatement is null");
    }

    List<ResultSetFuture> futures = new ArrayList<>(tags.size());
    BatchStatement batch = new BatchStatement(batchType);
    int i = 0;
    for (Entry<String, String> tag : tags.entrySet()) {
        batch.add(insertTag.bind(tenantId, type.name(), tag.getKey(), tag.getValue(), id));
        i += batch.size();
        if (i > batchSize) {
            futures.add(session.executeAsync(batch));
            batch.clear();
            i = 0;
        }
    }
    if (batch.size() > 0) {
        futures.add(session.executeAsync(batch));
    }
    Futures.allAsList(futures).get();
}

From source file:org.hawkular.alerts.engine.impl.CassDefinitionsServiceImpl.java

private void deleteTags(String tenantId, TagType type, String id, Map<String, String> tags) throws Exception {
    if (isEmpty(tags)) {
        return;//from  www . j  a va2  s .  c o m
    }

    PreparedStatement deleteTag = CassStatement.get(session, CassStatement.DELETE_TAG);

    List<ResultSetFuture> futures = new ArrayList<>(tags.size());
    BatchStatement batch = new BatchStatement(batchType);
    int i = 0;
    for (Entry<String, String> tag : tags.entrySet()) {
        batch.add(deleteTag.bind(tenantId, type.name(), tag.getKey(), tag.getValue(), id));
        i += batch.size();
        if (i > batchSize) {
            futures.add(session.executeAsync(batch));
            batch.clear();
            i = 0;
        }
    }
    if (batch.size() > 0) {
        futures.add(session.executeAsync(batch));
    }
    Futures.allAsList(futures).get();
}