List of usage examples for org.apache.commons.lang3.tuple Pair getValue
@Override
public R getValue()
Gets the value from this pair.
This method implements the Map.Entry interface returning the right element as the value.
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);// ww w.j a v a 2s . c om 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()) {/* w w w . ja v a 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());// www.j a va 2 s.c om 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 ww. j av 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;/* w w w. j a v a 2 s.c om*/ 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)); }/*from w ww .jav a 2 s.c o m*/ } 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); }
From source file:org.phenotips.data.internal.controller.SimpleNamedData.java
/** * Shortcut method for getting a value from this list, the first one where the key is equal to the requested name. * //from w w w.j a va 2 s . c o m * @param name the name of the entry to retrieve * @return the value found in the pair with the key equal to the requested name; if more than one such pairs exists, * the value from the first one is returned; if no such pair exists, {@code null} is returned */ public T get(String name) { for (Pair<String, T> entry : this) { if (StringUtils.equals(entry.getKey(), name)) { return entry.getValue(); } } return null; }
From source file:org.shaman.terrain.vegetation.ImpositorCreator.java
@Override public void simpleInitApp() { File folder = new File(OUTPUT_FOLDER); if (folder.exists()) { assert (folder.isDirectory()); } else {//from w w w.j ava 2s . c o m folder.mkdir(); } List<TreeInfo> trees = new ArrayList<>(); List<String> errors = new ArrayList<>(); //collect input MultiMap<Biome, Pair<String, Float>> treeDef = new MultiValueMap<>(); Map<String, Float> probabilities = new HashMap<>(); try (BufferedReader in = new BufferedReader(new FileReader(TREE_DEF_FILE))) { in.readLine(); //skip head while (true) { String line = in.readLine(); if (line == null) break; String[] parts = line.split(";"); Biome biome = Biome.valueOf(parts[0]); String treeName = parts[1]; float prob = Float.parseFloat(parts[2]) / 100f; treeDef.put(biome, new ImmutablePair<>(treeName, prob)); Float p = probabilities.get(treeName); if (p == null) { p = prob; } else { p += prob; } probabilities.put(treeName, p); } } catch (IOException ex) { Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex); } LOG.info("TreeDef: " + treeDef); LOG.info("TreeProb: " + probabilities); //create trees treeCreation: for (Map.Entry<String, Float> entry : probabilities.entrySet()) { try { String treeName = entry.getKey(); List<TreeInfo> treeInfos = new ArrayList<>(); float prob = entry.getValue(); if (prob <= MAX_PROP) { TreeInfo info = createTree(null, treeName, 0, 1); if (info != null) { treeInfos.add(info); } else { continue treeCreation; } } else { int n = (int) Math.ceil(prob / MAX_PROP); float p = prob / n; for (int i = 0; i < n; ++i) { TreeInfo info = createTree(null, treeName, i, p); if (info != null) { treeInfos.add(info); } else { continue treeCreation; } } } //create tree infos for (Map.Entry<Biome, Object> treeDefE : treeDef.entrySet()) { for (Pair<String, Float> v : (Collection<Pair<String, Float>>) treeDefE.getValue()) { if (treeName.equals(v.getKey())) { for (TreeInfo i : treeInfos) { TreeInfo i2 = i.clone(); i2.biome = treeDefE.getKey(); i2.probability = v.getValue() / treeInfos.size(); trees.add(i2); } } } } } catch (IOException ex) { Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("trees:"); for (TreeInfo t : trees) { System.out.println(" " + t); } LOG.log(Level.INFO, "save tree infos, {0} trees in total", trees.size()); try (ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(TREE_DATA_FILE)))) { out.writeObject(trees); } catch (IOException ex) { Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex); } LOG.info("done"); stop(); }
From source file:org.silverpeas.core.io.temp.LastModifiedDateFileTask.java
/** * Process all the requests. This method should be private but is already declared public in * the/*from ww w. j ava 2 s .c o m*/ * base class Thread. */ @Override public void run() { Pair<File, Long> pair = nextRequest(); // The loop condition must be verified on a private attribute of run method (not on the static // running attribute) in order to avoid concurrent access. while (pair != null) { CacheServiceProvider.clearAllThreadCaches(); /* * Each request is processed out of the synchronized block so the others threads (which put * the requests) will not be blocked. */ try { File currentFile = pair.getKey(); Long lastModifiedDate = pair.getValue(); if (currentFile.isFile()) { setLastModifiedDate(currentFile, lastModifiedDate); } else if (currentFile.isDirectory()) { for (File file : FileUtils.listFilesAndDirs(currentFile, FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())) { setLastModifiedDate(file, lastModifiedDate); } } } catch (Exception e) { SilverLogger.getLogger(e); } // Getting the next request if any. pair = nextRequest(); } }
From source file:org.silverpeas.core.io.temp.TestLastModifiedDateFileTask.java
@SuppressWarnings("ConstantConditions") @Test// w ww.j a v a 2s.c o m public void verifyLastModifiedDate() throws Exception { List<File> files = new ArrayList<File>(); File fileTest = new File(tempPath, "file.txt"); FileUtils.touch(fileTest); files.add(fileTest); fileTest = new File(tempPath, "folder"); fileTest.mkdirs(); files.add(fileTest); fileTest = new File(fileTest, "file1.txt"); FileUtils.touch(fileTest); files.add(fileTest); fileTest = new File(fileTest.getParentFile(), "file2.txt"); FileUtils.touch(fileTest); files.add(fileTest); fileTest = new File(fileTest.getParentFile(), "otherFolder"); fileTest.mkdirs(); files.add(fileTest); fileTest = new File(fileTest, "otherFile1.txt"); FileUtils.touch(fileTest); files.add(fileTest); fileTest = new File(fileTest.getParentFile(), "otherFile2.txt"); FileUtils.touch(fileTest); files.add(fileTest); Thread.sleep(200); long oneSecondAfterFileCreation = System.currentTimeMillis(); List<Pair<File, Long>> fileLastModifiedDate = new ArrayList<Pair<File, Long>>(); for (File file : files) { fileLastModifiedDate.add(Pair.of(file, file.lastModified())); } for (Pair<File, Long> fileOrFolder : fileLastModifiedDate) { assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(), is(fileOrFolder.getValue())); assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(), lessThan(oneSecondAfterFileCreation)); } Thread.sleep(1001); File[] tempRootFiles = tempPath.listFiles(); assertThat(tempRootFiles, arrayWithSize(2)); for (File tempRootFile : tempRootFiles) { LastModifiedDateFileTask.addFile(tempRootFile); } long l = 0; while (LastModifiedDateFileTask.isRunning()) { l++; } assertThat("This assertion shows that the thread stops after all the files are performed", l, greaterThan(0l)); Logger.getAnonymousLogger().info(MessageFormat .format("Calling LastModifiedDateFileThread.isRunning() {0} times", String.valueOf(l))); for (Pair<File, Long> fileOrFolder : fileLastModifiedDate) { assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(), greaterThan(fileOrFolder.getValue())); assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(), greaterThan(oneSecondAfterFileCreation)); } }