Example usage for com.google.common.collect Maps transformValues

List of usage examples for com.google.common.collect Maps transformValues

Introduction

In this page you can find the example usage for com.google.common.collect Maps transformValues.

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:com.twitter.aurora.scheduler.state.CronJobManager.java

/**
 * Triggers execution of a cron job, depending on the cron collision policy for the job.
 *
 * @param config The config of the job to be triggered.
 *///from   w ww . jav a 2  s . c o m
@VisibleForTesting
void cronTriggered(SanitizedConfiguration config) {
    IJobConfiguration job = config.getJobConfig();
    LOG.info(String.format("Cron triggered for %s at %s with policy %s", JobKeys.toPath(job), new Date(),
            job.getCronCollisionPolicy()));
    cronJobsTriggered.incrementAndGet();

    ImmutableMap.Builder<Integer, ITaskConfig> builder = ImmutableMap.builder();
    final Query.Builder activeQuery = Query.jobScoped(job.getKey()).active();
    Set<IScheduledTask> activeTasks = Storage.Util.consistentFetchTasks(storage, activeQuery);

    if (activeTasks.isEmpty()) {
        builder.putAll(config.getTaskConfigs());
    } else {
        // Assign a default collision policy.
        CronCollisionPolicy collisionPolicy = orDefault(job.getCronCollisionPolicy());

        switch (collisionPolicy) {
        case KILL_EXISTING:
            try {
                schedulerCore.killTasks(activeQuery, CRON_USER);
                // Check immediately if the tasks are gone.  This could happen if the existing tasks
                // were pending.
                if (!hasTasks(activeQuery)) {
                    builder.putAll(config.getTaskConfigs());
                } else {
                    delayedRun(activeQuery, config);
                }
            } catch (ScheduleException e) {
                LOG.log(Level.SEVERE, "Failed to kill job.", e);
            }
            break;

        case CANCEL_NEW:
            break;

        case RUN_OVERLAP:
            Map<Integer, IScheduledTask> byInstance = Maps.uniqueIndex(activeTasks,
                    Tasks.SCHEDULED_TO_INSTANCE_ID);
            Map<Integer, ScheduleStatus> existingTasks = Maps.transformValues(byInstance, Tasks.GET_STATUS);
            if (existingTasks.isEmpty()) {
                builder.putAll(config.getTaskConfigs());
            } else if (Iterables.any(existingTasks.values(), Predicates.equalTo(PENDING))) {
                LOG.info("Job " + JobKeys.toPath(job) + " has pending tasks, suppressing run.");
            } else {
                // To safely overlap this run, we need to adjust the instance IDs of the overlapping
                // run (maintaining the role/job/instance UUID invariant).
                int instanceOffset = Ordering.natural().max(existingTasks.keySet()) + 1;
                LOG.info("Adjusting instance IDs of " + JobKeys.toPath(job) + " by " + instanceOffset
                        + " for overlapping cron run.");
                for (Map.Entry<Integer, ITaskConfig> entry : config.getTaskConfigs().entrySet()) {
                    builder.put(entry.getKey() + instanceOffset, entry.getValue());
                }
            }
            break;

        default:
            LOG.severe("Unrecognized cron collision policy: " + job.getCronCollisionPolicy());
        }
    }

    Map<Integer, ITaskConfig> newTasks = builder.build();
    if (!newTasks.isEmpty()) {
        stateManager.insertPendingTasks(newTasks);
    }
}

From source file:io.mindmaps.graql.internal.query.VarImpl.java

@Override
public Map<VarAdmin, Set<ValuePredicateAdmin>> getResourcePredicates() {
    // The type of the resource is guaranteed to exist
    //noinspection OptionalGetWithoutIsPresent
    Function<VarAdmin, VarAdmin> type = v -> v.getType().get();

    Function<VarAdmin, Stream<ValuePredicateAdmin>> predicates = resource -> resource.getValuePredicates()
            .stream();/*from w  w  w. jav  a 2 s. c om*/

    Map<VarAdmin, List<VarAdmin>> groupedByType = resources.stream().collect(groupingBy(type));

    return Maps.transformValues(groupedByType, vars -> vars.stream().flatMap(predicates).collect(toSet()));
}

From source file:ninja.leaping.permissionsex.backend.memory.MemorySubjectData.java

@Override
public ImmutableSubjectData clearParents() {
    if (this.contexts.isEmpty()) {
        return this;
    }//from ww w.ja va2 s.  c  om

    Map<Set<Entry<String, String>>, DataEntry> newValue = Maps.transformValues(this.contexts,
            dataEntry -> dataEntry == null ? null : dataEntry.withoutParents());
    return newData(newValue);
}

From source file:org.eclipse.sw360.datahandler.common.SW360Utils.java

public static String fieldValueAsString(Object fieldValue) throws SW360Exception {
    if (fieldValue == null) {
        return "";
    }/* w  w  w  .  j a va 2s .com*/
    if (fieldValue instanceof TEnum) {
        return nullToEmpty(ThriftEnumUtils.enumToString((TEnum) fieldValue));
    }
    if (fieldValue instanceof String) {
        return nullToEmpty((String) fieldValue);
    }
    if (fieldValue instanceof Map) {
        Map<String, Object> originalMap = nullToEmptyMap(((Map<String, Object>) fieldValue));
        // cannot use CommonUtils.nullToEmptyString here, because it calls toString() on non-null objects,
        // which destroys the chance for ObjectMapper to serialize values according to its configuration
        Map<String, Object> map = Maps.transformValues(originalMap, v -> v == null ? "" : v);
        return serializeToJson(map);
    }
    if (fieldValue instanceof Iterable) {
        return serializeToJson(fieldValue);
    }
    return fieldValue.toString();
}

From source file:io.fluo.api.types.TypedSnapshotBase.java

@SuppressWarnings({ "unchecked" })
private Map<Column, Value> wrap(Map<Column, Bytes> map) {
    Map<Column, Value> ret = Maps.transformValues(map, new Function<Bytes, Value>() {
        @Override// ww w. ja  v  a  2s.  com
        public Value apply(Bytes input) {
            return new Value(input);
        }
    });

    return Collections.unmodifiableMap(DefaultedMap.decorate(ret, new Value((Bytes) null)));
}

From source file:io.atomix.core.map.impl.PartitionedAtomicMapProxy.java

@Override
public CompletableFuture<Boolean> prepare(TransactionLog<MapUpdate<K, byte[]>> transactionLog) {
    Map<PartitionId, List<MapUpdate<K, byte[]>>> updatesGroupedByMap = Maps.newIdentityHashMap();
    transactionLog.records().forEach(update -> {
        updatesGroupedByMap.computeIfAbsent(getProxyClient().getPartitionId(update.key().toString()),
                k -> Lists.newLinkedList()).add(update);
    });/*  www. j  ava  2 s.  c om*/
    Map<PartitionId, TransactionLog<MapUpdate<K, byte[]>>> transactionsByMap = Maps.transformValues(
            updatesGroupedByMap,
            list -> new TransactionLog<>(transactionLog.transactionId(), transactionLog.version(), list));

    return Futures
            .allOf(transactionsByMap.entrySet().stream()
                    .map(e -> getProxyClient().applyOn(e.getKey(), service -> service.prepare(e.getValue()))
                            .thenApply(v -> v == PrepareResult.OK || v == PrepareResult.PARTIAL_FAILURE))
                    .collect(Collectors.toList()))
            .thenApply(list -> list.stream().reduce(Boolean::logicalAnd).orElse(true));
}

From source file:com.b2international.snowowl.snomed.datastore.request.DescriptionRequestHelper.java

private static <T> Map<String, SnomedDescription> extractBest(
        Multimap<String, SnomedDescription> descriptionsByConceptId, List<T> orderedValues,
        Function<SnomedDescription, T> predicateFactory) {

    Map<String, SnomedDescription> uniqueMap = Maps.transformValues(descriptionsByConceptId.asMap(),
            new ExtractBestFunction<T>(orderedValues, predicateFactory));
    return ImmutableMap.copyOf(Maps.filterValues(uniqueMap, Predicates.notNull()));
}

From source file:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

private void updatePrimaryWellConcentration(Plate plate) {
    Map<String, Object> properties = Maps.newHashMap();
    properties.put("plateNumber", plate.getPlateNumber());
    properties.put("libraryWellType", LibraryWellType.EXPERIMENTAL);
    List<Well> wells = _dao.findEntitiesByProperties(Well.class, properties);
    ConcentrationStatistics concentrationStatistics = plate.getConcentrationStatistics();
    for (Well well : wells) {
        if (well.getMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
        }//w  w w.  ja v  a2s.  co  m
        if (well.getMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
        }
    }

    Map<BigDecimal, Integer> mgMlCounts = Maps.transformValues(Multimaps.index(
            Lists.newArrayList(Iterators.filter(wells.iterator(),
                    Predicates.compose(Predicates.notNull(), Well.ToMgMlConcentration))),
            Well.ToMgMlConcentration).asMap(), CollectionSize);

    if (!mgMlCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMgMlConcentration(findMaxByValueThenKey(mgMlCounts).getKey());

    Map<MolarConcentration, Integer> molarCounts = Maps.transformValues(Multimaps.index(
            Lists.newArrayList(Iterators.filter(wells.iterator(),
                    Predicates.compose(Predicates.notNull(), Well.ToMolarConcentration))),
            Well.ToMolarConcentration).asMap(), CollectionSize);

    if (!molarCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMolarConcentration(findMaxByValueThenKey(molarCounts).getKey());
}

From source file:nl.minbzk.dwr.zoeken.enricher.service.EnricherService.java

/**
 * Reconstruct the import envelope so existing code can be used.
 *
 * @param envelope//w ww.  j av a  2s . c  o m
 * @param value
 * @param schemaField
 * @throws IllegalStateException if field of enricher document can not be mapped to import envelope.
 */
private void mapEnricherDocumentToImportEnvelope(final ImportEnvelope envelope, final Object value,
        final String schemaField) {
    Map<String, List<String>> envelopeFields = envelope.getFields();
    if (schemaField.equals("*") && value instanceof Map) {
        @SuppressWarnings("unchecked")
        Map<String, String> values = (Map<String, String>) value;
        Map<String, List<String>> transformedValues = Maps.transformValues(values,
                new Function<String, List<String>>() {
                    @Override
                    public List<String> apply(String s) {
                        return Lists.newArrayList(s);
                    }
                });
        // create new map to avoid lazy evaluation of function
        envelopeFields.putAll(Maps.newHashMap(transformedValues));
    } else if (value instanceof List) {
        @SuppressWarnings("unchecked")
        List<String> values = (List<String>) value;
        envelopeFields.put(schemaField, values);
    } else if (value instanceof Date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        envelope.setSingleValue(schemaField, dateFormat.format(value));
    } else if (value instanceof Integer) {
        envelope.setSingleValue(schemaField, value.toString());
    } else if (value instanceof String) {
        envelope.setSingleValue(schemaField, (String) value);
    } else {
        throw new IllegalStateException("Can not apply value '" + value + "' type for schemaField "
                + schemaField + " to import envelope");
    }
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

/**
 * Perform submit rollback with the caches and empty rollback transactions for every node
 */// www .j  a  v  a  2  s .co  m
private CheckedFuture<Void, DTxException.RollbackFailedException> rollbackUponCommitFailure(
        final Map<InstanceIdentifier<?>, PerNodeTxState> commitStatus) {

    Map<InstanceIdentifier<?>, CachingReadWriteTx> perNodeCache = new HashMap<>();

    for (DTXLogicalTXProviderType type : this.perNodeTransactionsbyLogicalType.keySet()) {
        Map<InstanceIdentifier<?>, CachingReadWriteTx> tmpMap = this.perNodeTransactionsbyLogicalType.get(type);
        perNodeCache.putAll(tmpMap);
    }

    Rollback rollback = new RollbackImpl();
    final ListenableFuture<Void> rollbackFuture = rollback.rollback(perNodeCache,
            Maps.transformValues(commitStatus, new Function<PerNodeTxState, ReadWriteTransaction>() {
                @Nullable
                @Override
                public ReadWriteTransaction apply(@Nullable final PerNodeTxState input) {
                    return input.getRollbackTx();
                }
            }));

    return Futures.makeChecked(rollbackFuture, new Function<Exception, DTxException.RollbackFailedException>() {
        @Nullable
        @Override
        public DTxException.RollbackFailedException apply(@Nullable final Exception input) {
            return new DTxException.RollbackFailedException(input);
        }
    });
}