Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:org.openhim.mediator.fhir.FhirProxyHandler.java

private List<Pair<String, String>> copyParams(List<Pair<String, String>> params) {
    List<Pair<String, String>> copy = new ArrayList<>();
    for (Pair<String, String> param : params) {
        if ("_format".equalsIgnoreCase(param.getKey())) {
            continue;
        }//from   ww w. j  a v a  2s  .  co  m

        copy.add(param);
    }
    return copy;
}

From source file:org.openhim.mediator.fhir.FhirProxyHandler.java

private String determineClientContentType() {
    // first check for Accept header
    String accept = request.getHeaders().get("Accept");
    if (accept != null && !"*/*".equals(accept)) {
        return accept;
    }/*from w w w .  ja v  a2s.  c  o m*/

    // secondly for _format param
    for (Pair<String, String> param : request.getParams()) {
        if (param.getKey().equals("_format")) {
            return param.getValue();
        }
    }

    // thirdly check for the format the client sent content with
    String contentType = request.getHeaders().get("Content-Type");
    if (contentType != null) {
        return contentType.contains("json") ? Constants.FHIR_MIME_JSON : Constants.FHIR_MIME_XML;
    }

    // else use JSON as a default
    return Constants.FHIR_MIME_JSON;
}

From source file:org.openrepose.core.services.ratelimit.cache.UserRateLimit.java

@Override
public UserRateLimit applyPatch(Patch patch) {
    HashMap<String, CachedRateLimit> returnLimits = new HashMap<String, CachedRateLimit>();
    Pair<ConfiguredRatelimit, CachedRateLimit> lowestLimit = null;

    for (Pair<String, ConfiguredRatelimit> limitEntry : patch.getLimitMap()) {
        CachedRateLimit rateLimit = adjustLimit(limitEntry);
        returnLimits.put(limitEntry.getKey(), rateLimit);
        if (lowestLimit == null || (rateLimit.maxAmount()
                - rateLimit.amount() < lowestLimit.getValue().maxAmount() - lowestLimit.getValue().amount())) {
            lowestLimit = Pair.of(limitEntry.getValue(), rateLimit);
        }//ww w . j a v  a 2 s.c o m
        if (rateLimit.amount() > rateLimit.maxAmount())
            break;
    }

    return new UserRateLimit(returnLimits, lowestLimit);
}

From source file:org.openrepose.core.services.ratelimit.cache.UserRateLimit.java

private CachedRateLimit adjustLimit(Pair<String, ConfiguredRatelimit> limitEntry) {
    CachedRateLimit returnRateLimit;/*from w w  w  . j a va 2s .  c o m*/

    while (true) {
        CachedRateLimit newRateLimit = new CachedRateLimit(limitEntry.getValue(), 1);
        CachedRateLimit oldRateLimit = limitMap.putIfAbsent(limitEntry.getKey(), newRateLimit);

        if (oldRateLimit == null) {
            return newRateLimit;
        }

        if ((System.currentTimeMillis() - oldRateLimit.timestamp()) > oldRateLimit.unit()) {
            returnRateLimit = newRateLimit;
        } else {
            returnRateLimit = new CachedRateLimit(limitEntry.getValue(), oldRateLimit.amount() + 1,
                    oldRateLimit.timestamp());
        }

        if (limitMap.replace(limitEntry.getKey(), oldRateLimit, returnRateLimit)) {
            return returnRateLimit;
        }
    }
}

From source file:org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.java

private void determineGlobalShadowOrder() {
    // Topological sorting with Kahn's algorithm
    List<Pair<ShadowVariableDescriptor<Solution_>, Integer>> pairList = new ArrayList<>();
    Map<ShadowVariableDescriptor<Solution_>, Pair<ShadowVariableDescriptor<Solution_>, Integer>> shadowToPairMap = new HashMap<>();
    for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
        for (ShadowVariableDescriptor<Solution_> shadow : entityDescriptor
                .getDeclaredShadowVariableDescriptors()) {
            int sourceSize = shadow.getSourceVariableDescriptorList().size();
            Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = MutablePair.of(shadow, sourceSize);
            pairList.add(pair);// www. ja  v  a 2  s.  c  o m
            shadowToPairMap.put(shadow, pair);
        }
    }
    for (EntityDescriptor<Solution_> entityDescriptor : entityDescriptorMap.values()) {
        for (GenuineVariableDescriptor<Solution_> genuine : entityDescriptor
                .getDeclaredGenuineVariableDescriptors()) {
            for (ShadowVariableDescriptor<Solution_> sink : genuine.getSinkVariableDescriptorList()) {
                Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink);
                sinkPair.setValue(sinkPair.getValue() - 1);
            }
        }
    }
    int globalShadowOrder = 0;
    while (!pairList.isEmpty()) {
        pairList.sort(Comparator.comparingInt(Pair::getValue));
        Pair<ShadowVariableDescriptor<Solution_>, Integer> pair = pairList.remove(0);
        ShadowVariableDescriptor<Solution_> shadow = pair.getKey();
        if (pair.getValue() != 0) {
            if (pair.getValue() < 0) {
                throw new IllegalStateException("Impossible state because the shadowVariable ("
                        + shadow.getSimpleEntityAndVariableName()
                        + ") can not be used more as a sink than it has sources.");
            }
            throw new IllegalStateException("There is a cyclic shadow variable path"
                    + " that involves the shadowVariable (" + shadow.getSimpleEntityAndVariableName()
                    + ") because it must be later than its sources (" + shadow.getSourceVariableDescriptorList()
                    + ") and also earlier than its sinks (" + shadow.getSinkVariableDescriptorList() + ").");
        }
        for (ShadowVariableDescriptor<Solution_> sink : shadow.getSinkVariableDescriptorList()) {
            Pair<ShadowVariableDescriptor<Solution_>, Integer> sinkPair = shadowToPairMap.get(sink);
            sinkPair.setValue(sinkPair.getValue() - 1);
        }
        shadow.setGlobalShadowOrder(globalShadowOrder);
        globalShadowOrder++;
    }
}

From source file:org.optaplanner.core.impl.partitionedsearch.scope.PartitionChangeMove.java

@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
    for (Map.Entry<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> entry : changeMap
            .entrySet()) {/* ww  w . java  2 s .co  m*/
        GenuineVariableDescriptor<Solution_> variableDescriptor = entry.getKey();
        for (Pair<Object, Object> pair : entry.getValue()) {
            Object entity = pair.getKey();
            Object value = pair.getValue();
            scoreDirector.changeVariableFacade(variableDescriptor, entity, value);
        }
    }
}

From source file:org.optaplanner.core.impl.partitionedsearch.scope.PartitionChangeMove.java

@Override
public PartitionChangeMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirector) {
    Map<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> destinationChangeMap = new LinkedHashMap<>(
            changeMap.size());/*from ww  w  . j  a  va  2s .  co  m*/
    for (Map.Entry<GenuineVariableDescriptor<Solution_>, List<Pair<Object, Object>>> entry : changeMap
            .entrySet()) {
        GenuineVariableDescriptor<Solution_> variableDescriptor = entry.getKey();
        List<Pair<Object, Object>> originPairList = entry.getValue();
        List<Pair<Object, Object>> destinationPairList = new ArrayList<>(originPairList.size());
        for (Pair<Object, Object> pair : originPairList) {
            Object originEntity = pair.getKey();
            Object destinationEntity = destinationScoreDirector.lookUpWorkingObject(originEntity);
            if (destinationEntity == null && originEntity != null) {
                throw new IllegalStateException("The destinationEntity (" + destinationEntity
                        + ") cannot be null if the originEntity (" + originEntity + ") is not null.");
            }
            Object originValue = pair.getValue();
            Object destinationValue = destinationScoreDirector.lookUpWorkingObject(originValue);
            if (destinationValue == null && originValue != null) {
                throw new IllegalStateException("The destinationEntity (" + destinationEntity
                        + ")'s destinationValue (" + destinationValue + ") cannot be null if the originEntity ("
                        + originEntity + ")'s originValue (" + originValue + ") is not null.\n"
                        + "Maybe add the originValue (" + originValue + ") of class (" + originValue.getClass()
                        + ") as problem fact in the planning solution with a "
                        + ProblemFactCollectionProperty.class.getSimpleName() + " annotation.");
            }
            destinationPairList.add(Pair.of(destinationEntity, destinationValue));
        }
        destinationChangeMap.put(variableDescriptor, destinationPairList);
    }
    return new PartitionChangeMove<>(destinationChangeMap, partIndex);
}

From source file:org.optaplanner.core.impl.solver.termination.UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination.java

@Override
public void stepEnded(AbstractStepScope stepScope) {
    if (stepScope.getBestScoreImproved()) {
        DefaultSolverScope solverScope = stepScope.getPhaseScope().getSolverScope();
        long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis();
        Score bestScore = solverScope.getBestScore();
        for (Iterator<Pair<Long, Score>> it = bestScoreImprovementHistoryQueue.iterator(); it.hasNext();) {
            Pair<Long, Score> bestScoreImprovement = it.next();
            Score scoreDifference = bestScore.subtract(bestScoreImprovement.getValue());
            if (scoreDifference.compareTo(unimprovedScoreDifferenceThreshold) >= 0) {
                it.remove();// w  w w .ja v a  2s .  c o  m
                long safeTimeMillis = bestScoreImprovement.getKey() + unimprovedTimeMillisSpentLimit;
                solverSafeTimeMillis = safeTimeMillis;
                phaseSafeTimeMillis = safeTimeMillis;
            } else {
                break;
            }
        }
        bestScoreImprovementHistoryQueue.add(Pair.of(bestSolutionTimeMillis, bestScore));
    }
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingGenerator.java

private void createRoomList(ConferenceSolution solution, int roomListSize) {
    final int roomsPerFloor = 12;
    List<Room> roomList = new ArrayList<>(roomListSize);
    for (int i = 0; i < roomListSize; i++) {
        Room room = new Room();
        room.setId((long) i);
        room.setName("R " + ((i / roomsPerFloor * 100) + (i % roomsPerFloor) + 1));
        room.setCapacity((1 + random.nextInt(100)) * 10);
        TalkType talkType;//  ww w . ja  va  2 s.  c  o m
        if (i % 5 == 4) {
            talkType = labTalkType;
        } else {
            talkType = breakoutTalkType;
        }
        talkType.getCompatibleRoomSet().add(room);
        room.setTalkTypeSet(Collections.singleton(talkType));
        room.setUnavailableTimeslotSet(new LinkedHashSet<>());
        Set<String> tagSet = new LinkedHashSet<>(roomTagProbabilityList.size());
        for (Pair<String, Double> roomTagProbability : roomTagProbabilityList) {
            if (i == 0 || i == 4 || random.nextDouble() < roomTagProbability.getValue()) {
                tagSet.add(roomTagProbability.getKey());
            }
        }
        room.setTagSet(tagSet);
        logger.trace("Created room with name ({}) and tags ({}).", room.getName(), tagSet);
        roomList.add(room);
    }
    solution.setRoomList(roomList);
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingGenerator.java

private void createSpeakerList(ConferenceSolution solution, int speakerListSize) {
    List<Speaker> speakerList = new ArrayList<>(speakerListSize);
    speakerNameGenerator.predictMaximumSizeAndReset(speakerListSize);
    for (int i = 0; i < speakerListSize; i++) {
        Speaker speaker = new Speaker();
        speaker.setId((long) i);
        speaker.setName(speakerNameGenerator.generateNextValue());
        Set<Timeslot> unavailableTimeslotSet;
        List<Timeslot> timeslotList = solution.getTimeslotList();
        if (random.nextDouble() < 0.10) {
            if (random.nextDouble() < 0.25) {
                // No mornings
                unavailableTimeslotSet = timeslotList.stream().filter(
                        timeslot -> timeslot.getStartDateTime().toLocalTime().isBefore(LocalTime.of(12, 0)))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else if (random.nextDouble() < 0.25) {
                // No afternoons
                unavailableTimeslotSet = timeslotList.stream().filter(
                        timeslot -> !timeslot.getStartDateTime().toLocalTime().isBefore(LocalTime.of(12, 0)))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else if (random.nextDouble() < 0.25) {
                // Only 1 day available
                LocalDate availableDate = timeslotList.get(random.nextInt(timeslotList.size())).getDate();
                unavailableTimeslotSet = timeslotList.stream()
                        .filter(timeslot -> !timeslot.getDate().equals(availableDate))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            } else {
                unavailableTimeslotSet = timeslotList.stream().filter(timeslot -> random.nextDouble() < 0.10)
                        .collect(Collectors.toCollection(LinkedHashSet::new));
            }/* w  w w  .  ja va 2s  . c  om*/
        } else {
            unavailableTimeslotSet = new LinkedHashSet<>(timeslotList.size());
        }
        speaker.setUnavailableTimeslotSet(unavailableTimeslotSet);
        speaker.setRequiredTimeslotTagSet(new LinkedHashSet<>());
        speaker.setPreferredTimeslotTagSet(new LinkedHashSet<>());
        speaker.setProhibitedTimeslotTagSet(new LinkedHashSet<>());
        speaker.setUndesiredTimeslotTagSet(new LinkedHashSet<>());
        Set<String> requiredRoomTagSet = new LinkedHashSet<>();
        for (Pair<String, Double> roomTagProbability : roomTagProbabilityList) {
            if (random.nextDouble() < roomTagProbability.getValue() / 20.0) {
                requiredRoomTagSet.add(roomTagProbability.getKey());
            }
        }
        speaker.setRequiredRoomTagSet(requiredRoomTagSet);
        Set<String> preferredRoomTagSet = new LinkedHashSet<>();
        for (Pair<String, Double> roomTagProbability : roomTagProbabilityList) {
            if (random.nextDouble() < roomTagProbability.getValue() / 10.0) {
                preferredRoomTagSet.add(roomTagProbability.getKey());
            }
        }
        speaker.setPreferredRoomTagSet(preferredRoomTagSet);
        speaker.setProhibitedRoomTagSet(new LinkedHashSet<>());
        speaker.setUndesiredRoomTagSet(new LinkedHashSet<>());
        logger.trace("Created speaker with name ({}).", speaker.getName());
        speakerList.add(speaker);
    }
    solution.setSpeakerList(speakerList);
}