Example usage for com.google.common.collect ListMultimap replaceValues

List of usage examples for com.google.common.collect ListMultimap replaceValues

Introduction

In this page you can find the example usage for com.google.common.collect ListMultimap replaceValues.

Prototype

@Override
List<V> replaceValues(K key, Iterable<? extends V> values);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.tinspx.util.net.Cookies.java

/**
 * Fixes the Cookie and Cookie2 headers to ensure there is only one mapping
 * for each cookie header. Changes are made directly in the provided map.
 * <p>//from   w w  w. j  a va 2 s .co  m
 * If there are multiple mappings to either the Cookie or Cookie2 header,
 * they are combined into a single String delimited by the String "; "
 * (semicolon followed by space).
 *
 * @param headers the existing headers to fix
 * @return true if {@code headers} was modified
 */
public static boolean fixCookieHeaders(ListMultimap<String, String> headers) {
    boolean modified = false;
    List<String> h = headers.get(HttpHeaders.COOKIE);
    if (h.size() > 1) {
        headers.replaceValues(HttpHeaders.COOKIE, toSingleCookieList(h));
        modified = true;
    }
    h = headers.get(COOKIE2);
    if (h.size() > 1) {
        headers.replaceValues(COOKIE2, toSingleCookieList(h));
        modified = true;
    }
    return modified;
}

From source file:com.tinspx.util.net.Cookies.java

/**
 * Adds cookie headers to {@code headers}. {@code header} is the name of the
 * header and should be "Cookie" or "Cookie2", but that is not a
 * requirement. {@code values} are the header values associated with
 * {@code header}. These values are added to {@code headers} as a
 * <i>single</i> entry. If there are multiple values in {@code values}, they
 * are combined into a single String delimited by the String "; " (semicolon
 * followed by space). Any values associated with the key {@code header} in
 * {@code headers} are replaced.//from ww w.j  a va 2 s  . c  o m
 * <p>
 * {@code values} may be null or empty. If this is the case, no changes are
 * made to {@code headers} and false is returned. If changes were made to
 * {@code headers} true is returned.
 *
 * @see #toSingleCookieList(java.util.List)
 * @param headers the headers ListMultimap to update
 * @param header the name of the header, will be the key used to update
 * {@code headers}
 * @param values the String values associated with {@code header} that will
 * be combined into a single entry
 * @return true if {@code headers} was modified
 */
public static boolean addFixed(ListMultimap<String, String> headers, String header,
        @Nullable List<String> values) {
    if (values == null || values.isEmpty()) {
        return false;
    }
    headers.replaceValues(header, CollectUtils.iterable(toSingleCookieString(values)));
    return true;
}

From source file:org.glowroot.agent.model.TraceEntryComponent.java

public List<Trace.Entry> toProto(long captureTick,
        Multimap<TraceEntryImpl, TraceEntryImpl> asyncRootTraceEntries) {
    if (captureTick < startTick) {
        return ImmutableList.of();
    }// w w w.ja  va  2s  .c  om
    boolean completed = this.completed;
    if (completed && endTick < captureTick) {
        completed = false;
    }
    ListMultimap<TraceEntryImpl, TraceEntryImpl> parentChildMap = ArrayListMultimap.create();
    TraceEntryImpl entry = rootEntry.getNextTraceEntry();
    // filter out entries that started after the capture tick
    // checking completed is short circuit optimization for the common case
    while (entry != null && (completed || Tickers.lessThanOrEqual(entry.getStartTick(), captureTick))) {
        // checkNotNull is safe because only the root entry has null parent
        TraceEntryImpl parentTraceEntry = checkNotNull(entry.getParentTraceEntry());
        parentChildMap.put(parentTraceEntry, entry);
        entry = entry.getNextTraceEntry();
    }
    // merge in async trace entry roots
    for (Entry<TraceEntryImpl, Collection<TraceEntryImpl>> entries : asyncRootTraceEntries.asMap().entrySet()) {
        TraceEntryImpl parentTraceEntry = entries.getKey();
        List<TraceEntryImpl> childTraceEntries = Lists.newArrayList(parentChildMap.get(parentTraceEntry));
        for (TraceEntryImpl asyncRootTraceEntry : entries.getValue()) {
            TraceEntryImpl loopEntry = asyncRootTraceEntry;
            while (loopEntry != null
                    && (completed || Tickers.lessThanOrEqual(loopEntry.getStartTick(), captureTick))) {
                TraceEntryImpl loopParentEntry = loopEntry.getParentTraceEntry();
                if (loopParentEntry == null) {
                    childTraceEntries.add(loopEntry);
                } else {
                    parentChildMap.put(loopParentEntry, loopEntry);
                }
                loopEntry = loopEntry.getNextTraceEntry();
            }
        }
        childTraceEntries = TraceEntryImpl.orderingByStartTick.sortedCopy(childTraceEntries);
        parentChildMap.replaceValues(parentTraceEntry, childTraceEntries);
    }
    return getProtobufChildEntries(rootEntry, parentChildMap, startTick, captureTick);
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRaceLapsData.java

@Override
protected List<Pilot> calculateRaceLapsInOrder(Race race, Map<Pilot, Integer> laps) {
    ListMultimap<Integer, Pilot> raceOrder = ArrayListMultimap.create(EXPECTED_MAXIMUM_LAPS,
            scores.getPilots().size());//from  ww  w.java2  s. c o  m

    extractRaceLaps(race, laps, raceOrder, null);

    // Get penalties for each pilot
    ListMultimap<Pilot, Penalty> cancelLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    ListMultimap<Pilot, Penalty> adjustLaps = ArrayListMultimap.create(EXPECTED_MAXIMUM_PENALTIES,
            scores.getPilots().size());
    for (RaceAttendee attendee : Maps.filterKeys(race.getAttendees(), Predicates.in(scores.getPilots()))
            .values()) {
        for (Penalty penalty : Iterables.concat(Ordering.natural().immutableSortedCopy(attendee.getPenalties()),
                scores.getSimulatedRacePenalties(attendee.getPilot(), race))) {
            if (penalty.getValue() != 0) {
                switch (penalty.getType()) {
                case CANCEL_LAPS:
                    cancelLaps.put(attendee.getPilot(), penalty);
                    break;

                case ADJUST_LAPS:
                    adjustLaps.put(attendee.getPilot(), penalty);
                    break;

                default:
                    break;
                }
            }
        }
    }

    // Apply lap cancellation penalties
    if (!cancelLaps.isEmpty()) {
        final Multiset<Pilot> pilotLaps = HashMultiset.create(laps.size());

        for (Map.Entry<Pilot, Integer> pilotLapCount : laps.entrySet()) {
            pilotLaps.setCount(pilotLapCount.getKey(), pilotLapCount.getValue());
        }

        for (Map.Entry<Pilot, Penalty> entry : cancelLaps.entries()) {
            int value = entry.getValue().getValue();
            if (value > 0) {
                pilotLaps.remove(entry.getKey(), value);
            } else {
                pilotLaps.add(entry.getKey(), Math.abs(value));
            }
        }

        extractRaceLaps(race, laps, raceOrder, new Predicate<Pilot>() {
            @Override
            public boolean apply(@Nullable Pilot pilot) {
                return pilotLaps.remove(pilot);
            }
        });
    }

    // Save pilot order
    List<Pilot> origPilotOrder = getPilotOrder(raceOrder);
    SortedSet<Pilot> noLaps = new TreeSet<Pilot>(new PilotRaceNumberComparator());
    Set<Integer> changed = new HashSet<Integer>();

    // It is intentional that pilots can end up having 0 laps but be considered to have completed the race
    for (Map.Entry<Pilot, Penalty> entry : adjustLaps.entries()) {
        Pilot pilot = entry.getKey();
        int lapCount = laps.get(pilot);

        raceOrder.remove(lapCount, pilot);
        changed.add(lapCount);

        lapCount += entry.getValue().getValue();
        if (lapCount <= 0) {
            lapCount = 0;
            noLaps.add(pilot);
        }
        laps.put(pilot, lapCount);

        raceOrder.put(lapCount, pilot);
        changed.add(lapCount);
    }

    // Apply original pilot order
    if (!changed.isEmpty()) {
        origPilotOrder.addAll(noLaps);

        for (Integer lapCount : changed) {
            raceOrder.replaceValues(lapCount,
                    Ordering.explicit(origPilotOrder).immutableSortedCopy(raceOrder.get(lapCount)));
        }

        return getPilotOrder(raceOrder);
    } else {
        return origPilotOrder;
    }
}

From source file:eu.esdihumboldt.hale.common.align.merge.functions.JoinContext.java

/**
 * Apply information collected in the context to the cell.
 * //  ww w  .  j a  v  a  2  s  .co m
 * @param newCell the merged cell
 * @param log the cell log
 * @param migration the alignment migration
 */
public void apply(MutableCell newCell, AlignmentMigration migration, SimpleLog log) {
    ListMultimap<String, ParameterValue> params = ArrayListMultimap.create();

    /*
     * Order: Keep original order but replace entities w/ all matches
     */
    Set<TypeEntityDefinition> types = new LinkedHashSet<>();
    for (TypeEntityDefinition type : orgParameter.getTypes()) {
        List<TypeEntityDefinition> repl = replacements.get(type);
        if (repl.isEmpty()) {
            log.error("Could not find replacement for type {0} in join order", type);
            types.add(type);
        } else {
            for (TypeEntityDefinition replacement : repl) {
                Filter filter = typeFilters.get(replacement.getDefinition());
                if (filter != null) {
                    // apply filter
                    types.add(new TypeEntityDefinition(replacement.getDefinition(),
                            replacement.getSchemaSpace(), filter));
                } else {
                    types.add(replacement);
                }
            }
        }
    }

    /*
     * Conditions: (1) add conditions from matches and (2) add conditions
     * from original cell translated to new schema (via property mapping),
     * if they are not duplicates
     */
    Set<Pair<PropertyEntityDefinition, PropertyEntityDefinition>> cons = new LinkedHashSet<>();

    // add conditions from matches
    for (Cell match : joinMatches) {
        JoinParameter matchParameter = CellUtil.getFirstParameter(match, JoinFunction.PARAMETER_JOIN)
                .as(JoinParameter.class);
        for (JoinCondition condition : matchParameter.getConditions()) {
            cons.add(new Pair<>(condition.baseProperty, condition.joinProperty));
        }
    }

    // migrate original conditions
    Set<JoinCondition> migrated = orgParameter.getConditions().stream().map(condition -> {
        PropertyEntityDefinition baseProperty = processOriginalConditionProperty(condition.baseProperty,
                migration, log);
        PropertyEntityDefinition joinProperty = processOriginalConditionProperty(condition.joinProperty,
                migration, log);
        JoinCondition result = new JoinCondition(baseProperty, joinProperty);
        return result;
    }).collect(Collectors.toSet());
    for (JoinCondition condition : migrated) {
        if (!condition.baseProperty.getType().equals(condition.joinProperty.getType())) {
            // migrated condition may contain "loop" condition

            cons.add(new Pair<>(condition.baseProperty, condition.joinProperty));
        }
    }

    // add messages on dropped filter/conditions
    for (EntityDefinition stripped : strippedSources) {
        if (!AlignmentUtil.isDefaultEntity(stripped)) {
            String msg = "Conditions/contexts for an original source could not be transfered and were dropped: "
                    + MergeUtil.getContextInfoString(stripped);
            log.warn(msg);
        }
    }

    // all conditions
    Set<JoinCondition> conditions = new HashSet<>();
    for (Pair<PropertyEntityDefinition, PropertyEntityDefinition> condition : cons) {
        conditions
                .add(new JoinCondition(applyFilter(condition.getFirst()), applyFilter(condition.getSecond())));
    }

    JoinParameter newParam = new JoinParameter(new ArrayList<>(types), conditions);
    params.replaceValues(JoinFunction.PARAMETER_JOIN,
            Collections.singleton(new ParameterValue(Value.of(newParam))));

    // script (Groovy Join)

    // Use Groovy Join if original or match uses a script
    if (!scripts.isEmpty()) {
        boolean originalScript = scripts.size() == 1
                && GroovyJoin.ID.equals(newCell.getTransformationIdentifier());
        Text script;
        if (originalScript) {
            // use original script
            script = new Text(scripts.get(0).getSecond());

            // create annotation
            log.warn(
                    "The Groovy script from the original cell was reused, logic and references to sources are very likely not valid anymore.");
        } else {
            // dummy script with all original scripts
            newCell.setTransformationIdentifier(GroovyJoin.ID);

            script = buildScript(scripts);

            // create annotation
            log.warn(
                    "At least one source mapping used a Groovy script, the script could not be combined automatically and was replaced with a dummy script (old scripts are commented out). Please check how you can migrate the old functionality.");
        }

        params.replaceValues(GroovyConstants.PARAMETER_SCRIPT,
                Collections.singleton(new ParameterValue(Value.of(script))));
    }

    newCell.setTransformationParameters(params);
}